I have a django app with a page that shows a data table of text strings populated from a model.
Each string is a website url. I need to be able to click on any one of these rows and have that url string written to a text file.
What I have so far results in a ‘reverse’ error as soon as the server tries to load the home page.
Here is the model:
class Environment(models.Model):
url = models.CharField(max_length = 250, null=True,
blank=True)
def __str__(self):
return self.url
Here is the view for the home page, which displays a list of urls populated from the model:
def home(request):
envs = Environment.objects.all()
f = open('environment.txt', 'r')
file_content = f.read()
f.close()
context = {'title':'Home Page',
'year':datetime.now().year, 'envs':envs, 'file_content':file_content}
return render(request, 'app/home.html', context)
here is the view for the writing of the url text to the file:
def write_url_to_file(request, url):
with open('environment.txt', 'w') as file:
file.write(url)
file.close()
return redirect('app:home')
Here is the url pattern:
path(‘write-url/<str:url>/’, views.write_url_to_file, name=’write_url_to_file’),
Here is the template tag. The idea is to click a url to write it to a text file:
<table>
<tr>
<th>Environment</th>
</tr>
{% for env in envs %}
<tr>
<td><a href="{% url 'app:write_url_to_file' env.url %}">{{ env.url }}</a></td>
</tr>
{% endfor %}
I have tried various things such as changing the template tage to {% url ‘app:write_url_to_file’ url=env.url %}, but it still results in reverse error.
In the view I have also tried redirect(reverse(‘app:home’)) but still the same error on loading the home page.
Any advice would be greatly appreciated