Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I mark button as active based on the page I am at?
when a user clicks a tab I want that tab to show as active in blue. I can do it using if statements like the one I show on the code, but I would be repeating the code a LOT, so there has to be another way, could someone let me a hand please? The current if statement shows the profile page which is active <!-- This is saying: inherit everything from __base.html --> {% extends "storePage/partials/__base.html" %} <!-- Main base template which contains header and footer too --> {% load crispy_forms_tags %} <!-- To beautify the form at signup --> {% block body %} <div class="container bootstrap snippet"> <div class="row"> <div class="col-md-3"> <div class="list-group "> <label class="card-header">Personal Settings</label> {% if request.get_full_path == "/settings/profile/" %} <a href="{% url 'profile-settings' %}" class="list-group-item list-group-item-action active"><span class="fa fa-user"></span> Profile</a> {% endif %} <a href="{% url 'account-settings' %}" class="list-group-item list-group-item-action"><span class="fa fa-cog"></span> Account</a> <a href="{% url 'emails-settings' %}" class="list-group-item list-group-item-action"><i class="fas fa-envelope"></i> Emails</a> <a href="{% url 'billing-settings' %}" class="list-group-item list-group-item-action"><span class="fa fa-credit-card"></span> Billing</a> </div> </div> <!-- Center-right navBar--> <div class="col-md-9"> {% block settingsPageInfo %} {% endblock %} <!-- Here goes the user information on the profile page --> </div> </div> </div> {% endblock %} … -
Django refresh template with new values
I am trying to save checkbox inputs on a form, and when the user goes back to that page, they only view what checkboxes they viewed. Basically want one page to act as a form and display the new retrieved values. HTML <div class="checkbox"> {{ form.schedule }} {{ notifications.schedule }} <label>When you schedule a lesson</label> </div> <div class="checkbox"> {{ form.cancel }} {{ notifications.cancel }} <label>When a lesson is cancelled</label> </div> views.py @login_required def account_notifications(request): if request.method == 'POST': form = NotificationsForm(request.POST, instance=request.user.notifications) if form.is_valid(): notifications = form.save(commit=False) notifications.user = request.user notifications.save() return redirect('/student/dashboard') else: form = ProfileForm() form = NotificationsForm() context = {'form': form} return render(request, 'student/account_notifications.html', context) I am trying to submit the data on that form, and also retrieve it whenever the user goes back to it. -
How to get the image id via a button to use it in views.py?
I'm pretty new to django and coding in generall, I'm trying to build an Instagram clone.. so my question is.. how can I comment on a post that is on the newsfeed(list of all uploaded images by every user), without leaving the newsfeed? So my approach is to give every send button an id? or name? and somehow use it inside my views.py #views.py def newsfeed(request): images = Image.objects.all().order_by('-pub_date') if request.method == 'POST': c_form = CommentForm(request.POST) if c_form.is_valid(): new_comment = c_form.save(commit=False) new_comment.owner = request.user new_comment.image = #here should be something that points to the image i'm commenting on c_form.save() return redirect('upload_img:newsfeed') else: c_form = CommentForm() context = {'images_temp': images, 'c_form': c_form} return render(request, 'newsfeed.html', context) #models.py class Comment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1) image = models.ForeignKey(Image, on_delete=models.CASCADE, default=1) text = models.CharField(max_length=225) pub_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s comments on %s image' % (self.owner, self.image.owner) #newsfeed.html {% for image in images_temp %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ c_form|crispy }} <button name="{{ image.image }}" type="submit" class="btn btn-primary"><i class="fas fa-paper-plane"></i></button> </form> {% endfor %} -
Google API django
i want to use google calendar API for chatbot. I've searching in google API for using google calendar, but i still not understand. My question is, how can we give some link that refers to "Accept" My chatbot calendar, and after somebody "Accept", their calendar can syncronize with My chatbot calendar Thank you! -
Bad gateway error when loading large sklearn model. Django/Ubuntu/Gunicorn/Nginx
I just developed a machine learning driven python 2.7 application which essentially loads a sklearn model with joblib and predicts a given dataset. On local host the application works perfectly, but when I deploy the django application on digital ocean (Ubuntu 18., gunicorn, nginx) I get a bad gateway error. I found out that the error is being raised when the model is being loaded with joblib. What I noticed as well is that the application works perfectly when a model that has the size of 8000 bites is being loaded but that but that the bad gateway error is being raised when I try to load a model of 60000 bites. What I have tried is to resize the droplet in order to avoid that the error is being caused by a lack of computing resources, but I still get the error! Unfortunately, I have no clue how to tackle the problem. So I hope that you guys can help me to find a way to resolve this issue. I appreciate any help. Thanks in advance. Kind regards Marcel -
Edit home page on django, wagtail project on AWS
I've been asked to change something on homepage on site that is live, and it is hosted on AWS S3. It is Django project with Wagtail as CMS. I know my way around Django but not S3. Can someone explain me what to do to edit homepage.html -
How to embed images in blog post with React and Django
i'm developing a blog for a friend using React and Django, Now I have to develop the text editor that he's going to use to write the articles but I don't know what to do in case of he wanting to embed images(not uploading them to the backend but using a external source like imgur,etc) on the text field between paragraphs, I suppose that django is not going to accept an <img/> being posted to the database on a text field, so my question is: do i need to handle this on the frontend or in the backend? sorry if it is a dumb question but i've been thinking how to approach this and i can't find a way. models.py class Article(models.Model): title = models.CharField(max_length=150) text = models.TextField() created = models.DateTimeField(auto_now_add=True) -
zappa deployment: Getting [Errno 28] No space left on device: OSError. Cleaned the tmp files
Intro: I am deploying my django app using zappa on to AWS lambda. So far I have made several attempts. I feel like I may have just got it. However now I got [Errno 28] No space left on device: OSError I have so far done $ cd /tmp/ $ rm -r * This made my tmp folder empty However when I run my zappa deploy I am still getting the same error. I don't want to format my computer. Is there another way Below is my TraceBack [Errno 28] No space left on device: OSError Traceback (most recent call last): File "/var/task/handler.py", line 580, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 245, in lambda_handler handler = cls() File "/var/task/handler.py", line 102, in __init__ self.load_remote_project_archive(project_archive_path) File "/var/task/handler.py", line 174, in load_remote_project_archive t.extractall(project_folder) File "/var/lang/lib/python3.6/tarfile.py", line 2010, in extractall numeric_owner=numeric_owner) File "/var/lang/lib/python3.6/tarfile.py", line 2052, in extract numeric_owner=numeric_owner) File "/var/lang/lib/python3.6/tarfile.py", line 2122, in _extract_member self.makefile(tarinfo, targetpath) File "/var/lang/lib/python3.6/tarfile.py", line 2171, in makefile copyfileobj(source, target, tarinfo.size, ReadError, bufsize) File "/var/lang/lib/python3.6/tarfile.py", line 252, in copyfileobj dst.write(buf) OSError: [Errno 28] No space left on device Can anyone advise how I can fix this -
Django Form submission leads to 404 Error
When an user submits a form, I am receiving the following error: Page not found (404) Request Method: csrfmiddlewaretoken=uaL0Ogej2bd0oSaNLXYwu1CxSPWz6mcs0PuXiwM2mpe01VecK5IVBK40xvqcFCJF&views=0&likes=0&slug=&name=do+do+ahadalfjkdas%3Bldfjksal%3B12321&submit=Create+CategoryPOST Request URL: http://127.0.0.1:8000/rango/add_category/rango/add_category/ Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order: ^$ [name='index'] ^admin/ ^rango/ ^$ [name='index'] ^rango/ ^about/ [name='about'] ^rango/ ^category/(?P<category_name_slug>[\w\-]+)/$ [name='show_category'] ^rango/ ^page/(?P<page_name_slug>[\w\-]+)/$ [name='show_page'] ^rango/ ^add_category/$ [name='add_category'] The current path, rango/add_category/rango/add_category/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It seems like I am appending rango/add_category twice and not re-referring back to the index page. But I am not sure what I am overlooking. Here's the relevant template: <!-- created in c7 for form viewing--> <!DOCTYPE html> <html> <head> <title>Rango</title> </head> <body> <h1>Add a Category</h1> <div> <form id="category_form" method="post" action="rango/add_category/"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{hidden}} {% endfor %} {% for field in form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} {% endfor %} <input type="submit" name="submit" value="Create Category" /> </form> </div> </body> </html> And the relevant forms file: #file added c7, forms from django import forms from rango.models import Page, Category … -
how to get value of download button into my django view?
I have a download button in my HTML that has a href to a path on my system for the corresponding file. How can I load that path into my view when at user clicks download? Also this value is unique for each download button. Right now I have some HTML that looks like this. How do I grab the info from item.OutputPath into my view when clicked? <div class="dashboard-2"> <div class="tasks-finished"> <h1>Finished tasks</h1> </div> <div class="tasks-list"> <table> <tr> <th>Name</th> <th>Task ID</th> <th>Status</th> </tr> {% for item in query_finished %} <tr> <td>{{ item.TaskNavn }}</td> <td>{{ item.TaskID }}</td> <td><a href="{{ item.OutputPath }}">Download</a> </tr> {% endfor %} </table> </div> </div> If there's any other way that I can do this without exposing my system path in the href I would much prefer to know that. Thanks in advance. Additonal info: I need this value because i'm trying to save it as a variable to serve protected files using Nginx. -
How to create custom django urls e.g james.john.website.com
How do I create custom django urls like james.john.website.com that links to a users profile page. I created the link by concatenating words with python, however I can't seem to figure out how to get each custom url into urls.py and how to get each custom url to link to each users custom profile. TL:DR How do I get a custom url like samantha.harvey.website.com to return a users profile page? -
Django - modal form and resubmission on page reload
I have got a modal contact form. The form works fine, but the page reload resubmits previously entered values. view.py ... if request.POST: form = ContactForm(request.POST) if form.is_valid(): entry = form.save() form = ContactForm() c.update(locals()) return render(request, 'template.html', c ) ... template.html <form action="." method="post" id="contact-form"> ... </form> I tried to clear the form in the GET request. Form fields are cleared, but this does not prevent submission on the page reload. else: #request.GET form = ContactForm() c.update(locals()) return render(request, 'template.html', c ) I have seen many examples suggesting a redirect. I do understand this approach, but in case of a modal form I would like to avoid the redirect. How to prevent modal form re-submissions? Is the redirect really the only way? -
How to get the equalent of python [:-1] in django ORM?
I am writing a django application where I want to get all the items but last from a query. My query goes like this: objects = Model.objects.filter(name='alpha').order_by('rank')[:-1] but it throws out error: Assertion Error: Negative indexing not supported. Any idea where I am going wrong? Any suggestions will be appreciated. -
Applying highlighting effect to text through replace() (Django 2.1)
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results. Code for custom filter: register = template.Library() @register.filter @stringfilter def highlight(value, search_term): return value.replace(search_term, "<span class='highlight'>%s</span>" % search_term) The filter doesn't change the targeted word's CSS class into <span class='highlight'>. Instead, the output displayed text in the browser is literally <span class='highlight'>word</span>. E.g. "The most desired car brand right now is <span class='highlight'>Tesla</span>." How can I make it so that the replace() method actually changes the CSS class of the targeted word? -
How to solve Identity column missing Always error for oracle 11g, django 2.0.7?
I am using Django 2.0.7, Python 3.7 and Oracle 11g. I cannot change these configurations. Whenever I am trying to migrate my models, I always get the error, 'Missing ALWAYS' which is an error associated with Identity columns. I know that Identity columns were introduced from oracle 12. Is there a way to overcome this issue with the version requirements I have? -
How can I delete or download the needed document from folder by a clicking on webpage button?
Let's say the user cannot find the folder in the computer so it is easier to manage the folder files on webpage. I manage to show the folder file documents on webpage/Here is that webpage/, then I try to download or delete the needed document, but I get some errors. I try to use os.path.exists() and os.remove() to delete the document, but as I understand I do not create my urls pattern correctly, and do not pass the right argument to my html template. Here is my code: urls.py: .... path('edited_agreements/', views.delete_new_file, name='delete_new_file'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py def new_files_list(request): path = MEDIA_ROOT new_files_list = [] for file in os.listdir(path): if file.endswith('.doc') or file.endswith('.docx'): new_files_list.append(file) return render(request, 'uploads/new_files_list.html', { 'new_files': new_files_list }) def delete_new_file(request, path): if request.method == 'POST': file_path = os.path.join(MEDIA_ROOT, path) if os.path.exists(file_path): os.remove(file_path) return redirect('new_files_list') .html .... <tbody> {% for new_file in new_files %} <tr> <td>{{ new_file }}</td> <td> <form method="post" action="{{ new_file.path }}" target="_blank"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm">Download</button> </form> </td> <td> <form method="post" action="{{ new_file }}"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </td> </tr> {% endfor %} </tbody> .... When I click on delete I want the … -
Problems referencing model in function based view
As the title states, I'm having trouble referencing my account model in my cmsUserDetailEdit view. The site itself doesn't break, but it seems like its just not able to find the model, as all the placed where the model is referenced is empty. I've tried placing the account in the context. E.g: 'account': account, but without luck. views.py def cmsUserDetailEdit(request, pk): account = Account.objects.all() accounts = Account.objects.get(pk=pk) if request.method == 'POST': u_form = UserEditPersonalForm(request.POST, instance=accounts.user) a_form = AccountEditPersonalForm(request.POST, instance=accounts) if u_form.is_valid() and a_form.is_valid(): u_form.save() a_form.save() messages.success(request, f'Account updated') return redirect('/cms/test/') else: u_form = UserEditPersonalForm(instance=accounts.user) a_form = AccountEditPersonalForm(instance=accounts) context = { 'u_form': u_form, 'a_form': a_form, } return render(request, 'cms/users/cms-users-user-edit.html', context) cms-users-user-edit.html <div class="note-card-content"> <div class="content"> {{ account.note }} <!-- This part is empty --> </div> </div> -
Django Rest Framework ViewSets is returning selected records rather than all records in list view
I have a django application. I have one part of my app that is not working as I was expecting. As of now I am using the django rest framework view sets. What I want is two basically have 2 different list views in the same viewset. 1 that returns all of the accounts in the accountviewset and another list view that returns all of the accounts associated with a user based on the user foreignkey in the account model. The code below returns all the acccounts associated with a specific person, but I am not able to have a list view that returns all of the accounts in the database. class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() lookup_field = 'user__username' def list(self, request): queryset = Account.objects.all() serializer_class = AccountSerializer def get_object(self): return self.queryset.get(user__username=self.kwargs.get('username')) -
Django: Get queryset of nested objects in Retrieve API View
I'm creating a Django application with django-rest-framework and using djongo to connect to MongoDB. I have a nested model as such: class Group(models.Model): group_code = models.CharField( max_length=15, blank=False, unique=True ) users = models.ArrayModelField( model_container=User ) class User(models.Model): name = models.CharField( max_length=100 ) user_code = models.CharField( max_length=32, default=hex_uuid, editable=False ) class Meta: abstract = True I'm attempting to set up a view to retrieve a User at the following URL: urlpatterns = { url(r'^user/(?P<group_code>[\w]+)/(?P<user_code>[\w]+)/$', UserDetail.as_view(), name='user-detail') } Essentially, I want the view to display just the User's information instead of the Group's information. This didn't work, but is what I attempted: class UserDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = UserFullSerializer def get_queryset(self, *args, **kwargs): return Group.objects.get(team_code=self.kwargs['group_code']).users lookup_field = 'user_code' lookup_url_kwarg = 'user_code' However, users in this case is a normal list instead of a QuerySet. Therefore, the lookup_field attribute is not working correctly. Any thoughts on how to access the nested list users of type User as a QuerySet so that this view can work properly? -
django request.POST.get() returns nothing
Trying to get a users input from django forms using request.POST.get(). It doesn't return anything even thought the user submits something. django form <form action="" method="post" > {%csrf_token%} <input name="choosestorename" id="choosestorename" placeholder="Choose a store name" type="text"></input> </form> django views def dashboard(request): if request.method == "POST": choosestorename = request.post.get("choosestorename") print(choosestorename) -
How do I run my python command as a cron while loading my environment vars?
I'm using Python 3.7 with Django. I want to set up a cron job ("crontab -e") where I run davea$ /bin/bash -l -c 'cd /Users/davea/Documents/workspace/mainpage_project; ./venv/bin/activate; python manage.py runstats' However, upon running that, I get the error File "manage.py", line 14 ) from exc If I run cd /Users/davea/Documents/workspace/mainpage_project; ./venv/bin/activate; python manage.py runstats everything runs fine, but I want to load environment variables which is why I was trying the former command. Is there a way to fix the first command so that I can load my environment vars and also execute my script? Below is my "manage.py" file ... #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainpage_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc # line 14 execute_from_command_line(sys.argv) -
Reverse querry with different users error and how to restrict the users allowed
I'm quite new to django, I wanted to create a project model. I don't know how to make this restrictions on the ManyToManyField, etc... Only teachers can be either the director or a coordinator Only students can be student Both, students and teachers can be the author of the project Moreover, I get these errors and I don't know why doing what the hint does will help or what would it do: unihub.Project.director: (fields.E305) Reverse query name for 'Project.director' clashes with reverse query name for 'Project.student'. HINT: Add or change a related_name argument to the definition for 'Project.director' or 'Project.student'. class Project(models.Model): PENDING = 0 APROVED = 1 ONGOING = 2 COMPLETED = 3 STATUS_CHOICES = ( (PENDING, 'pending'), (APROVED, 'aproved'), (ONGOING, 'ongoing'), (COMPLETED, 'completed') ) # serial number project_id = models.AutoField(primary_key=True) # Basic fields title = models.CharField(max_length=50, blank=False) description = models.CharField(max_length=250, blank=False) content = models.TextField(blank=False) tags = models.ManyToManyField(Tag) status = models.CharField(choices = STATUS_CHOICES, default=PENDING, max_length=15) # Date fields date_posted = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) # People working on project author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) student = models.OneToOneField(User, null=True, on_delete=models.SET_NULL) director = models.ManyToManyField(User) coordinators = models.ManyToManyField(User) # Files files = models.ManyToManyField(File) -
How do I select information in other table based on the ID provided using a loop
Super new to django, working on my 1st test project. I have an app that's called customers. Inside of that, I have a few models. The 2 main, once I am trying to get to work right now, are Customer_Info, and Company_Info. On the template side I want to pull information in the for loop from both templates. Companies could have multiple customers (contacts). So inside of the customer info table, I am storing the company uuid they might belong to. Some customers would not have that ID as they are individuals and do not have a company association. Here are the 2 models. class Customer_Info(models.Model): #Name of the table id = models.AutoField(primary_key=True) cust_uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) first_name = models.CharField(max_length=32, blank=False) middle_name = models.CharField(max_length=32, blank=True) last_name = models.CharField(max_length=32, blank=False) phone = models.CharField(max_length=10, blank=False) email = models.CharField(max_length=64, blank=False) address_1 = models.CharField(max_length=64, blank=True, null=True) address_2 = models.CharField(max_length=64, blank=True, null=True) city = models.CharField(max_length=16, blank=True, null=True) state = models.CharField(max_length=2, blank=True, null=True) zipcode = models.IntegerField(blank=True, null=True) country = models.CharField(max_length=16, blank=True, null=True) company_uuid = models.ForeignKey('company_info', to_field='company_uuid', db_column='company_uuid', on_delete=models.PROTECT, blank=True, null=True) # miht need a nullable defaul https://docs.djangoproject.com/en/2.1/ref/models/fields/#foreignkey user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=False) # miht need a something else https://docs.djangoproject.com/en/2.1/ref/models/fields/#foreignkey date_added = models.DateTimeField(auto_now=True) def __str__(self): return … -
replace() method not working in custom template filter (Django 2.1)
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results. Search engine code in view.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) Custom template filter code: @register.filter @stringfilter def highlight(value, search_term): return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)) HTML template code with the filter highlight applied to article.Content: <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article }}</a></li> <p> {{ article.Content|highlight:search_term }} </p> {% endfor %} </ul> CSS code for <span class='highlight'>: .highlight {color:red;} I get no error message but I don't see the highlighted effects. I tried doing other things with value.replace() here but I don't see the effects either. I think the replace() method is not working here. Maybe search_term is not recognized. Any idea what's the issue? -
Session doesn't work after applying Django security recommendations
I ran python manage.py check --deploy and got the following recommendations: System check identified some issues: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W006) Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, so your pages will not be served with an 'x-content-type-options: nosniff' header. You should consider enabling this header to prevent the browser from identifying content types incorrectly. ?: (security.W007) Your SECURE_BROWSER_XSS_FILTER setting is not set to True, so your pages will not be served with an 'x-xss-protection: 1; mode=block' header. You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. ?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only …