Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn Exited too quickly (process log may have details)
I have a django project named MyProj, and this project has some application inside as below: - MyProj -- app -- venv -- media -- django_project --- wsgi.py --- settings.py --- urls.py --- asgi.py To deploy on aws, I am in the phase of gunicorn configuring. However I face with this error: guni:gunicorn BACKOFF Exited too quickly (process log may have details) this is my gunicorn.conf: [program:gunicorn] directory=/home/ubuntu/MyProj command=/usr/bin/gunicorn workers 3 --bind unix:/home/ubuntu/MyProj/app.sock django_project.wsgi.application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn in gunicorn.err.log it says problem is in: usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: unrecognized arguments: django_project.wsgi.application -
Django/Jinja: Is there a way to pass a JS variable (eg. window.visualViewport.width) inside a macro function in Jinja?
So, the issue is that I want to pass the variable window.visualViewport.width to the backend so that I can dynamically send a different string image from the backend based on the width of the screen size. Here is my macro: {# window_width variable should be dynamic #} {%- macro get_dynamic_text(window_width='......') -%} <div style="background: {{ get_window_size(window_width)|safe }}"> ...... ...... </div> {%- endmacro -%} Here is my backend library function @library.global_function def get_data_bg(width): if width >= 1200: return 'large_desktop.png' elif 992 <= width < 1200: return 'medium desktop' elif 768 <= width < 992: return 'tablet.png' else: return 'mobile.png' I did try using JS like this but it did not work. It just sends the plain text (document.write(window.visualViewport.width)) to the backend library function which is of no use: {# window_width variable should be dynamic #} {%- macro get_dynamic_text(window_width='<script>document.write(window.visualViewport.width)</script>') -%} <div style="background: {{ get_window_size(window_width)|safe }}"> ...... ...... </div> {%- endmacro -%} -
how to convert a Django project to Malay (Malaysia) language? Tried using ugettext_lazy but it is only supporting popular languages
I tried gettext_lazy and am a able to convert the admin page into Spanish, French, Arabic, etc. But when I try with malay using the code ms, nothing is happening. -
Django request with annotate and count
Need help with django-orm request. I have model: class Member(models.Model): customer = models.CharField(max_length=50) item = ArrayField(models.CharField(max_length=50)) total = models.IntegerField() Need to make a request so that it displays the top 5 users by total (I understand how to do this), but for each of the 5 customers, need to display only those items that are found in at least two other customers of this top 5. For order by total I can use: Member.objects.order_by('total')[:5] But how do you do the second part of the query? -
Design a Flask/Django API
• Design a Flask/Django API which takes in start time and end time as a query string and returns the number of times a production unit state is in running state for the asked duration, • The plant functions in three different shifts as given below (timings are in IST timezone): shiftA: 6:00 AM - 2:00 PM shiftB: 2:00 PM - 8:00 PM shiftC: 8:00 PM - 6:00 AM -
How to send the object is and get the corresponding page number where that item exists in Django Rest Framework pagination?
How to use the object id and get the corresponding page number where that object belongs on all pages of the pagination in django-rest-framework. What I'm trying to do here is sort of reverse pagination with django-rest-framework. Is there any way to calculate the page number where a particular object belongs from all pages of the pagination and display it with the object(like in the serializer) ? Any answer would be great! Thank you! -
Running multiple async tasks and waiting for them all to complete in django,
I have a function which is data=[] async def connect(id): d= await database_sync_to_async(model.objects.filter()) data.append(d) and I call connect funciton like import asyncio loop = asyncio.get_event_loop() try: # run_forever() returns after calling loop.stop() tasks =[connect(1),connect(2),connect(3),connect(4),connect(5)] a, b = loop.run_until_complete(asyncio.gather(*tasks)) finally: loop.close() But this is not working,it says There is no current event loop in thread 'Thread-3'.. How can I implement it? -
Image not showing up in django from database
I was trying to create an eCommerce website using Django. I have created a model for products and tried to display the image to the home screen. But it's saying the image Is not found in the given URL. Can anyone resolve this issue will be helpful. And I have tried the methods already given in StackOverflow. my template file: {% for product in products %} <tr> <td>{{ product.id }}</td> <td><img src="{{ product.image1.url }}"></td> <td>{{ product.name }}</td> <td>{{ product.category }}</td> <td>{{ product.price }}</td> <td><a href="#" class="btn btn-primary">Edit</a></td> <td><a href="#" class="btn btn-danger">Delete</a></td> </tr> {% endfor %} urls.py file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admins/', admin.site.urls), path('', include('user.urls')), path('admin/', include('admins.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Python MongoDB datatime in json
I am trying to load mongo data in my django application as a json data. For that I am using this sample data: mydict = { "startsAt": { "time": { "date": datetime.datetime.today() - timedelta(days = 1) + timedelta(hours = i) }, "valid": True } I am inserting above data in my mongo db: And I am trying to load this data to json using: def filterRegistration(): sreialise_mongo = json_util.dumps(mycol.find(),indent=4, sort_keys=True, default=default) page_sanitized = json.loads(sreialise_mongo) return sreialise_mongo And in Django I am loading this data using: @api_view(['GET']) def test(request): return Response({"message": filterRegistration()}) And I am getting a json data like this: "startsAt": { "time": { "date": { "$date": 1612775312481 } }, "valid": true And I want a data like: "startsAt": { "time": { "date": "2021-01-18T06:21:34.677Z" }, "valid": true I have tried few methods in similar question. But I am unable to find a solution. -
How can I do to test that using mock?
I have this model : class Team(models.Model): user = models.CharField(max_length=250, default="default", null=True) def save(): self.initial = "edited" super(Team, self).save(*args, **kwargs) And I would like to use a mock to test the save function but I am new in mock. Do you know how can I do that ? Thank you very much ! -
Backend Devolopment [closed]
I have created an annotation tool that can annotate images and texts simultaneously. I need to develop an web app for this tool. The tool is interactive also. Initially I want to make the backend or the server side of the tool with the help of Django 'Python based framework'. How to do it? -
How to style the input file button with bootstrap in Django?
I would like to style my file input inside my Django template. It currently looks as follows: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Generate Links</button> </form> When I add something like shown below, everything works but when I select a file, the name of the file does not show up when a file is selected. <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="custom-file"> <input type="file" class="custom-file-input" name="document" id="validatedCustomFile" required> <label class="custom-file-label" for="validatedCustomFile">Choose file...</label> <div class="invalid-feedback">Invalid File</div> </div> <button type="submit">Generate Links</button> </p> </form> I have been looking for a solution online, but I cannot figure it out. Thank you! -
Why do I get error "not all arguments converted during string formatting" when running PostgreSQL UPDATE in Django?
I'm trying to update a couple of tables in a PostgreSQL database. It is in Django. But I get the following error: not all arguments converted during string formatting. Why does this code throw this error? : def deleteInventoryLocation(param_ilid): try: sql = "update db.tablex set enabled = 0 where locationId = %s;" sqldata=(param_ilid) cursor = db.cursor('mydb',sql,sqldata) result = cursor.connect() sql = "update db.tabley set locationid = 1 where locationid = %s;" sqldata=(param_ilid) cursor = db.cursor('mydb',sql,sqldata) result = cursor.connect() status = "OK!" except Exception as e: result = e status = "ERROR!" return result, status Kepp in mind that I'm pretty new to Django and Python. I also replaced the db name and table names with dummy names for security reasons. Thanks! -
Python / django - problem with relations many to many
I have a problem with django in python. I did a project that adds a company to the database and then displays it as a business card (something like google maps). However, I have manytomany relations and displaying selected company attributes in html. This is what the model looks like class Company(models.Model): name = models.CharField(max_length=255) description = models.TextField(max_length=500) contact = models.EmailField(max_length=500) services = models.ForeignKey('CategoryServices', on_delete=models.CASCADE, null=True) city = models.ForeignKey('City', on_delete=models.CASCADE, null=True) have_stationary = models.ForeignKey('Stationary', on_delete=models.CASCADE, null='Brak danych') atribute_comp = models.ManyToManyField('AttributesCompany') def __str__(self): return self.name This is the view class AddCompanyView(LoginRequiredMixin, View): def get(self, request): form = AddCompanyForm() return render(request, 'addcompany.html', {'form': form}) def post(self, request): form = AddCompanyForm(request.POST) if form.is_valid(): new_company = Company.objects.create(name=form.cleaned_data['name'], description=form.cleaned_data['description'], contact=form.cleaned_data['contact'], services=form.cleaned_data['services'], city=form.cleaned_data['city'], have_stationary=form.cleaned_data['have_stationary']) new_company.atribute_comp.set(form.cleaned_data['attribute_company']) return redirect(f'/company/{new_company.id}') else: return render(request, 'addcompany.html', {'form': form}) AND class CompanyView(View): def get(self, request, company_id): company = Company.objects.get(id=company_id) contact = Company.objects.all() comments = Comments.objects.filter(company_name=company) city = City.objects.all() stationary = Stationary.objects.all() return render(request, 'company.html', {'company': company, 'contact': contact, 'company_id': company_id, 'city': city, 'comments': comments, 'stationary': stationary}) This is what forms looks like class AddCompanyForm(forms.Form): name = forms.CharField(label="Nazwa firmy") description = forms.CharField(label="Opis firmy") contact = forms.EmailField(label="Email do firmy") services = forms.ModelChoiceField(queryset=CategoryServices.objects.all(), label='W jakiej branży działa firma') city = forms.ModelChoiceField(queryset=City.objects.all(), label='Wybierz miasto gdzie firma … -
When I tried to deploy to Heroku my Django project it is not detecting the buildpack. Could anyone help me please?
I have tried all methods in the documentation but still I am having the same issue. -
How to solve attribute error 'QueryDict' object has no attribute 'company'?
I want to allow a user can create an another user. I created a form for that. It works perfectly at the beginning but later I changed a few things and now it is not working, the form doesn't save. I tried to find where is the mistake but I can not find. How can I fix it? Note: comp_name is a hidden field, so user should not see it AttributeError at /signup/ 'QueryDict' object has no attribute 'company' views.py def signup(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) form_class = SignUpForm rank_form = RankForm(request.POST) if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.is_active = False rank_form = RankForm(instance=user, user=request.user) rank_form.save() if form.cleaned_data['password1'] != "": user.set_password(form.cleaned_data['password1']) user.save() return redirect('home') else: form = form_class() context = { 'form': form, 'rank_form': rank_form } return render(request, 'signup.html', context) models.py class CompanyProfile(models.Model): comp_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) comp_name = models.CharField(max_length=200) country = models.CharField(max_length=200, default='') class Rank(models.Model): rank_name = models.CharField(max_length=200) company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) class UserProfile(AbstractUser): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=250) … -
Reading external token in Django
I am calling Django API from .NET API. I am passing a validated Bearer token (JWT) in the header. I am not able to read the token from the header in Django API. I am using only functional API views. The users, models and db is managed in .NET only. Why is Django stripping my token in the header? How to enable secured token reading in Django Functional API? -
Print takes more than 2 seconds in python
I have a variable which is obj=model.filter(id=id) and i have print function which display obj value. i measure it by pref_counter() it takes more than 2 seconds. my code are like obj=model.filter(id=id) c = time.perf_counter() print(obj) d = time.perf_counter() print("seconds", d - c) #shows 2 seconds Fun part is if I print it twice, it will take 4 seconds. -
ERROR: Service 'app' depends on service 'db' which is undefined
I'm getting this error while trying to run: docker-compose run app python manage.py migrate in the console. This is the error: ERROR: Service 'app' depends on service 'db' which is undefined. My docker-compose.yml is this one: version: '3' volumes: database: { } services: app: build: context: . dockerfile: ./docker/app/dev/Dockerfile environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=xxxx depends_on: - db volumes: - ./app:/app:z env_file: - ./.envs/.dev/.app - ./.envs/.dev/.postgres ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" Everything is linked accordingly so I don't know where this error can come from. -
Apply filter with Prefetch in prefetch_related()
I am creating a multi language project. I am using 2 models to save data. Fields that are same for all languages (like images) in model 1 and texts in model 2 with ForeignKey to model 1. class FidelityClubs(models.Model): image = models.ImageField(upload_to='admin/fidelity_clubs/') class FidelityClubTexts(models.Model): title = models.CharField(max_length=255) content = RichTextField() language = models.ForeignKey('van_admin.Languages', on_delete=models.CASCADE, default='1') club = models.ForeignKey('van_admin.FidelityClubs', on_delete=models.CASCADE, related_name='texts') There is a default language. All contents will be available in default language (french). If user select another language, I have search content in that language and if content is not available in that language, I have to show content in default language. I using this query. fidelities = FidelityClubs.objects.all().prefetch_related(Prefetch('texts', FidelityClubTexts.objects.filter(language__code=lang_code))) I am sending this data by APIs. This is showing data like this. { "image": "http://127.0.0.1:8000/media/admin/fidelity_clubs/logo-1.png", "texts": [ { "id": 9, "title": "CosmetiCar en", "content": "<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, CosmetiCar Informaton Lorem Ipsum is simply dummy text of the printing and typesetting industry. en</p>", "language": 2, "club": 13 } ] }, { "image": "http://127.0.0.1:8000/media/admin/fidelity_clubs/logo-2.png", "texts": [] }, This is not working. If data is available in required language … -
How to access Post IPAddress HitCount in Template
I am building BlogApp and I made a HitCount Feature for count the views of BlogPost through IPAddress. BUT i am stuck on a Problem. AND i don't know how to access in Template. models.py PostViews model is for Count the Views through IPAdress of the User. class PostViews(models.Model): IPAddress = models.GenericIPAddressField(default='45.243.82.169') post = models.ForeignKey('BlogPost',on_delete=models.CASCADE,null=True) class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(auto_now_add=True,null=True) @property def views_count(self): return PostViews.objects.filter(post=self).count() views.py def detail_view(request,pk): data = get_object_or_404(Post,pk=pk) views = PostViews.objects.get_or_create(pk=pk) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') context = {'views':views`,'data':data} return render(request, 'show_more.html', context ) show_more.html {{ views }} The Problem I don't know how to access HitCount Views in template. Views are adding in Admin Properly through IPAddress BUT i have no idea how to acces them. What have i tried I have also pass x_forwarded_for in context AND i did try to access but nothing worked. Any help would be Appreciated. Thank You in Advance. -
django inspectdb command run migrations
I have connected with an existing database with Django which is on an SQL server. It's working fine. after that, I am getting all tables using python manage.py inspectdb command. It gives me all tables but now I want to access data for all tables. Is a need to run migrations for that tables? if yes, then I don't want to put default user migrations in an existing database how can I solve this? -
Why does my django webserver stop after trying to send password reset mail?
Here are the logs, I tried to read them but I got no idea how to fix this error. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 850, in resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_nav_sidebar_enabled] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf..get_val at 0x00000285F295D488>>, 'request': <WSGIRequest: GET '/reset_password/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.. at 0x00000285F2B482F0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x00000285F2A4EE10>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000285F2B200F0>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': , 'view': <django.contrib.auth.views.PasswordResetView object at 0x00000285F2B201D0>, 'title': 'Password reset', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] "GET /reset_password/ HTTP/1.1" 200 1903 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en\formats.py first seen with mtime 1603131647.8355522 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en_init.py first seen with mtime 1603131647.8345575 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\staticfiles\storage.py first seen with mtime 1603131653.6030731 (0.031) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE (UPPER("auth_user"."email"::text) = UPPER('######@gmail.com') AND "auth_user"."is_active"); args=('######@gmail.com',) File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\mail\backends\smtp.py first seen with mtime 1603131654.0612879 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\mail\backends\base.py first seen with mtime 1603131654.0582974 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\smtplib.py first seen with mtime 1530052318.0 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\sites\requests.py first seen with mtime 1603131652.143951 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\mail\backends_init.py first seen with mtime 1603131654.0572996 "POST /reset_password/ HTTP/1.1" 302 0 -
How to query a user's display information in the AccountDisplayInformation from the AccountModel
I am trying to query the instagram field in the AccountDisplayInfo model through the account model. via this line in the view: displayinfo = get_object_or_404(AccountDisplayInfo, account=account) I am however not able to query that information as I got a 404 error..any idea why this is happening? Did I do something wrong in views.py or forms.py Also, would be great if you can advise on this:: If I have 2 tables. Table 1 and Table 2. Table 2 has a foreign key to table 1 but table 1 dont have a foreign key to table 2. How can I query table 2's data from table 1? Thanks models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class AccountDisplayInfo(models.Model): account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) instagram = models.CharField(max_length=50, unique=True, blank=True, null=True) #instagram views.py def display_information_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) context = {} displayinfo = get_object_or_404(AccountDisplayInfo, account=request.user.id) if request.POST: form = DisplayInformationForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = DisplayInformationForm(request.POST, instance=request.user, initial={ "instagram": displayinfo.instagram, } ) context['form'] = form else: form = DisplayInformationForm( initial={ "instagram": displayinfo.instagram, } ) context['form'] = form return render(request, "account/displayinfo.html", context) forms.py class DisplayInformationForm(forms.ModelForm): class Meta: model = AccountDisplayInfo fields … -
How can I get list of all items with query received?
I am making a Django project in which I have User List which contains various Items. Each Item has its attribute like name, quantity and date. This is my model of items: class Item(models.Model): STATUS = ( ('BOUGHT', 'BOUGHT'), ('NOT AVAILABLE', 'NOT AVAILABLE'), ('PENDING', 'PENDING'), ) userlist = models.ForeignKey(userList, on_delete=models.SET_NULL, blank=True, null=True) item_name = models.CharField(max_length=200, null=True) item_quantity = models.CharField(max_length=200, null=True) item_status = models.CharField(max_length=200, null=True, choices=STATUS) date = models.DateField(null=True) def __str__(self): return self.item_name This is my views.py: def listView(request): if request.user.is_authenticated: fd = None user_id = request.user.id userlist, created = userList.objects.get_or_create(user_id=user_id) items = userlist.item_set.all() if request.body: data = json.loads(request.body) fd=data['date'] else: items = None context = {'items': items} return render(request, 'list_manager/index.html', context) Here, fd is the query 'date' received from body. By default, items contains all the items present in the list. Now I just want the list of objects which have item.date==fd, how can I achieve that?