Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect to routes that has the same url in multiple apps
I'm new to coding so excuse me if this was a silly question but I couldn't find a clear answer anywhere. So I have a django project with two apps inside it, both of them has the root '/',what is the exact format and implementation to use return redirect('/')to let django differentiate between these two roots in different apps maybe using naming routes. a step by step guide will be appreciated, thank you in advance. -
Django REST get() returned more than one object
I'm trying to use nested serializers to get a response which includes fields from two models. However i get this error get() returned more than one Location -- it returned more than 20! When looking for a solution it seems that this error comes up when using get but in my view i use filter instead. I am trying to understand what part of the code causes the error. Models.py class Microcontrollers(models.Model): name = models.CharField(max_length=25) serial_number = models.CharField(max_length=20, blank=True, null=True) type = models.CharField(max_length=15, blank=True, null=True) software = models.CharField(max_length=20, blank=True, null=True) version = models.CharField(max_length=5, blank=True, null=True) date_installed = models.DateField(blank=True, null=True) date_battery_last_replaced = models.DateField(blank=True, null=True) source = models.CharField(max_length=10, blank=True, null=True) friendly_name = models.CharField(max_length=45, blank=True, null=True) private = models.IntegerField() datetime_updated = models.DateTimeField(db_column='DateTime_Updated') # Field name made lowercase. class Meta: managed = True db_table = 'microcontrollers' verbose_name_plural = "Microcontrollers" def __str__(self): return self.friendly_name class StationStatus(models.Model): microcontroller = models.ForeignKey(Microcontrollers, models.DO_NOTHING) date_from = models.DateField() date_to = models.DateField(blank=True, null=True) location = models.CharField(max_length=45) active = models.IntegerField() notes = models.CharField(max_length=100, blank=True, null=True) datetime_updated = models.DateTimeField(db_column='DateTime_Updated') # Field name made lowercase. class Meta: managed = True db_table = 'station_status' verbose_name_plural = 'Station Status' Serializers.py class StationInfoSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = StationStatus … -
Choices in django form
in my form i want to select department from 2 options: some object(every time only one) and None. my form.py class TeamGoalForm(ModelForm): def __init__(self, *args, **kwargs): employees = kwargs.pop('employees') department = kwargs.pop('department') super().__init__(*args, **kwargs) self.fields['employees'].queryset = employees #self.fields['department'].choices = [(1, department), (2, None)] #self.fields['department'].initial = [1] class Meta: model = TeamGoal fields = ('team_goal_title','department','employees', 'team_goal_description', 'gpd_year','team_factor_0','team_factor_1','team_factor_2','team_factor_3','team_factor_weight') widgets = { 'team_goal_title': forms.TextInput (attrs={'class':'form-control', 'placeholder':'Enter the title of goal'}), 'department': forms.Select (attrs={'class': 'form-control', 'placeholder':'Select department'}), } in my view.py I have had: if request.method == 'POST': form = TeamGoalForm(request.POST, employees=employees, department=department) if form.is_valid(): form.save() Here my department is an object. How to implement something like this, 'cos my solution does't work? -
django-rest-framework speed-up endpoint with http requests
I have an application on DRF and there is an endpoint inside which sends an http requests in the loop for each item. Endpoint is very slow because of this, any ideas how to speed it up? example of code class MyView(APIView): def get(self, request: Request) -> Response: for cat in Cats.objects.all(): data = CatsInfoService.get_info(cat) # send http request return Response({"message": "ok"}) -
django form data to pdf or A4 paper
Is it possible to design an A4 paper and create a form in which the user fills in information in the form on the site and django converts the information to the paper that you designed previously and prints it? -
Django count conditionally annotated values in "group-by" statement
Having the following models: class TheModel(models.Model): created_at = models.DateTimeField(default=datetime.now) class Item(models.Model): the_model = models.ForeignKey(TheModel, on_delete=models.CASCADE, related_name='items') How can be calculated the number of models and how many of them have more than 2 items grouped by day? I tried: qs = models.TheModel.objects.all() qs = qs.annotate(contained_items=Count('items')) result = qs.values('created_at__date').annotate( total_count=Count('created_at__date'), models_with_contained_items=Count('created_at__date', filter=Q(contained_items__gt=2)) ) But it raises "OperationalError" "misuse of aggregate function COUNT()" -
How to set the admin site inline choice field fixed based on the index of the inline
My current situation: I have created a model with an inline. With min_num and max_num, I can decide how many inlines a model will have. These values come from the length of a tuple I use inside the inline model. The inline model: In the picture, you can see the inline model has 4 inlines, but the difficulty field is 4 times the same. What I expect: I want the difficulty to be set to the index of the inlines (inline 0 matches tuple 0 no sport level, ...). So the option to change the difficulty shouldn't be possible as well. -
How to make a model field equal to a queryset result
I am new to django and coding in general. I have this project that I am trying to code thats basically an auctions website. I am facing some difficulties structuring the models though. Here are 2 models of all models class Listing(models.Model): title = models.CharField(max_length=64) image = models.URLField(null=True, blank=True) description = models.CharField(max_length=64) starting_price = models.DecimalField(max_digits=7, decimal_places=2) current_price = #highest bid price bids_count = #count of bids lister = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings") def __str__(self): return f"Title: {self.title} ({self.id}), Lister: {self.lister.username}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") bidder = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="bids") amount = models.DecimalField(max_digits=7, decimal_places=2) time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Bid by {self.bidder.username} on {self.listing.title} ({self.listing.id}) for an amount of {self.amount}" I am trying to let the current price equal to the highest bid of that listing current_price = Listing.bid.objects.all().aggregate(Max("amount")) And count the number of bids bids_count = Listing.bid.count() I know we cant place querysets inside models fields like I have done but i did it to demonstrate my issue. Surely there is some way around this but I just cant figure it out. -
django testing serializer got an unexpected keyword argument 'data'
I have a serializer like this: class ExampleSerializer(serializers.Serializer): name = serializer.CharField(require=True) An a test like this: class TestExampleSerializer(TestCase): def test_example_serializer(self): ExampleSerializer(data={'name': 'test_name'}) I see in a lot of places (guides, posts...) that it should works in that way, calling the serializer with 'data' keyword, but I have an error precisely in that point: TypeError: __init__() got an unexpected keyword argument 'data' I see many examples and all looks the same to me, so, what I'm doing bad? The configuration is correct because there's other serializers tested and they works, I don't know why mine not. -
Display a different user's information in a profile (Not the logged in user's)
I'm working on a project for school, it's sort of mini-stackoverflow. So, I have a section where users are able to click on the creator of a post, and it'll take then to a page where they can see said user's information and all the posts they have created. So, so far the code for the user posts list is perfect but I can't get the profile information to be displayed correctly. To explain the problem in a more simple way, it's basically that, if I click on winston1420's profile instead shows me a different profile (of the logged in user) My profile on HTML template <section class="py-5"> <div class="container my-5"> <div class="row justify-content"> <div class="col-lg-6"> <div class="content-section"> <div class="media"> <img class="rounded-circle profile-img" src="{{ user.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <p class="text-secondary">{{ user.first_name }} {{ user.last_name }}</p> <p class="text-secondary">{{ user.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ user.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ user.date_joined }}</p> <p class="text-secondary">Última vez visto: {{ user.last_login }}</p> <p class="mb-0">{{ user.profile.about }}</p> </div> </div> </div> </div> </div> My user's post list <div class="container my-5"> <div class="row justify-content"> <div class="col-lg-6"> <h2>Publicaciones de <strong><a href="">{{ view.kwargs.username }}</a></strong> ({{ page_obj.paginator.count }}) </h2> <br> … -
how should django query be in my function?
I have a model with file field i am trying to download the data after querying from database how should my query be. models.py: class Mymodel(Basemodel): file_processed = models.FileField( upload_to='myfile/ss', validators=[FileExtensionValidator([''])], blank=True, null=True, editable=False, views.py : @api_view(('GET',)) def download_view(request): d = ''' Mymodel.objects.?''' response = HttpResponse( d.file, content_type='', ) return response -
How to return to the same page in django
I have added react to my videos in my project. After reacting on the post i want to stay in the same page. here's all videos template <figcaption class="info-wrap"> <h6 class="title"><a href="{% url 'singlevideo' pk=video.pk cpk=video.category.id %}">{{video.title}}</a></h6> <i style="color:black; font-size:12px;">@{{video.creator}} || {{video.upload_date}}||{{video.category}}</i> <div class="action-wrap"> <div class="price-wrap h5"> after clicking on the title it takes to the page of the video http://localhost:8000/videos/9/5/ and the single video template <figcaption class="info-wrap"> <div style="padding:20px;"> {% if video.pk in like_post %} <a href="{% url 'unliked' pk=video.pk %}"><i class="fa fa-heart" style="font-size:36px;"></i></a> {% else %} <a href="{% url 'liked' pk=video.pk %}"><i class="fa fa-heart-o" style="font-size:36px;"></i></a> {% endif %} </div> views.py def liked(request,pk): post= Uploads.objects.get(pk=pk) already_liked=Like.objects.filter(post=post,user=request.user) if not already_liked: liked_post=Like(post=post,user=request.user) liked_post.save() return redirect('/') def Unilked(request,pk): post= Uploads.objects.get(pk=pk) already_liked=Like.objects.filter(post=post,user=request.user) already_liked.delete() return redirect('/') models.py class Like(models.Model): post=models.ForeignKey(Uploads,on_delete=models.CASCADE,related_name='like_post') user= models.ForeignKey(User,on_delete=models.CASCADE,related_name='liker') date_created= models.DateTimeField(auto_now_add=True) def __st__(self): return str(self.user)+' liked '+str(self.post) urls.py from cmath import sin from django.urls import path from Videos.views import Uploader,show_video,single_video,liked,Unilked urlpatterns = [ path('upload/',Uploader,name="upload_video"), path('',show_video,name="show_video"), path('<int:pk>/<int:cpk>/', single_video,name="singlevideo"), path('liked/<int:pk>/',liked,name="liked"), path('unliked/<int:pk>/',Unilked,name="unliked"), ] i want to stay on the same page after reacting. But the problem is singlevideo take 'pk' and 'cpk' . Thanks in advance. -
GAE Django fails with OperationalError: (2062, 'Cloud SQL socket open failed with error: No such file or directory')
In my Django (+grappelli) admin when a model instnace has 10+ related autocompleted items then all subesquent request fail with OperationalError: (2062, 'Cloud SQL socket open failed with error: No such file or directory') All requests after that and for a few minutes are 500 with the same error. At least once I had to delete all instances and restart the database after it never recovered. Having read the other stackoverflow questions, I suspect that this is a concurrent requests issue (since the autocompleted fields in the admin are ajax requests possibly happening all at once). My issue is that I cannot reproduce this on the staging server no matter how many related items I add. Production is instance_class F4 and staging the default F1. -
Installing Django projects from pypi in your own project
As a relative beginner to Django I would like to know what the best practice is when it comes to using other developer's apps in your own project. I've found a booking/reservation app I want to use in my own project here: https://pypi.org/project/django-reservation/ however, I don't want everything it contains eg. the Product model, as I have a Van model already which would essentially be the 'product' a user would reserve. In this case, I'm wondering if it would be best to either: keep the entire django-reservation app installed (and copy over any files I want to edit, including where I have to update the code because the developer last updated this project 5 years ago), OR not install it and scour the files to copy over any code that I can use in building my own booking/reservation app. I'm concerned about the time it could take to fix unknown bugs in a project this old. -
Ident between django tag {%%} in vs code
I would like to indent my code between the django tags {%%}. e.g from {% for disease in diseases %} <h3 class="card flex flex--center-all grid__element">{{ disease}}</h3> {% endfor %} to this: {% for disease in diseases %} <h3 class="card flex flex--center-all grid__element">{{ disease}}</h3> {% endfor %} Unfortunately Beautify automaticly unindent, and the default formatter in vs code stick all the blocks on the same line. I tried to change the Vs code settings by creating new tags, or new brackets, or changing the way VS code indent. Nothing work. All helps are welcome. -
Generate XML from List in Python
I want to generate a XML-Scheme/XSD out of Lists. The form of the Paths is a list like so: l1 = ['Customers', 'CustomerType', 'B2B', 'Industry', 'Manufacturing', 'ManufactureOfFurniture'] l2 = ['Customers', 'CustomerType', 'B2B', 'Industry', 'Manufacturing', 'ManufactureOfJewellery'] l3 = ['Customers', 'CustomerType', 'B2C', 'Industry' ...] ... And with a dict that has all the classes to corresponding lists: schema_dict = { "c-customertype-b2b-industry-manufacturingoffurnite" : l1, "c-customertype-b2b-industry-manufacturingofjewellery": l2, ... } And out of that i want to create a XML-Schema like this: <xs:element name="customers"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="customertype"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="b2b"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="industry"/> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="manufacturing" type="c-customertype-b2b-industry-manufacturing" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="b2c"> {...} I already have the simpletypes. The Last value in path should have a typename of the simpletype. simpleTypes look like this: <xs:simpleType name="c-customertype-b2b-industry-manufacturing" final="restriction"> <xs:restriction base="xs:ENTITY"> <xs:enumeration value="cars" /> <xs:enumeration value="knifes" /> </xs:restriction> </xs:simpleType> I'm currently working with xml.etree.ElementTree to make Elements but im open for other suggestions. -
Django InvalidCursorName error when Google or Facebook crawler bots request my home page
I have been receiving InvalidCursorName error for a while in my django website and the HTTP_USER_AGENT shows Facebook or Google bots: for example when i mention my website domain in a comment i received this error immediately. Migrations are all done and i have run the commande python manage.py migrate --run-syncdb but i still receiving this error. -
How to initialize foreign key into a form in Django
I have this two models, one Voucher model is a foreign key to the RegistrationForm model. Anytime someone a search and the in item exist in the voucher model, I want it to be initialized to the Registration form and saved Error Message raise ValueError( ValueError: Cannot assign "'phr201'": "RegistrationForm.voucher" must be a "Voucher" instance. Models class Voucher(models.Model): name = models.CharField(max_length=120, null=True, blank=True) class RegistrationForm(models.Model): voucher = models.OneToOneField(Voucher, on_delete=models.CASCADE) full_Name = models.CharField(max_length=200,) Date_of_birth = models.CharField(max_length=100) View.py class RegistrationProcessing(generic.CreateView): form_class = Registerform template_name = 'RegistrationProcessing.html' def form_valid(self, form): form.instance.voucher = self.request.GET.get('q') return super().form_valid(form) def get_context_data(self, **kwargs): context = super(RegistrationProcessing, self).get_context_data(**kwargs) query = self.request.GET.get('q', default='') print(query.id) context.update({ 'job_listing': Voucher.objects.filter( Q(name__iexact=query) ) }) return context -
Django object.filter(X__contains = 210922143300) gives error
Please help me out def search_venues(request): if request.method == "POST": searched = request.POST['searched'] titles = Information.objects.get(id=210922143300) print(titles) titles = Information.objects.filter(id__contains=21092214330) print (titles) return render(request, 'search_titles.html', {'searched': searched, 'titles': titles}) else: return render(request, 'search_titles.html', {}) the first print statement gives me: <QuerySet [<Information: Wind energy can deliver vital slash to global warming>]>, like i expect the second print statement gives me: enter image description here What should i do, ofc in the future i want to pass my searched variable -
Filtering a table by a <select> clause with Django
I have a table that needs to be filtered on a select HTML clause giving a functionality like an excel filter. How can this filtering can be implemented? I want to filter it by owner Table Example: <table class="table table-hover"> <thead class="table-bordered"> <tr> <th scope="col">NumberID</th> <th scope="col">Title</th> <th scope="col"> Owner <select name="columns" class="form-select" aria-label="Default select example"> <option selected>All</option> <option value='option1' id="filterOwner">1</option> <option value='option2' id="filterOwner">2</option> <option value='option3' id="filterOwner">3</option> <option value='option4' id="filterOwner">4</option> <option value='option5' id="filterOwner">5</option> </select> </th> <th scope="col">Status</th> </tr> </thead> <tbody id='myTable'> {% for data in dataset %} <tr> <td>{{ data.NumberID }}</a></td> <td>{{ data.title }}</a></td> <td>{{ data.owner }}</a></td> <td>{{ data.currentMonthStatus }}</a></td> <td> <a type="button" class="btn btn-outline-success btn-sm" href="/updatecontrol/{{data.NumberID}}">edit utility control</a> </td> </tr> {% endfor %} </tbody> -
How do i serve files uploaded by the user in a locally deployed django project
I deployed my django app using python manage.py runserver 0.0.0.0:8888. And i set debug to False. HOw do i serve files uploaded by the user. The app is an internal app and can only be accessed by staffs of the organization. So they want the media files to be stored locally on the server -
Integrating Model, Serializer and Algorithm in a tree structure coherently
I have a tree-like structure of objects, linked to each-other with foreign keys. Each object's fields are stored in a model. Each object has a serializer. Each object has a few routines, now stored in an algorithm class. There is a serializer that recreates the tree structure into a nested dictionary. How do I merge these 3 facets of each object into a single object? Should I create a child object, which inherits from the three others (scary)? or should I include the model and the serializer inside my algo class as inner objects (seems more modular and independent)? -
matching query does not exist. in django
Hi This is my Project I needed define two get_absolute_url in my project get_absolute_url one models.py def get_absolute_url(self): return reverse("cv:resume_detial", args={self.id, self.slug}) urls.py path('resume-detial/<int:resume_id>/<slug:resume_slug>', views.ResumeDetialView.as_view(), name="resume_detial"), views.py class ResumeDetialView(View): template_name = 'cv/resume-detial.html' def get(self, request, resume_id, resume_slug): resumes = ResumeDetial.objects.get(pk=resume_id, slug=resume_slug) return render(request, self.template_name, {'resumes':resumes}) This is a work But other get_absolute_url is does not work models.py def get_absolute_url(self): return reverse("cv:project_detial", args={self.id, self.project_slug}) urls.py path('project-detial/<int:project_id>/<slug:projects_slug>', views.ProjectDetialView.as_view(), name="project_detial"), views.py class ProjectDetialView(View): template_name = 'cv/project-detial.html' def get(self, request, project_id, projects_slug): projects = ResumeDetial.objects.get(pk=project_id, slug=projects_slug) return render(request, self.template_name, {"projects":projects}) django messages DoesNotExist at /project-detial/1/todo-django ResumeDetial matching query does not exist. I am a beginner and thank you for your help -
when i deploy django application on heroku. My websocket is is disconnect when i tried to connect
heroku Application Logs INFO failing WebSocket opening handshake ('Internal server error') WARNING dropping connection to peer tcp4:10.1.40.17:31231 with abort=False: Internal server error DEBUG WebSocket closed for ['10.1.40.17', 31231] my settings.py import redis CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.pubsub.RedisPubSubChannelLayer", "CONFIG": { "hosts": [("*", 6379)], }, }, } -
ReactJS with graphql CORS Issue
I have running django backend on http://127.0.0.1:8000 and I want to request it with reactjs frontend. As you can see below, I can see the successful response in the Insomnia app. But, When I want a request with reactjs frontend, I get a CORS ERROR. I check the request in the inspect networks and I saw a similar request payload with insomnia.