Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Add formset to a form
I am trying to add a formset to a forms in order to be able to add lines to a bill. I`ve start using a generic view as I found this tutorial for working with formset: https://dev.to/zxenia/django-inline-formsets-with-class-based-views-and-crispy-forms-14o6 I kept encountering some errors when trying to load the form. The current error is: init() takes 1 positional argument but 2 were given, Many Thanks views.py @login_required(login_url="/login/") class BillCreate(CreateView): model = Bill template_name = 'accounting/bills/create_bill.html' form_class = BillForm success_url = None def get_context_data(self, **kwargs): data = super(BillCreate, self).get_context_data(**kwargs) if self.request.POST: data['lines'] = BillLineFormSet(self.request.POST) else: data['lines'] = BillLineFormSet() return data def form_valid(self, form): context = self.get_context_data() lines = context['lines'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if lines.is_valid(): lines.instance = self.object lines.save() return super(BillCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('accounting:bill_detail', kwargs={'pk': self.object.pk}) models.py class Bill(models.Model): vendor = models.CharField(max_length=250, null=True, blank=True) bill_title = models.CharField(max_length=250, null=True, blank=True) reference = models.CharField(max_length=250, null=True, blank=True) class BillLine(models.Model): bill = models.ForeignKey(Bill,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False) bill_item = models.CharField(max_length=100, verbose_name="Line") description = models.TextField(blank=True, null=True) forms.py class BillForm(forms.ModelForm): class Meta: model = Bill fields = ['bill_title','vendor','reference'] def __init__(self, *args, **kwargs): super(BillForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( … -
, i having problem with Listmodelmixin. when i call self.list(request). it only returns only first object.. i am pasting my code here
below is my class code with get method. problem is if i do not specify pk only one value is coming . its not returning complete list. and if i add pk it works fine for every record. pls guide. class UserGenericAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated ] queryset = User.objects.all() serializer_class = UserSerializer def get(self, request, pk=None): if pk: return Response({ 'data': self.retrieve(request, pk).data }) return self.list(request).data -
Can this Django queryset loop be optemize?
I need to replace an index value in a pandas data-frame, my solution involves looping through the queryset and replacing the values 1 by 1 before converting into a list for pandas. The issue is that this method takes almost 3 times as long, below is my loop for i in list(report_queryset): Merchant = Posranges.objects.using('DATABASE').filter(posgroupid=i['posgroupid']) i['posgroupid'] = Merchant[0].description # value replacement with description field from posranges database updated_list.append(i) is there a way that this can be optimized? or have I completely missed a better way altogether? -
JSONDecodeError at / .. Expecting value: line 1 column 1 (char 0) [closed]
I'm working on a payment gateway project. so I converted a string into JSON and then create a payment URL. but this error occurs. traceback: Traceback (most recent call last): File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Desktop\Django Web App\Len-den\len_den\users\views.py", line 101, in product_rashid print(r.json()) File "C:\Users\user\Desktop\Django Web App\Len-den\venv\lib\site- packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I think an error occurs here. def payment(request): jsonObj={ "name": "name" } json_string = json.dumps(jsonObj) print(json_string) url = "https://url.something" headers = {'Content-type': 'application/json', 'Accept': 'application/json'} r = requests.post(url, data=json_string, headers=headers) print(r.json()) j = r.json()['status'] k = r.json()['data'] if j == "200": payment_id = k['payment_id'] redirect_url = k['redirect_url'] payment_link = str(redirect_url) + "?" + str(payment_id) print(payment_link) context = { 'payment_link': payment_link, } return render(request, 'users_dashboard/payment.html', context) return render(request, 'users_dashboard/product_rashid.html') -
How to track download link in django?
I followed these method to track how much downloaded the file was. But total_downloads always remains same(it's 0). How to increment total_downloads field by 1 after every download? My models.py: from django.db import models class FilesAdmin(models.Model): id_no = models.IntegerField() name = models.CharField(max_length=20) loc = models.CharField(max_length=20) adminupload = models.FileField(upload_to='media') total_downloads = models.IntegerField(default=0) def __str__(self): return self.name views.py. In this program, I want to increment the number of downloads. But it's 0 in admin site. from django.shortcuts import render from django.http import HttpResponse import os from .models import FilesAdmin def index(request): context = {'file': FilesAdmin.objects.all()} return render(request,'libooki/index.html',context) def download(request,path): file_path = os.path.join(settings.MEDIA_ROOT,path) if os.path.exists(file_path): with open(file_path,'rb') as fh: response = HttpResponse(fh.read(),content_type="application/adminupload") response['Content-Disposition']='inline;filename'+os.path.basename(file_path) FilesAdmin.total_downloads+=1 FilesAdmin.total_download.save() return response urls.py from django.contrib import admin from django.urls import include,path from django.conf import settings from django.conf.urls.static import static from libooki import views #here's libooki is my app name from django.conf.urls import url from django.views.static import serve urlpatterns = [ path('', views.index,name='index'), path('admin/', admin.site.urls), url(r'^download/(?P<path>.*)$',serve,{'document_root': settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html where to people can download the file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> {% for post in file%} <h2>{{post.name}}</h2> <a href="{{post.adminupload.url}}" download="{{post.adminupload.url}}">Download</a> {% endfor %} </body> … -
Django - robot.txt - sitemaps - dynamic video service
I have been developing a dynamic video service. The couple of example links regarding the service are as following ( there are thousands of video links in the service ) : https://supereye.co.uk/watch/?v=QByCOKlmao5 or https://supereye.co.uk/watch/?v=4pZ3APUR4hx I have done the following changes in settings.py: SITEMAP_MAPPING = 'mysite.urls.sitemaps' SITEMAP_INDEX_URL = 'sitemap-video-' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ROBOTS_CACHE_TIMEOUT = 60*60*24 INSTALLED_APPS += [ 'django.contrib.sitemaps', 'django.contrib.sites', 'robots', 'sitemap_generate', 'corsheaders', and in urls.py from django.contrib.sitemaps.views import sitemap from mysite.sitemaps import VideoSitemap sitemaps = { 'static': VideoSitemap } urlpatterns = [ path('admin/', admin.site.urls), path(r'^robots.txt$', include('robots.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='sitemap-index'), path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), What shall I add into django models of robots admin url and sitemaps ? How can I correctly implement/integrate robot.txt and sitemaps for each using the following packages : django-sitemap-generate django-robots -
Django - Generic OneToOneField to enable select_related() functionality
I have the following models: class A(Model): ... class B(Model): ... class C(Model): ... class Generic(Model): genericable_id = PositiveIntegerField() genericable_type = CharField() # One of A, B, C ... For which the data look like this: Table A: id, other fields 1, ... 2, ... Table B: id, other fields 1, ... 2, ... Table C: id, other fields 1, ... 2, ... Table D: id, genericable_id, genericable_type, other fields 1, 1, 'A', ... 2, 2, 'A', ... 3, 1, 'B', ... 4, 2, 'B', ... 5, 1, 'C', ... 6, 2, 'C', ... To retrieve Generic object from A/B/C's class perspective, I do something like the following: Example for class A @property def genericable(self): return Generic.objects.get(genericable_id=self.id, genericable_type='A') It turns out I query for that generic object quite a lot from all these classes, and it slows down my application, as there's no way to prefetch that object using select_related() given current implementation (cached_property helps a bit, but having an ability to do that through select_related would be much better. I was wondering whether it is possible to somehow define that relationship in Django so I can do for example: qs = A.objects.select_related().all() # all generic objects for A retrieved … -
form registers as valid but does not update
This is a very weird phenomenon. Why is it that even though the form is valid, the values are not updated? It works if i do it in django admin though. I am not even receiving any errors. The form is just valid but its not being updated. Its as if they took the old values to update... html: <form action="{% url 'account:displayinfo' request.user.id %}" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <div class="d-flex justify-content-center"> <button type="submit" class="btn btn-primary btn-sm col-lg-5">Update</button> </div> </form> views.py def display_information_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) context = {} displayinfo = AccountDisplayInfo.objects.get(account=account) if request.method == "POST": form = DisplayInformationForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): info = form.save(commit=False) info.account = request.user info.save() messages.success(request, 'Your profile display information have been updated', extra_tags='editdisplayinfo') 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 = ('instagram',) 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 -
Python threading lifecycle
I am developing a Django project where after discarding the use of celery for its complexity, I have implemented python threading directly through the Thread class. The purpose is very simple tasks that do not need a control if they have been carried out, such as sending push messages to devices (with a very low load, in the order of about 20 messages per hour). However I have been looking for multiple information about the Thread life cycle in python and I can come up with a conclusion about it. Is it necessary to manually close each Thread launched or does the process end when the run function completes? Not being necessary to control the correct execution of the operation, what advantages does the use of celery have over this option with the purpose and workload mentioned? -
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) …