Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wrong date time getting extracted in my Django project
I am currently inserting current timestamp in my postgresdb. As shown below, the date 19th feb got inserted. but when I got to Django shell and printed all the dates, its printing 18th feb. How can i solve this confusion. In my settings.py, current timezone is set to UTC and I cannot change that. Please suggest -
Django Forms rendering into HTML
Which system in Django is responsible for rendering a Form class instance into valid HTML? I cant seem to find any information on it -
Need help in Django 2x ,( FOREIGN KEY constraint failed )
hi everyone i made a simple modeland my problem is when i try to make a FOREIGN KEY in my model it shows me this error message , it would be awesome if you can help here is the code Model.py: from django.db import models from django.utils import timezone # Create your models here. class category(models.Model): title=models.CharField(max_length=100,default='') def __str__(self): return self.title class gigpost(models.Model): title=models.CharField(default='',max_length=100) Category=models.OneToOneField(category,on_delete=True,default='') published_at=models.DateTimeField(auto_now_add=True) description=models.TextField(default='',max_length=None) mainphoto=models.ImageField(default='') photo=models.FileField() def __str__(self): return self.title Admin.py from django.contrib import admin from .models import gigpost , category # Register your models here. admin.site.register(gigpost) admin.site.register(category) the error message : IntegrityError at /admin/gigpost/category/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/gigpost/category/add/ Django Version: 2.2.5 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: C:\Users\Madara\Miniconda3\envs\myEv\lib\site-packages\django\db\backends\base\base.py in _commit, line 240 Python Executable: C:\Users\Madara\Miniconda3\envs\myEv\python.exe Python Version: 3.7.6 Python Path: ['C:\\Users\\Madara\\Desktop\\empliya\\empliya', 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\python37.zip', 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\DLLs', 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib', 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv', 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib\\site-packages'] Server time: Tue, 18 Feb 2020 19:34:39 +0000 -
Generate unique string for each db object
I have a model where I need to create a UNIQUE string for each object in the db. I've made a function to generate the string, but I can create an object using the django admin once, and then the second time it will error out and say that the value is not unique. What can I do so Django just generates a new string if the previous one was used already? models.py def randomword(length): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length)) class Refferal(models.Model): email = models.EmailField(max_length=254, unique=True) coupon = models.CharField(default=randomword(4), primary_key=True, editable=False, max_length=4) count = models.IntegerField(default=0) Log output from when I try to create the second object using the admin The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner return view(request, *args, **kwargs) β¦ -
Where does SECRET_KEY value come from when moving to production. Do I need to generate it?
I understand this needs to be set when moving to production, I am just not sure where it comes from. Do I need to create one using ssh-keygen on my local computer and move it to my host/server or is the key provided by the host (digitalocean in my case)? Also, when I tried to research this subject, I only saw that you can use ssh keys to log in to your server using ssh keys. I went through this process in a tutorial on deployment I am currently going through. But, this doesn't seem like the value that should be placed in SECRET_KEY in settings.py. Especially since I have different keys for the root user of the server and for the user justin I created. Where does the SECRET_KEY value I need for production come from? -
Not able to return value in django templetes using class-based view
I am new to Django and I don't know much about class-based view. I was trying to return value in Django template and I am not able to access those value using template tag.I was trying to print value of distance and duration which you can see in my chart.html code. Here is my views.py code class chartView(TemplateView): template_name = 'chart.html' def calculate(self): self.res=requests.get('https://ipinfo.io/') self.data=self.res.json() self.current_loc=self.data['city'] gmaps = googlemaps.Client(key='****************************') my_dist = gmaps.distance_matrix(self.current_loc,'bhaktapur')['rows'][0]['elements'][0] # Printing the result #the variable name describes the distance and time for that bloodbank eg:-redcross,whitecross etc. redcross={ 'distance':my_dist['distance']['text'], 'duration':my_dist['duration']['text'] } my_dist = gmaps.distance_matrix(self.current_loc,'lalitpur')['rows'][0]['elements'][0] whitecross={ 'distance':my_dist['distance']['text'], 'duration':my_dist['duration']['text'] } my_dist = gmaps.distance_matrix(self.current_loc,'jorpati')['rows'][0]['elements'][0] greencross={ 'distance':my_dist['distance']['text'], 'duration':my_dist['duration']['text'] } my_dist = gmaps.distance_matrix(self.current_loc,'maharajgunj')['rows'][0]['elements'][0] yellowcross={ 'distance':my_dist['distance']['text'], 'duration':my_dist['duration']['text'] } dist_list=[redcross,whitecross,greencross,yellowcross] return render(request,'chart.html',{'dist_list': dist_list}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs"]= app.objects.all() return context my url.py code urlpatterns = [ re_path(r'chart.html/$',views.chartView.as_view(),name="Charts"), ] urlpatterns += staticfiles_urlpatterns() chart.html code {% for items in qs %} <div class="conty"> <canvas class="myChart"></canvas> </div><br><br> <div align="center"> <table> <tr> <th>{{items.name}}</th> <th>{{dist_list[0]['distance']}}</th> <th>{{dist_list[0][duration]}}</th> </tr> </table> </div> {% endfor %} and my error is django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[0]['duration']' from 'dist_list[0]['duration']' [19/Feb/2020 00:32:22] "GET /chart.html/ HTTP/1.1" 500 159883 -
TypeError: Failed to fetch, the error i am getting, i am using reactjs as frontend and django as backend
TypeError: Failed to fetch, the error i am getting, what i am trying to do is created a backend in django and calling that api from reactjs but i am getting the error mentioned // urls.py path('list', views.get_image, name='get_image'), // views.py def get_image(request): pdfs = PdfStore.objects.all() output_data = [] for i in pdfs: single_data = { "id":i.id, "name":i.pdf.name, "url":i.pdf.path } output_data.append(single_data) return JsonResponse(output_data,safe=False) // frontend-react test.js get_data = async() =>{ try{ let body = { method: 'GET', async: true, } let url = "http://127.0.0.1:8000/list" let response = await fetch(url,body); let result = await response.json(); console.log(result); } catch(error){ console.log(error); } } -
Django form is not valid but no error is sent
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database. Code on Github I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you! -
IndexError in Django. List out of range
I have a program that takes in input from user then splits the values and converts it into a list. num_of_subjects = 5 #input by user subjects = ['eng', 'maths', 'sci', 'his'] #wrong input by user expecting subjects = ['eng', 'maths', 'sci', 'his', 'phy'] #because num_of_subjects is 5 views.py def schoolinput_view(request): if request.method == 'POST': subjects_view = request.POST.get('subjects') for i in range(num_of_subjects): sub = subjects_view[i] print(sub) This gives an list out of range error as expected so I tried try: def schoolinput_view(request): if request.method == 'POST': subjects_view = request.POST.get('subjects') for i in range(num_of_subjects): sub = subjects_view[i] print(sub) except IndexError as listerror: print('Please check if subjects meet number of subjects') And this didn't solve the problem and still gives IndexError even if the exception is handled. -
Why can't Nginx find Django's static files?
I'm trying to understand how static files are served up by Django using a project I've created on my Mac using Django 3, Gunicorn, and Nginx. The website serves up templates correctly except that the templates can't see my CSS stylesheet. When I go to a page, for example 127.0.0.1:8000/app1/ and view the source, I see this in my HTML template: <link rel="stylesheet" href="/static/css/main.css"> If I click on the href link, I get a page "Not Found" at the address http://127.0.0.1:8000/static/css/main.css. This seems like it should be the correct link but the template can't see the main.css stylesheet as I would expect. Here are the pertinent files in my 'mysite' project located in /Users/me/projects/django/django-staticfiles: βββ app1 β βββ templates β β βββ app1 β β βββ index.html βββ mysite β βββ settings.py β βββ wsgi.py βββ static β βββ css β βββ main.css βββ static-final β βββ admin β β βββ css β β βββ fonts β β βββ img β β βββ js β βββ css β βββ main.css Here are the pertinent settings: # mysite/settings.py ... DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', ] ... INSTALLED_APPS = [ 'django.contrib.staticfiles', 'app1', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, β¦ -
Rank and count elements of list of lists in django
I have a Genre and a User models. Each Genre has an id and a name, and there is a many-to-many relationship, so that each User likes 0 or more Genres. Is there an efficient query for obtaining how many likes has each Genre, across all users, in descendant order? My current approach works, but it is extremely inefficient since it has to read all the likes of all the users for each genre: In [1]: genres = list(Genre.objects.values('name', 'id')) In[2]: genres Out[2]: [{'id': 10, 'name': 'Rock'}, {'id': 11, 'name': 'Pop'}, {'id': 12, 'name': 'Hip hop'}, {'id': 13, 'name': 'Electronic'}, {'id': 14, 'name': 'Classical'}] In [3]: likes_by_users = [] In [4]: users = list(User.objects.all()) In [5]: for u in users: ...: current_user_likes = [] ...: likes_by_users.append(current_user_likes) ...: for lg in u.liked_genres.all(): ...: current_user_likes.append(lg.pk) In [6]: likes_by_users Out[6]: [[14], [11, 12], [11, 10, 13, 12], [], [13, 12, 10, 1 [10, 11]] In [7]: counts = {} In [8]: for g in genres: ...: counts[g['id']] = { ...: 'name' : g['name'], ...: 'likes': 0 ...: } ...: for l in likes_by_users: ...: for gid in l: ...: if gid == g['id']: ...: counts[gid]['likes'] += 1 In [9]: ranking = sorted(list(counts.values()), key=lambda β¦ -
How to redefine built-in django loggers
I have deployed a django project on production but still actively working on it. As mentioned in documentation I disabled Debug=True to Debug=False. But while working on project i faced with necessity to look on raised traceback of errors and exceptions as when project turned on Debug=True. I read that I can enable logging in django and that it had several built-in loggers which can cover my necessity. I found in documentation the following advice Thus you should be very careful using 'disable_existing_loggers': True; itβs probably not what you want. Instead, you can set disable_existing_loggers to False and redefine some or all of the default loggers; or you can set LOGGING_CONFIG to None and handle logging config yourself. From description of built-in loggers I found that my necessity will cover the following loggers django django.request django.db.backends While I tried to configure them I didn't found any information about handlers which should handle these loggers. And my first question is how properly configure handlers for built-in loggers. I also want to understand best practices about where I should print generated by loggers record logs. Can anyone explain me -
How to link already existing table to a new one (many to one) in Django
I want to create many doubly linked lists with already existing items in my database. As of today, each item exists on it's own (there are like 10000 items) and the idea is to stop referencing to each one of them by their ID, but instead refer to a list of items by the list's ID, so i want to create a new table called "itemset" that represent a list and add to each list the corresponding items. So i'll have a lot of lists from the beginning and i don't know how to assigng the items to each list. I'm using django 1.9 -
How can I deal with a massive delete from Django Admin?
I'm working with Django 2.2.10. I have a model called Site, and a model called Record. Each record is associated with a single site (Foreign Key). After my app runs for a few days/weeks/months, each site can have thousands of records associated with it. I use the database efficiently, so this isn't normally a problem. In Django Admin, when I try to delete a site however, Django Admin tries to figure out every single associated object that will also be deleted, and because my ForeignKey uses on_delete=models.CASCADE, which is what I want, it tries to generate a page that lists thousands, possibly millions of records that will be deleted. Sometimes this succeeds, but takes a few seconds. Sometimes the browser just gives up waiting. How can I have Django Admin not list every single record it intends to delete? Maybe just say something like "x number of records will be deleted" instead. -
Inserting datas for a specified date range in django
Please lemme know , how to add datas for all days in an year or more in django. Let's say i want to add a vechicle which is available for all days. How can i store this in mysql?, Later whenever search for that vehicles, it should display , AVAILABLE ON EVERYDAY!. I think you guys understand the question! Please help me. Thank you -
TypeError at /account/ sequence item 1: expected a bytes-like object, NoneType found
I am trying to get a progress bar to load as per the instructions here. At the moment this is my view. def progress_view(request): count_pag = 200 result = hello.tasks.my_task(8,request).delay(1) context = {'task_id': result.task_id} return render(request, 'display_progress.html', context={'task_id': result}) This is my tasks.py @shared_task(bind=True) def my_task(self, seconds, request): progress_recorder = ProgressRecorder(self) result = 0 for i in range(seconds): time.sleep(1) result += i progress_recorder.set_progress(i + 1, seconds) return result There is no problem when i remove the 'request' input. But i need some sort of extra input into the function in order to do the processing i want. How to add extra inputs to the 'my_task' function without giving a traceback like below??? Traceback: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/alvintung/rndtwitr/hello/views.py" in account 22. return progress_view(request) File "/Users/alvintung/rndtwitr/hello/views.py" in progress_view 33. result = hello.tasks.my_task(8,request).delay(1) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery. /local.py" in __call__ 191. return self._get_current_object()(*a, **kw) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/task.py" in __call__ 375. return self.run(*args, **kwargs) File "/Users/alvintung/rndtwitr/hello/tasks.py" in my_task 27. progress_recorder.set_progress(i + 1, seconds) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery_progress/backend.py" in set_progress 40. 'description': description File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/app/task.py" in update_state 892. self.backend.store_result(task_id, meta, state) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery/backends/base.py" in store_result β¦ -
SetUp objects not passed with self in Django test class
I'm writing a test class in Django. I want to pass some objects to the View to test. I create them in the setUp. But they are not passed to my view in my self "object". Why is this? class SystemDeleteSiteTests(APITestCase): def setUp(self): self.user = UserFactory() role = RoleFactory(role=Role.SYSTEM_USER) UserRoleFactory(user=self.user, role=role) self.admin_user = UserFactory() role = RoleFactory(role=Role.SOUNDTALKS_CS) user_role = UserRoleFactory(user=self.admin_user, role=role) self.site_1 = SiteFactory(name="site_1") self.user_site = UserSiteFactory(user=self.user, site=self.site_1) def test_delete_site_as_system_user(self): self.client.force_login(self.user) url = reverse("system-site-detail", kwargs={"site_pk": self.site_1.pk}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_200_OK) In my view I check if there is a UserSite and that is created in the setUp, but I always get the permissiondenied error because it's not passed with the self object..: class SystemSiteView(GenericAPIView): pagination_class = StandardPagination def get_permissions(self): return IsAuthenticated(), IsSystemUser() # noinspection PyMethodMayBeStatic def get_serializer_class(self): return SystemRemoveSitesSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully deleted the site."), SystemRemoveSitesSerializer, ) }, ) def delete(self, request, site_pk): """ DELETE the site. """ site = Site.objects.filter(pk=site_pk).delete() if not site: raise NotFound if not UserSite.objects.filter(site_id=site_pk).exists(): raise PermissionDenied return Response( {"message": "Successfully deleted the site"}, status=status.HTTP_204_NO_CONTENT, ) -
Transaction atomic needed for bulk create?
I'm using the bulk_create method from Django to create many entries at once. To ensure that the changes are only committed if there is no exception I'm thinking about adding transaction.atomic() to the code blocks but I'm not sure if I need to add it. From my understanding I only need to add it in Scenario 2 because in this case I'm executing more than one query. Scenario 1 Create 1.000 entries in one query Entry.objects.bulk_create([ Entry(headline='This is a test'), Entry(headline='This is only a test'), # ... ]) Scenario 2 Create 10.000 entries in in batches of 1.000 Entry.objects.bulk_create([ Entry(headline='This is a test'), Entry(headline='This is only a test'), # ... ], batch_size=1_000) -
DRF - add argument to Model.save(...)
I have an Invoice model and there is a recalculate argument in the overridden Invoice.save() method. I want Invoice to be recalculated always except when it's created using it's serializer. Is it possible? Serializers use create so I'm not sure how to do that. (It's a ModelSerializer) -
How to declare a variable and increment it in Django templates
How to initialize a numerical variable in Django templates. {% with i=1 %} {% for cont in data %} {% if i|divisibleby:3 %} {{ forloop.i }} <!-- HTML --> {% elif i|divisibleby:2 %} {{ forloop.i }} <!-- HTML --> {% else %} {{ forloop.i }} <!-- HTML --> {% endif %} Getting this error due to {% with i=1 %} TemplateSyntaxError at /tools-dash/ Unclosed tag on line 21: 'with'. Looking for one of: endwith. -
html can not display fist for-loop result, django
I'm new in django, I would like to display my view.py to index.html, the view.py: def index(request): context_dict = {} customers = Customer.objects.all() carts = Cart.objects.select_related('customer') goods = Good.objects.select_related('cart__customer') context_dict['Cart']=carts context_dict['Good']=goods context_dict['Customer'] = customers return render(request, 'index.html', context=context_dict) and the index.html for loop is like this: <ul> {% for customer in Customer %} <li>{{ customer.name }}</li> {% for cart in Cart %} {% if customer.id == cart.id %} {% for good in Good %} {% if cart.id == good.id %} {{good.name}}--{{good.count}}--{{good.price}} {% endif %} {% endfor %} {% endif %} {% endfor %} {% endfor %} </ul> but the result displayed like this: Bob should have water--2--50 under it. it seems customer.id == cart.id cannot match. but I don't know how to fix it. please help, thanks a lot! -
How do I connect my docker Django instance to my docker mysql instance?
I'm running Docker on Mac High Sierra. I want to run Docker container to house both my Django instances and MySql instances. I have the following docker-compose.yml file ... version: '3' services: web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 apache: restart: always build: ./apache/ ports: - "80:80" #volumes: # - web-static:/www/static links: - web:web mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql volumes: my-db: The ".env" file I set up looks like this ... DB_NAME=maps_data DB_USER=chicommons DB_PASS=password DB_SERVICE=mysql DB_PORT=3406 In my web (Django) instance, I have set my settings.py db thusly ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_SERVICE'], 'PORT': os.environ['DB_PORT'] } } However, when I run "docker-compose up," I get the following errors complaining about not being able to connect to the database ... web_1 | Traceback (most recent call last): web_1 β¦ -
docker and redis server connection
is it necessary to run the docker docker run -p 6379:6379 -d redis:2.8 to work the redis server? because I have assignment to create chatting app using python, Django and postgres -
Changing Django template form field id dynamically - insert iterator value into input field id
I have a single form class which I pass into the template along with an initial_range value. I iterate over each number in that range and render the same form - I insert the value into the appropriate ids. I hide all forms but the one being worked on and using a queue in javascript, I cycle through the forms. Each time a user submits the front form, I hide it, re-populate it with new data in the background while they work on the next form in the queue. I need a unique id and name attribute for each form input field, so I want to include the initial_range value. As this is generated at the template, I'm struggling to insert it into the field because I don't know how to access "field.id" and "field.name" in order to change them (for the input field - I managed to do so for the label, as below). Forms.py class MyForm(forms.Form): address_line1 = forms.CharField( widget=forms.TextInput( attrs={'class':'form-control-plaintext'}), disabled=True, label="Address 1") Views.py class FormView(View): def get(self, request): my_form = MyForm(prefix='form_input_') # this isn't the actual prefix but I have one context = { 'form': my_form, 'initial_range': range(1,3)} return render(request, 'myapp/mytemplate.html', context) mytemplate.html {% for i β¦ -
How to set the time period for django model
I want to keep the time period in Django model. like 60 sec, 10 min. so I choose TimeField class for this purpose my_period = models.TimeField() Is it correct practice??? Because when I try to edit this value in admin page, there shows am or pm. I think I should just ignore it though....