Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm working on django framewrk and I'm totaly new to this so I'm uable to to cofigure the static files like css and java, I'm changing the css but no
enter image description here I'm working on django framewrk and I'm totaly new to this so I'm uable to to cofigure the static files like css and java, I'm changing the css but not being update on chrome -
What is 'obj' while creating custom list_display in the Django ModelAdmin
While going through the Django docs for a custom list_display (displaying fields in the admin, other than the fields present in the model), I came through the below code: class PersonAdmin(admin.ModelAdmin): list_display = ('upper_case_name',) @admin.display(description='Name') def upper_case_name(self, obj): return ("%s %s" % (obj.first_name, obj.last_name)).upper() The PersonAdmin class is the self in the method upper_case_name, but I wonder what is the obj here? -
JsonResponse from django app not showing in html table or console.log
I have a django app that parses a csv and stores the data in sqlite which works great and i can see the data in the admin panel. Now i'm having trouble displaying the data either in the front end as a table or in the console. views.py def airpollution_table_data(request): table_data = {} pollutant_list = [pollutant for pollutant in Pollutant.objects.all()] country_list = [country for country in Country.objects.all()] for pollutant in pollutant_list: table_data[pollutant.name] = {} for i, country in enumerate(country_list): total = PollutantEntry.objects \ .aggregate(total=Sum('pollution_level', filter=Q(pollutant=pollutant, country=country)))['total'] minimum = PollutantEntry.objects \ .aggregate(min=Min('pollution_level', filter=Q(pollutant=pollutant, country=country)))['min'] maximum = PollutantEntry.objects \ .aggregate(max=Max('pollution_level', filter=Q(pollutant=pollutant, country=country)))['max'] count = PollutantEntry.objects.filter(pollutant=pollutant, country=country).count() units = PollutantEntry.objects.filter(pollutant=pollutant, country=country).first() units = units.units if units else '' if total is not None and count: table_data[pollutant.name][country.iso_code] = {'avg': total / count, 'min': minimum, 'max': maximum, 'limit': pollutant.limit_value, 'units': units} return JsonResponse(table_data) URLs.py from django.urls import path from . import views app_name = 'supplychain' urlpatterns = [ path('', views.airpollution, name='airpollution'), path('airpollution_table_data', views.airpollution_table_data, name='airpollution_table_data'), path('temp_country_creator', views.temp_country_creator, name='temp_country_creator') ] welcome.html table code <!-- Table Section--> <section class="page-section mt-5" id="data-table"> <div class="container"> <!-- Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Data Table</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Table--> … -
Auto Increment in Django with views.py
if request.method == 'POST': m = sql.connect(host="localhost",user="root",password="admin@123", database= "ticketsys") cursor = m.cursor() ticketid = request.POST['ticketid'] email = request.POST['email'] username = request.POST.get('username') checkbox = request.POST['checkbox'] adult = request.POST['adult'] fromstation = request.POST['fromstation'] tostation = request.POST['tostation'] rate = request.POST["rate"] date = request.POST.get('date') usermessage = request.POST['usermessage'] c = "insert into ticketsys.ticketgen values('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(ticketid,email,username,checkbox,adult,fromstation,tostation,rate ,date, usermessage) cursor.execute(c) m.commit() return render(request, 'account/ticketconf.html') else: return render(request, 'account/ticket.html') Here, ticket id is auto-increment but its showing me error. 1366 (HY000): Incorrect integer value: '' for column 'ticketid' at row 1 What is best way to solve this problem. so that without creating model I can be able to post my data in mysql. SQL- Image -
django-import-export export with queryset
I'm using django-import-export and just try to export data from outside admin page. My query returns correct answer, but I get empty rows in dataset, only header is showing. It works only without values and annotate. How can I fix this? resources.py class ReviewResource(resources.ModelResource): class Meta: model = staff_review fields = ('employee', 'review') views.py review = staff_review.objects.values( 'employee' ).annotate( e = Count('employee'), review = Concat('review') ).filter( month = month(), id__in = Subquery(id.values('last_id')), ).order_by( 'employee' ) review_resource = ReviewResource() dataset = review_resource.export(review) print(dataset) -
how to split words that user inserts in input field in Django app
I have a search bar that is searching in 3 models columns title, body, short_description. Right now, I am using Q lookups but there are some search limitations that I'd like to 'improve'. One of them is that Q lookups find only results based only on phrase results that are exactly the same as in field so for instance, I have the title why python is so amazing? and I must write why or python or python is in order to get results. What I'd like to get is to extend the search bar to work in the following way: A user inserts a question in the search bar: python language and search lookup is splitting each word and returning all objects that contain python or language. In the end the result would return object with why python is so amazing?, no matter it user puts python language or amazing python. I am posting my current code below: views.py def search_items(request): query = request.GET.get('q') article_list= Article.objects.filter(title__icontains=query) qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) | Q(short_description__icontains=query) | Q(body__icontains=query) article_list= Article.objects.filter(lookups, status=1).distinct() qa_list = QA.objects.filter(lookups, status=1).distinct() context = { 'query_name': query, 'article_list': article_list, 'qa_list': qa_list, } return render(request, … -
Como resolver erro no heroku domains? [closed]
Olá, estou usando o comando heroku domains:app django.opentowork.net.br e está sendo retornada a seguinte mensagem de erro: (curso-django) PS C:\Users\55799\Desktop\curso-django> heroku domains:add django.opentowork.net.br Adding django.opentowork.net.br to ⬢ pypro42... done » Error: Require params: sni_endpoint. » » Error ID: invalid_params Alguém faz ideia do que esteja acontecendo? Agradeço desde já! -
count number of user signed up in django template
I am trying to show how many people have signed up in the front page. {% for use in user.all %} {{use}} {% endfor %} {{user.count.all}} {{user.count}} None of them have worked. What's the template language or can i show it fetching data from views? thanks in advance -
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field - models.ForeignKey
I'm trying to create a frontend data entry page for an existing model. However, when clicking the link, I get an error: crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field Just to be clear, adding the data from Django Admin works with no issues at all. Having looked through a number of answered questions here, one did highlight what I believe could be problem, but it was out of context and did not provide much of an explanation. I am trying to create a frontend entry form for users that corresponds with a foreign key. models.py class NewHandoff(models.Model): handoff_pk = models.AutoField(primary_key=True) handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date") shift1_pri = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Primary") shift1_sec = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Secondary") def __str__(self): return f"{self.handoff_date}" class Meta: verbose_name_plural = 'Handoffs' # New Handoff Form class NewHandoffForm(forms.ModelForm): class Meta: model = NewHandoff fields = ['shift1_pri','shift1_sec'] views.py from django.shortcuts import redirect, render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.http.response import HttpResponse from django.contrib import messages from .models import AttentionForm, NewHandoffForm # Handoff View Page class NewHandoffView(LoginRequiredMixin,View): def get(self, request): greeting = {} greeting['heading'] = "New Handoff" greeting['pageview'] = "Handoff" return render (request,'handoff/handoff-new.html') def post(self, request): if request.method == "POST": if "add-new-handoff-button" in request.POST: create_new_handoff_form … -
Ordering queryset by model string
I'm defining the string for a model as follows: class Customer(models.Model): company_name = ... first_name = ... last_name = ... def __str__(self): if self.company_name != None and self.company_name != "": return self.company_name else: return self.first_name + " " + self.last_name When querying for customers, is it possible to order the query by the string that represents the model instance? eg c = Customers.objects.all().order_by('???????') Thanks! -
How can i get data from a specific user rather then ID in my django app
i am trying to get date from a user when sending a webhook. The JSON will be handling the username of which user i want the data to be used from . but i get an error that user is expecting an id how can i make it that it is looking for a username rather then id.This is the error and this is my Models code class Bybitapidatas(models.Model): #user = models.OneToOneField(User, null=True,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1,on_delete=models.CASCADE) apikey = models.CharField(max_length=30) apisecret = models.CharField(max_length=40) def __str__(self): return str(self.user) + self.apikey + self.apisecret and this is my views file where i am trying to get the data for the user @csrf_exempt @require_POST def webhook(request): #get current users keys jsondata = request.body data = json.loads(jsondata) for the_data in data: users = the_data print(users) database = Bybitapidatas.objects.get(user=users)# this is where it is asking for the id? for apikey in database: apikey = apikey.apikey for apisecret in database: apisecret = apisecret.apisecret session = HTTP(endpoint='https://api-testnet.bybit.com/', api_key=apikey, api_secret=apisecret,spot=True) print(session.place_active_order( symbol="BTCUSDT", side="Buy", type="MARKET", qty="20", timeInForce="GTC" )) print(apikey) -
Docker-compose django-python container communication
So I am running a django node and a regular python script using docker-compose. The python script regularly asks django backend for data. However, when I docker-compose up I get this error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=8080): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f3d6e45dc10>: Failed to establish a new connection: [Errno 111] Connection refused')) Here is my docker-compose.yaml: version: "3" services: backend: command: > sh -c "python3 manage.py wait_for_db && python3 manage.py migrate && python3 manage.py runserver 0.0.0.0:8080" build: context: ./backend dockerfile: Dockerfile volumes: - ./backend:/backend ports: - "8080:8080" monitor: command: > sh -c "python3 main.py" build: context: ./monitor dockerfile: Dockerfile volumes: - ./monitor:/monitor ports: - "8082:8082" from monitor I do: response = requests.get(url = 'http://0.0.0.0:8080/') What is a correct way to communicate between nodes in docker? P.S Cors origins are allowed in django -
Serving CHANGING static django files in production
I need to serve a static file that has a changing name. This works fine with DEBUG = True, but immediately breaks with DEBUG = False. I'm currently using Whitenoise to serve files in production, and tried executing collectstatic after the filename changes, but that didn't help. Any advice is appreciated -
Django / Python - how can I write this more compactly?
How can I write this more compactly? I think it might be possible using a Dictionary, but I'm just not sure how, as I'm only 2 weeks into learning Django and Python. Thanks in advance! if form1.is_valid() and form2.is_valid(): if form2.is_valid() and form2.cleaned_data.get('right_to_work_selection') == 'Passport' and form3.is_valid(): if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form3.save() form7.save() form8.save() return redirect('profile_employment') if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'U.K. Limited Company' and form9.is_valid(): form1.save() form2.save() form3.save() form7.save() form9.save return redirect('profile_employment') if form2.is_valid() and form2.cleaned_data.get('right_to_work_selection') == 'Birth Certificate & N.I. Number' and form4.is_valid() and form6.is_valid(): if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form4.save() form6.save() form7.save() form8.save() return redirect('profile_employment') if form7.is_valid() and form7.cleaned_data.get('working_type_selection') == 'U.K. Limited Company' and form9.is_valid(): form1.save() form2.save() form4.save() form6.save() form7.save() form9.save() return redirect('profile_employment') -
How to architect a web scraping api? [closed]
I am planning on building an app that takes some input from the user and than scrapes real state data from different websites and processes that data (like average price etc) and display that data to the user. So how should the scraping be done? on the server of by the frontend? My Stack: Django (with libraries like celery and channels) PostgreSQL Flutter (for mobile) React (for web) RabbitMQ as a message broker -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` [closed]
views.py @api_view(['POST','GET']) def nric_validate(request): if request.method == 'GET': ki = Kiosk.objects.all() serializer =Kioskserialize(ki, many=True) return Response(serializer.data, status=status.HTTP_200_OK) if request.method =="POST": k = Kiosk.objects.all() serializer = Kioskserialize(k, many=True) nric_no = request.POST['nric_no'] user = auth.authenticate(nric_no=nric_no) # uid = request.POST.get('uid') uid = FRUser.objects.values_list('uid',flat=True) print(uid) if uid == nric_no: Kiosk(nric_no=nric_no).save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When i run this code it displays Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> I don't know where is the issue I have given Response also But it shows this error -
cannot upload images to DRF using React Native
I am trying to upload image from react native to django server I cannot upload it. i can get uri of image properly at the server end following error is occur _mysql.connection.query(self, query) django.db.utils.DataError: (1406, "Data too long for column 'Services_image' at row 1") my server end code class ServicesList(APIView): permission_classes = [IsAuthenticated] parser_classes = (MultiPartParser, FormParser,JSONParser,FileUploadParser) def post(self, request,): data=request.data print(data) Services.objects.create(s_name=data.get('title'),description=data.get('description'), provider_user_id=self.request.user.id, services_rate_per_hour=70,Services_image=data.get('image')) return Response(status=status.HTTP_201_CREATED) models.py Services_image=models.ImageField(upload_to='Services', blank=True,null=True) my uri of image 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540m.arshad5857%252FManagPatients/ImagePicker/214b8e7e-8027-4778-95d5-281c4a8bf356.jpg' I have no idea how to resolve this error plz answer me. How to upload image in django with proper way using react native -
Django database update
I wrote a parser that takes the name and price of the product from the url. Each product has its own url. Information about the price of goods must be constantly updated and displayed on the site. Do not tell me if it is possible every 30-60 seconds to parse all products (which are stored in the database) by url and have their data displayed on the site. (I don't know how to make the data automatically update and save to the database). -
Problem with placeholder on a django template input form field
I am creating a user login using the default django authentication system. Using a bootstrap template, I am creating a form with custom fields, and they are working correctly. The problem is that when displaying this form, it renders showing the value attribute instead of the placeholder that I have passed to it. This is who it looks: login page login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <img class="mb-4" src="{% static 'images/logo.jpg' %}" alt="" width="100" height="100"> <h1 class="h3 mb-3 fw-normal">Please sign in</h1> <div class="form-floating"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" value="{{form.username}}"> <label for="floatingInput">Username</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" value="{{form.password}}"> <label for="floatingPassword">Password</label> </div> <div class="checkbox mb-3"> <label> <input type="checkbox" value="remember-me"> Remember me &emsp; <a href="{% url 'password_reset' %}"> Lost password?</a> </label> </div> <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button> <p class="mt-5 mb-3 text-muted">&copy; 2022 all rights deserved</p> </form> -
Django saving multiple forms - what's a compact way of doing this?
Is there a more compact way of writing this in Python / Django? I haven' finished this yet, but I can see it growing big quickly, as I need to include further branches for 3 other values of form7.cleaned_data.get('working_type_selection') == '3 other Options', apart from 'Employee'. If it's Employee form8 gets saved, otherwise it could be form 9, or form 10. The saving of the forms has to be the final step of each branch right? if form1.is_valid() and form2.is_valid(): if form2.cleaned_data.get('right_to_work_selection') == 'Passport' and form3.is_valid(): if form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form3.save() form7.save() form8.save() return redirect('profile_employment') if form2.cleaned_data.get('right_to_work_selection') == 'Birth Certificate & N.I. Number' and form4.is_valid() and form6.is_valid(): if form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form4.save() form6.save() form7.save() form8.save() return redirect('profile_employment') if form2.cleaned_data.get('right_to_work_selection') == 'Certificate of Registration & N.I. Number' and form5.is_valid() and form6.is_valid(): if form7.cleaned_data.get('working_type_selection') == 'Employee' and form8.is_valid(): form1.save() form2.save() form5.save() form6.save() form7.save() form8.save() return redirect('profile_employment') -
Filter model by m.Choices
On Django3, I have a model each line has tuple. class CallType(m.Choices): PUSH = (1,"Pushing",True) PULL = (2,"Pulling",False) PUNCH = (3,"Punching",False) And in form.py action_type = forms.ChoiceField( required=False, choices=sm.CallType.choices) Now I want to filter the Item like this below. action_type = forms.ChoiceField( required=False, choices=sm.CallType.filter(third_item=True) This code is of course doesn't work. However is it possible? -
How to integrate bKash payment method in Django?
i just trying to integrate payment method on my course selling app. https://github.com/RakibulIslamDigonto -
'ModelChoiceField' object is not iterable - calling objects from existing Model
Losing the will to live here lol. Can't work out what's going wrong here, I'm calling objects from a model that has values in Django Admin but every time I try to fix one thing, it breaks another. I want to be able to create a new entry from frontend, but I get this error when trying to migrate: Stack error File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py", line 784, in __init__ self.choices = choices File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py", line 801, in _set_choices value = list(value) TypeError: 'ModelChoiceField' object is not iterable Please see my model below: models.py # Model engineer_shifts = [ (0,'Shift 1), (1,'Shift 2'), (2,'Shift 3') ] class Engineer(models.Model): engineer = models.CharField(max_length=200,default="John Smith",verbose_name="Engineer") engineer_shift = models.IntegerField(choices=engineer_shifts,verbose_name="Shift") def __str__(self): return f"{self.engineer}" class Meta: verbose_name_plural = 'Engineers' class CreateHandoff(models.Model): handoff_pk = models.AutoField(primary_key=True) handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date") shift1_lead = models.IntegerField(choices=engineer_picker,verbose_name="Shift 1 Lead") shift1_sec = models.IntegerField(choices=engineer_picker,verbose_name="Shift 1 Secondary") def __str__(self): return f"{self.handoff_date}" class Meta: verbose_name_plural = 'Handoffs' # Form engineer_picker = forms.ModelChoiceField( queryset=Engineer.objects.all() ) class CreateHandoffForm(forms.ModelForm): shift1_lead = forms.ChoiceField( label = "Select Shift 1 Lead", choices = engineer_picker, required = True ) shift1_sec = forms.ChoiceField( label = "Select Shift 1 Secondary", choices = engineer_picker, required = True ) class Meta: model = CreateHandoff fields = ["shift1_lead","shift1_sec"] -
PK incrementing when adding new TestCase
I realized when I'm adding new TestCase PK in old TestCase is incrementing. For example, I'm testing .get_absolute_url method: def get_absolute_url(self): return reverse('linkdetail', kwargs={'pk': self.pk}) with this test def test_get_absolute_url(self): obj = Link.objects.get(title="test_tile") self.assertEqual(obj.get_absolute_url(), "/link/1/") and to this point everything is okay and test is passing, but when I add another TestCase class LinkCommentTestCase(TestCase): def setUp(self): user = User.objects.create(username="test", password="asd") link = Link.objects.create(title="test_tile2", link="http://google.com", author=user) comment = LinkComment.objects.create(author=user, link=link, content="asd") def test_get_comments_count(self): obj = LinkComment.objects.get(content="asd") im getting this error ====================================================================== FAIL: test_get_absolute_url (links.tests.test_models.LinkTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/x/Desktop/x/links/tests/test_models.py", line 72, in test_get_absolute_url self.assertEqual(obj.get_absolute_url(), "/link/1/") AssertionError: '/link/2/' != '/link/1/' - /link/2/ ? ^ + /link/1/ ? Why is this happening and how can I prevent this? -
Unique field case insensitive constraint
I am trying to ensure that all tags are unique when converted to lowercase. However, when I run the migrate on the following model I receive the following error: api.Tag: (models.E012) 'constraints' refers to the nonexistent field 'Lower(F(name))'. class Tag(models.Model): name = models.CharField(max_length=30) class Meta: constraints = [ models.UniqueConstraint( fields=[Lower('name')], name='unique_name' ), ]