Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display survey questioner with different choices in template
I am working on a survey app where users that have administrator role can login to the admin dasboard and create surveys. A survey can have multiple questioniors. When creating a survey the admin users can add either checkbox choice, radio choice or a text box option to a question. At the moment these functionality is working fine, what i need help with is how to display the survey questions to the surveyor page. How can i display all the questioners with option such as checkbox, textbox etc. The current template can only display the questions with radio choices. class Survey(models.Model): title = models.CharField(max_length=200) # creator = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) archive = models.CharField(max_length=200, default='') def __str__(self): return self.title class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) enter_question = models.CharField(max_length=900) def __str__(self): return self.enter_question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=100) choice_text = models.CharField(max_length=100) choice_check = models.CharField(max_length=100, null= True) <div class = "jumbotron container centerdv header-top"> <h2>{{survey.title}}</h2> </div> <div class="d-flex flex-column"> <form method = "post" action =#> <input type = "hidden" name = "survey_id" value = {{survey.id}}> {% csrf_token %} {% for question in questions %} <div class="p-2"> <h4 class="header"> Question {{ forloop.counter }}: {{ question.enter_question }} </h4> </div> … -
mapping request.data into a onetoone field
I have a JSON request data as follows and I want to process that using Django serializer and views in order to create the record in the database using a POST request. { "username":"user1", "first_name":"name1", "email":"name1@gmail.com", "phone": "123456", "app_id": "435673339303abc" } And following are my Django database models and serializer where a custom user model is created which has a onetoone django user model: models.py from django.contrib.auth.models import User from django.db import models class CustomUserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=20, blank=True) app_id = models.CharField(max_length=20, blank=True) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'email') class CustomUserSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = CustomUserModel fields = ('user', 'phone', 'app_id') def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) customuser, created = CustomUserModel.objects.update_or_create(user=user, defaults={ 'phone': validated_data.pop('phone'), 'app_id': validated_data.pop('app_id')}) return customuser views.py class usersApi(generics.ListAPIView): serializer_class = CustomUserSerializer def get_queryset(self): queryset = CustomUserModel.objects.all() return queryset def post(self, request, format=None): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(raise_exception=ValueError): serializer.create(validated_data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) But with this serializer and views, I have to pass a nested json data as follows with user object which I don't want to. { "user": { "username":"user1", "first_name":"name1", "email":"name1@gmail.com" }, "phone": "123456", "app_id": "435673339303abc" … -
In Django I want to fetch the selected file name file is in my media folder so I want to fetch it and display it in html that the file is selected
This is my html code for update the form I have the uploaded file through a html form and the pdf file is getting stored in my media folder and the file name in database, so like the text fields I also want to retrieve the selected file from the media folder the value ="{{i.cv}}" is not working like I did it in text fields so basically I have two html one is for filling up where there is also file field am uploading pdf files in it and it is storing in media folder another html for updating the data in there the upload cv does not select any file what's the solution for this. this is my html <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black">Upload CV</label></br> <input type="file" name="cv" id="cv1" value ="{{i.cv}}"> </div> </div> here is models.py class ApplyForm(models.Model): cv = models.FileField(upload_to='') this is views.py def update(request, id): i.cv = request.FILES['cv'] I just want the file to be selected during edit I am uploading pdf files -
How I can get the object from the for loop in Django
I try to get object from foor loop and pass it to context -> template but when I try to do this it return null values for example here for post in comma: comment = PostCommentIDF.objects.filter(post=post) #here I try to get the object out side post_with_comments.append({post, comment}) print(comment.all()) So in this example I can't pass it to template because it return null but here it works when I try to print the values inside the foor loop for post in comma: comment = PostCommentIDF.objects.filter(post=post) post_with_comments.append({post, comment}) print(comment.all()) So My qustion here how I can pass the comment to template and return actual values not null values -
Python pipeline error when deploying to EC2 setuptools_rust
Hello I'm having this problem when trying to deploy a django application to aws, the app runs perfectly locally but when trying to deploy to aws this error shows up. like this I tried to install that manually, but it doesn't work that way. -
Documenting a file download on RESTApi
I have the following view which returns a file, the thing is that I don't know how to write a documentation for this route. This doesn't return JSON, it returns a file based on the Content-type that the client has asked for. def get(self, *args): """ * ``:param request:`` GET request to send with ``Authorization: Bearer token_id``. * ``:return:`` Authenticated Seeker CV file """ seeker_cv_file = CV.objects.get(seeker=self.get_queryset()).cv_file return HttpResponse(seeker_cv_file, content_type=self.request.content_type) I don't have any idea on how to write a conventional documentation block for this route. Any suggestion? I am using drf-spectacular by the way. -
Python/DJANGO: How to modify existing variable and also import new variables using import *
I have a file test.py with list_sample = [1,2,4] Now, I want to append to the list from another file eg: test2.py list_sample =+ [10,11] # also I have many other things in this script a=10 c=10+a and modify test.py as list_sample = [1,2,4] # I want to import all the variables from test2.py but also append the list_sample # I cant do that directly in this file. Because this is like blueprint from .test2 import * print(a+30) print(list_sample) But this gives an error list_sample not defined The only way I can do this change test2.py to list_sample = [1,2,4,10,11] # also I have many other things in this script a=10 c=10+a One more option i have is change test2.py to from .test import list_sample list_sample += [10,11] # also I have many other things in this script a=10 c=10+a but this will lead to circular imports Conclusion This is not possible so then i decided to just go like this. Add some segregation in the test2.py # variables from master file # copy them from the test.py list_sample = [1,2,3] # changes to variables from master file list_sample =+ [10,11] # new variables a=10 c=10+a Reason I want this … -
django.db.utils.OperationalError: FATAL: sorry, too many clients already
I am running a Django app on Django's development server with PostgreSQL as the backend database. I got this error: django.db.utils.OperationalError: FATAL: sorry, too many clients already when I was doing a load testing using Locust. My Locust script runs the test with 100 concurrent clients: env.runner.start(100, spawn_rate=100, wait=True) I have seen several answers on SO, such as: Getting OperationalError: FATAL: sorry, too many clients already using psycopg2 Getting "FATAL: sorry, too many clients already" when the max_connections number is not reached Django+Postgres FATAL: sorry, too many clients already From those threads, I think I understand the cause of the error, but I am still very confused. How does it scale in real life if PostgreSQL cannot handle even 100 concurrent clients? Does it have anything to do with the fact that I am using a development server? Will it help if I use Gunicorn? If some connection clean-up is needed, is it something that I should implement in the Locust script? I am quite new in this area, so I apologize if the answers to those questions are obvious. -
Betfair - Result After Match Completion without placing bet
We are fatching odds from betfair API. How can we see result of that game/odds without placing bet on betfair ? -
Django REST framework change JSON structure
I am working on a Django project, the data that I have now is something like this: [ { "sid": "A1", "annofk": [ { "id": 8, "chrs": "chr1", "seq_start": 18262640, "seq_end": 18262660, }, { "id": 9, "chrs": "chr1", "seq_start": 18262640, "seq_end": 18262660, }, { "id": 10, "chrs": "chr1", "seq_start": 18262640, "seq_end": 18262660, } ] }, { "sid": "A2", "annofk": [ { "id": 5, "chrs": "chr1", "seq_start": 24613130, "seq_end": 24613155, }, { "id": 11, "chrs": "chr1", "seq_start": 24613130, "seq_end": 24613154, } ] } ] I really want to change the structure into this: [ { "sid": "A1", "annofk": { "id": 8, "chrs": "chr1", "seq_start": 18262640, "seq_end": 18262660, } }, { "sid": "A1", "annofk": { "id": 9, "chrs": "chr1", "seq_start": 18262640, "seq_end": 18262660, } }, { "sid": "A1", "annofk": { "id": 10, "chrs": "chr1", "seq_start": 18262640, "seq_end": 18262660, } }, { "sid": "A2", "annofk": { "id": 5, "chrs": "chr1", "seq_start": 24613130, "seq_end": 24613155, } }, { "sid": "A2", "annofk": { "id": 11, "chrs": "chr1", "seq_start": 24613130, "seq_end": 24613154, } } ] These data are from two tables (models). These data are from a reverse look up results. Two Serializers is here: class AnnotationSerializer(serializers.ModelSerializer): class Meta: model = annotation fields = "__all__" class … -
How to calculate the date of a Blog post in hours days months and years?
I have a Blog Post and would like to calculate the day, months and years elapsed? class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') created_on = models.DateTimeField(auto_now_add=True) I would like it in a format like 1 year ago, 2 days ago, 2 hrs ago. -
How do I update data on SQLite Database using HTML
I'm trying to allow users to update the information that they have provided by clicking the edit icon on my html webpage, but I am unsure on how to start. Below are the codes used to add new data and retrieve the newly added data: def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': name = request.POST['name_field'] email = request.POST['email_field'] claim = request.POST['claim_field'] claimtype = request.POST.get('claimtype') description = request.POST['description_field'] receipt = request.POST.get('receipt_field') cheque = request.POST.get('Cheque') ins = SaveClaimForm(name=name, email=email, claim=claim, claimtype=claimtype, description=description, receipt=receipt, cheque=cheque) ins.save() print("The Data has been written") return render(request, 'Login/newclaim.html/', context) viewclaims def viewclaims(request): context = initialize_context(request) user = context['user'] if user.get('email', None): claims = SaveClaimForm.objects.filter(email=user.get('email', None)) return render(request, 'Login/existingclaims.html', {'claims':claims, 'user':user}) SaveClaimForm Models class SaveClaimForm(models.Model): name = models.CharField(max_length=200) email = models.EmailField() claim = models.DecimalField(decimal_places=2, max_digits= 6) claimtype = models.CharField(max_length=200) description = models.TextField(max_length= 500) receipt = models.FileField() cheque = models.CharField(max_length=200) -
Run a django update but call the save method
Is there a way to do the following: Asset.objects.filter(pk=asset.pk).update(**item) And also call the .save() method? I think I've read somewhere that you can run an update on the actual instance and not go through the objects manager. How would that be done? Currently I'm doing the following, which is quite repetitive and inefficient: a = Asset.objects.filter(pk=asset.pk).update(**item) a.save() -
pip freeze is not providing correct package versions
I had a remote developer help me with a Django Channels project, and what he did works well. Now I am trying to reproduce his work on my production server, and am stuck... (Unfortunately, the remote developer is not available to ask as he seems to have fallen off planet earth) When I do pip freeze on his project I get: (Among many other items that all match my pip freeze exactly) channels==3.0.2 channels-redis==2.4.2 when I try to install these same packages on my project I get the error: File "./site/asgi.py", line 31, in <module> url(r"^stream/(?P<device_id>[\d\-]+)/$", StreamConsumer.as_asgi()), AttributeError: type object 'StreamConsumer' has no attribute 'as_asgi' Which is referring to my asgi.py file: application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": django_asgi_app, # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ url(r"^stream/(?P<device_id>[\d\-]+)/$", StreamConsumer.as_asgi()), url(r"^status/(?P<device_id>[\d\-]+)/$", StatusConsumer.as_asgi()) ]) ), }) After some searching on this error, I came to the conclusion that this is due to older channels-redis So I did pip install channels-redis==3.2.0 Now the error is gone, great. But now the websockets keep disconnecting and crashing due to these 2 errors: <WebSocketProtocol client=['127.0.0.1', 59462] path=b'/ws/stream/streaming'> took too long to shut down and was killed. and channels_redis/core.py", line 667, … -
How to concatenate int to str in django template
I have a views integerfield in my model Post I am not able to concatenate the integer field in my django template. {{post.views||stringformat:"s"}} view {{ post.views||stringformat:"s"}}|pluralize }} I would also like to have it pluralized -
The current path, api/v1/latest-products, didn't match any of these
I am experiencing this problem following a tutorial and I can't identify the error. Tried changing to re_path and did not work. I created one product in the django admin database already so it should be showing something else instead of the 404 in the address. "GET /api/v1/latest-products HTTP/1.1" 404 7667 Not Found: /latest-products Below the code: URLS.PY urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('product.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) VIEWS.PY from rest_framework.views import APIView from rest_framework.response import Response from .models import Product from .serializers import ProductSerializer class LatestProductsList(APIView): def get(self, request, format=None): products = Product.objects.all()[0:4] serializer = ProductSerializer(products, many=True) return Response(serializer.data) MODELS.PY class Product(models.Model): category = models.ForeignKey(Category, related_name = 'products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank= True, null = True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) Thanks for the help. -
Why are comment permalinks for django-comments-xtd going to example.com in Wagtail?
I'm setting up comments in Wagtail using django-comments-xtd and one thing I'm having trouble figuring out is why my comment permalinks keep going to https://example.com/news/bloggy-test-post/#c1 instead of https://localhost:8000/news/bloggy-test-post/#c1. I found a user with a similar issue in the Wagtail Google group who discovered that they had "example.com" set as their site in Wagtail admin. But I have only one site in my settings and it's currently set to "localhost" with a port of 8000. Screenshot of the Wagtail admin site showing there is one site set to localhost with a port of 8000 I searched all my files and libraries for "example.com" and the only other setting I found was the BASE_URL setting in base.py. I tried changing that to http://localhost:8000 and the comment permalinks are still being directed to "example.com". Is there another setting I'm missing? Or another way I'm supposed to get the URL? Currently, I have this code for grabbing the url in my models.py file: def get_absolute_url(self): return self.get_url() This is the comments section code from my template: {% get_comment_count for page as comment_count %} <p> <a href="{% pageurl page %}#comments"> {{ comment_count }} comment{{ comment_count|pluralize }} </a> {{ comment_count|pluralize:"has,have" }} been posted. </p> {% render_xtdcomment_tree … -
.main not formatting correctly - Django
I have the following two files where home inherits from base. base.html: <html> <head> <style type="text/css"> .sidenav { height:100%; width:160px; position: fixed; z-index:1; top:0; left:0; background-color:#111; overflow-x: :hidden; padding-top:20px; } .sidenav a { padding:6px 8px 6px 16px; text-decoration: none; font-size:25px; color: #818181; display:block; } .sidenav a:hover{ color:#f1f1f1; } .main{ margin-left:300px; padding: 0px 10px; } </style> <title>{% block title %}Brandon's Site{% endblock %}</title> </head> <body> <div class="sidenav"> <a href="/">Home</a> </div> {% block content %} {% endblock %} </body> </html> home.html: {%extends 'main/base.html' %} <head> <style type="text/css"> .main{ margin-left:300px; padding: 0px 10px; } </style> </head> <div class = "main"> {% block content %} Add New Plant <form method = "post" action = ""> {% csrf_token %} {{form.as_p}} <button type = "submit", name = "save">Add New Plant</button> </form> {% endblock %} </div> </html> However, the form in home.html for some reason isn't recognizing the left margin and is stuck under the sidebar that I've created to the left. It ends up looking like this: Why isn't it offset to the right like the CSS implies? -
How to post Multiple Json Fields/Objects in Django using JavaScipt
I am Following a Short Tutorial on Django API where I have extended the Model to include a couple more Fields I can get the Front End working but can not Post data for the new Fields The Block of Code Below is where I would like to add a few more Fields to Post..., at least that is where I think it should go...?? var title = document.getElementById('title').value fetch(url, { method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body: JSON.stringify({'title': title }) } ).then(function(response){ buildList() document.getElementById('form').reset() }) }) **** Model **** from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) name = models.CharField(max_length=75, blank=True, null=True) price = models.FloatField(default='0.00') productdesc = models.CharField(db_column='ProductDesc', max_length=75, blank=True, null=True) # Field name made lowercase. producttype = models.CharField(db_column='ProductType', max_length=75, blank=True, null=True) # Field name made lowercase. producttypefamily = models.CharField(db_column='ProductTypeFamily', max_length=75, blank=True, null=True) # Field name made lowercase. numworkstation = models.IntegerField(db_column='Numworkstation', default='0') # Field name made lowercase. numserver = models.IntegerField(db_column='Numserver', default='0') # Field name made lowercase. addlconsole = models.IntegerField(db_column='addlconsole', default='0') # Field name made lowercase. productcomplexitybase = models.FloatField(db_column='ProductComplexityBase', default='550') # Field name made lowercase. productcomplexityfac = models.FloatField(db_column='ProductComplexityFac', default='1.0') # Field name made lowercase. digital = models.BooleanField(default=False,null=True, blank=True) def __str__(self): … -
python /Django filtering data
I am quite new to Programming ,I have created 3 model children fields : name , is_active and is_sponsored Sponsor fields : Name Sponsorship fields :children(foreign key), sponsor(foreign key), start_date and end_date. i need to set a condition only those only those children shall be displayed that have less than 2 sponsorship on current date and are active. i have already set filter in sponsorshipForm relating to is_sponsored. but to check and change is_sponsored value with regards to above condition. basically i and unable to write logic for the above condition please help -
Trouble deploying python on Heroku
I forked some code from GitHub and am trying to get it working as an app on Heroku. I'm pretty new to coding so your help is greatly appreciated! My goal is to get the code from GitHub (booking bot) to run so my boss can make tennis court reservations automatically. He likes to play at certain times and the reservations get taken within seconds of being released. I found this code that seems like it will solve the problem and am hoping to get it running. I was able to deploy it on Heroku by connecting to GiHub and made some of the changes necessary but I'm getting this message: Not Found The requested resource was not found on this server. Here's a link to the app on Heroku: https://gary-reserve.herokuapp.com/ Here's a link to my fork on GitHub: https://github.com/GaryKentTeam/booking_bot Thank you for your help! a -
Python/Django URls
Disclamer.....this is an assignment! Can some one tell me why I am getting Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%20%25%20url%20'detail'%20user%20%25%20%7D Using the URLconf defined in bobbdjango.urls, Django tried these URL patterns, in this order: [name='home'] profile [name='profile'] user_detail/<str:user_id> [name='detail'] The current path, { % url 'detail' user % }, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I think its a problem with my URL but I am not seeing source of error. I would just like to click on the link on the home page and move to the user details page. See code below... My Home page <body> {% block content %} <h1>This is home page</h1> <div> <!-- <a href="{% url 'profile' %}">Your profile</a> --> {% for user in users %} <a href="{ % url 'detail' user % }"> <h3>{{user.first_name}}</h3> </a> {% endfor %} </div> {% endblock %} </body> My main URL urlpatterns = [ ## path('admin/', admin.site.urls), path('', include('bobbpets.urls') ), ## path('bobbpets/<int:user.id/>', views.userDetails, name='userDetails'), ] My app URL urlpatterns = [ ## path('admin/', admin.site.urls), path('', views.home, name='home'), path('profile', views.profile, name='profile'), … -
django forms to_field_name for model choice field not selected with instance
Two simple models for example: A product that has a foreign key of warehouse. class Warehouse(models.Model): ... uuid = models.UUIDField(editable=False, default=uuid.uuid4) ... class Product(models.Model): ... warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) ... It is required to hide the PK(ID) of warehouse from select's options to customer. So I apply the to_field_name in the form as below class ProductForm(forms.ModelForm): ... warehouse = forms.ModelChoiceField( queryset=Warehouse.objects.all(), to_field_name='uuid',) # using UUID instead of pk ... Then the pk is replaced by uuid. The problem appears that when I try to edit an existing product, the current warehouse of the instance is not selected anymore. -
I need to run an query on django but i am unable to genrate Algorithum
I have These models in Django class Course(models.Model): Title = models.CharField(max_length=200, unique=True) Card_Title = models.CharField(max_length=200, default='Nothing') Description = RichTextField(blank=True, null=True) Course_Image = models.FileField(upload_to='CoursesImages') Progress = models.IntegerField(blank=True, null=True) date = models.DateField(default=timezone.now, blank=True) def __str__(self): return self.Title class Lesson(models.Model): Course_id = models.ForeignKey(Course, on_delete=models.CASCADE) Number = models.IntegerField() Title = models.CharField(max_length=200) Completed = models.BooleanField(default=False, blank=True) date = models.DateField(default=timezone.now, blank=True) def __str__(self): return self.Title + ' (' + str(self.Number) + ')' class Topic(models.Model): Title = models.CharField(max_length=100) Topic = models.FileField() Lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) Completed = models.BooleanField(default=False, blank=True) date = models.DateField(default=timezone.now, blank=True) def __str__(self): return self.Title How its work : Every Lessons Will Have one Course So We have Many Lessons in one Course And one Topic can have one Lesson So We have many Topic in one Lesson **I Need To Figure out quey like this {'Lesson1':[Topic1,Topic2,Topic,3,Topic,4],'Lesson':[Topic1,Topic2,Topic,3,Topic,4],........} We will give course id Relevant Lessons and Topic will have to be fetched -
Django model - query with date arithmetic on model with multiple DateTimeField fields
I am using Django 3.2 I have a model like this: class FoodItem(models.Model): display_date = models.DateTimeField() expiry_date = models.DateTimeField() safe_to_eat_days_after_expiry = models.SmallPositiveInteger() # ... I want to run a query to get all items that have expired, but are still safe to eat. This is what I have so far: criterion1 = Q(expiry_date__gt=date.today()) criterion2 = Q(???) # expiry_date +timedelta(safe_to_eat_days_after_expiry ) <= date.today() FoodItem.objects.filter(criterion1 & criterion2) How do I implement this?