Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing the choices of the model in the ModelSerializer
please I need your help, I have choices in the model and make model Serializer from this model but need to modify on those choices as i use filterset in the Serializer so i need to add more options in the dropdown menu, here is the code. Serializer.py: class BlaListSerializer(serializers.ModelSerializer): STATUS_new1='new1' STATUS_new1='new2' STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_new1, _('New1')), (STATUS_new2, _('New2')), (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) status = serializers.ChoiceField(choices=STATUS_CHOICES) class Meta: model = Bla fields = ( "id", "title", "status", ) model.py: class Bla(ProjectBaseModel, AuditLogMixin): STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) title = models.CharField(max_length=200, blank=True, null=True, verbose_name=_('Title')) status = models.CharField(max_length=200, blank=False, null=True, choices=STATUS_CHOICES) view.py: class MyBla(ListAPIView): serializer_class = BlaListSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['status', ] my problem is that the status isn't updated with the new options in the DRF -
How does Django manage different subdomains on one Django project?
I want my Django project to be accessible at many different endpoints. For one app, I want it accessible at app.domain.com and for another app I want it accessible at dashboard.spira.ai. How can I achieve this? I am using AWS Elastic Beanstalk and Route 53. I tried looking at Django's djangoproject.com and their Github repo, as they do this. However, I couldn't figure it out. Thanks! -
Formatting a JSON Response to build a URL
I'm incredibly stuck on trying to format receive a JSON response, and format it. Order of operations: Query a REST API endpoint (https://endpoint.com/api/v1/employee?id={username}) Receive JSON response: {"employee":{"full name":"Example Name","function":"Role","office":"Office Location",team":"Team 1|Team 2|Team 3|"}} In my base.js file within my django app, I am hoping to extract the team strings and pass them into another URL. What way can I do this? When I $.getJSON from the endpoint I receive responseJSON, responseText, etc. but I'm unable to pull them out/use them in any way. -
How can I access parent model fields in a form using the child model?
For context, I'm trying to create a form that allows users to upload info about their own custom Pokemon. Basically, they are creatures that you can catch, name, and level up. To draw a comparison, it is a similar concept to dogs; there are labradors, German Shepherds, huskies, etc. that would be variations of a base Dog model, but then each individual would have a name and other defining characteristics. I've created Pokemon and CustomPokemon models and imported the latter into my forms.py file. I'm trying to access some parent fields but am unable to: from django import forms from .models import CustomPokemon class PokemonForm(forms.ModelForm): class Meta: model = CustomPokemon fields = ['pokemon.poke_name', 'name', 'level'] The poke_name field is inherited from the parent Pokemon model while the other two fields belong to the CustomPokemon model. I'm getting this FieldError: Unknown field(s) (pokemon.poke_name) specified for CustomPokemon. The issue isn't resolved by using poke_name, so I'm curious how I can access the parent model's fields so they can be displayed in the form. -
Why is my print statement not showing up in django runserver?
I've been using django for only 3 days and the biggest problem that I've had with it is that i can't print() stuff with it in the runsever terminal i'm using django 2.1.5 this is what I've done def test(request): print('test') return HttpResponse('test') the code works fine but it's not displaying the print(), it seems to work with everyone else is maybe there's another way to display it to the terminal? I've tried using python logging as well it's still not displaying anything P.S sorry for such a simple question but i'm that kind of guy that can't read documentation -
How to correctly query to a Foreign Key in Django?
I have a group of models Cluster, Server and Service which have a relationship, through a ForeignKey, one-to-many, as the following snippet: class Server(models.Model): cluster = models.ForeignKey(Cluster, null=True, on_delete=models.PROTECT) shortname = models.CharField(max_length=20, null=False) . . . class Service(models.Model): host_server = models.ForeignKey(Server, null=False, on_delete=models.PROTECT) name = models.CharField(max_length=20, null=False) technology = models.CharField(max_length=20, null=False) . . . And now I am trying to get a set of Servers in a query, along with the related Services using def infra(request, cluster_name): cluster = Cluster.objects.get(name__iexact=cluster_name) servers = Server.objects.filter(cluster_id=cluster.id).order_by('shortname') services = Service.objects.filter(host_server__in=servers).order_by('id') template = 'webapp/infra.html' context = { 'cluster':cluster, 'servers':servers, 'services':services, } return render(request, template, context) However, on the view, I am getting all the services in a single QuerySet instead of a QuerySet per Server containing only the Services associated with it. As a workaround to this, I used the following: <h5>Services</h5> <ul class="list-group"> {% for service in services %} {% if service.host_server_id == server.id %} <li class="list-group-item">{{ service.name }}</li> {% endif %} {% endfor %} </ul> But I have the feeling that there must be a way to iterate through the services of each server in a more elegant way than going through absolutely all of the services each time and then deciding if … -
Django field lookup - sequence of letters
I would like to be able to search trough a database attribute with sequences of letters rather than words. Example: The MySQL database has an attribute called breadcrumb_text containing the following: HomeMonclerMenClothingTrousersMonclerTrousersMonclerTrousers With my current code (see below), if I search with "Moncler Trouser" as keywords, or just "Moncler", no result will be returned. product_list = Products.objects.filter(Q(breadcrumb_text__icontains= search_text)).all() I have to search for the precise attribute to get a result. I would like the code to look for any sequence of letters contained in the attribute that matches each keywords. Can someone help me with that? Many thanks in advance, Kind regards -
Django - How to change the default queryset in a view if a filter is used?
I have a Django project, in which, in my view, I have this: def get_queryset(self, **kwargs): qs = super(OrderTableView, self).get_queryset() if self.request.user.profile.store is not None and self.request.user.is_superuser is False: qs = qs.filter(store=self.request.user.profile.store) today = datetime.datetime.now().date() qs = qs.filter(total__gt=0).filter(address__isnull=False).filter(location__isnull=False).filter(date__date=today).order_by('-date') return qs This works correctly, I want only the orders from the day to be displayed when the view loads, and this works correctly. However, in the view I also have filters for the date, which I want to use to filter the date if the user so chooses. This filter, for example, filters all the dates after the date selected in the filter. def filter_date(self, queryset, name, value): yesterday = datetime.date(year=value.year, month=value.month, day=value.day) - datetime.timedelta(days=1) queryset = queryset.filter(date__gt=yesterday) return queryset The problem is that, as far as I understand, the get_queryset method works first, and so, when arriving to the filters, the queryset already excludes all dates that are not from today, which is fine when the view loads, but should not always occur, since sometimes I'd like to include orders in dates other than today, if I'm searching, for instance. Is there a way in Django to set an initial queryset to a view, but then using a different queryset … -
Can't pass model data in templates django
I want to pass data from 'About' model to html template, but I can't figure out what is going wrong.. as I am new to Django. I gave lot of time to it.. but it still remains the same: from django.db import models class About(models.Model): image = models.ImageField(upload_to = 'pics') desc = models.TextField() views.py from django.shortcuts import render from .models import About def index(request): abt = About.objects.all() return render(request,'home/index.html',{abt:'abt'}) html <img src="{{abt.image}" alt="profile photo"> <p>{{abt.desc}}</p> -
django : calculate with function each line of your db
I would like to calculate 'total' for each line, with the following code, it shows only last line total, not each line total. class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) def total(self): items = self.invoiceitem_set.all() for item in items: amount_due = (item.price * item.quantity) return round(amount_due, 2) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) HTML {% for product in object.invoiceitem_set.all %} <tr> <td>{{product.product}}</td> <td>{{product.price}}</td> <td>{{product.quantity}}</td> <td>{{object.total}}</td> </tr> -
How can I redirect in class with return statement?
In my views.py file I have as_view class called QuestionCreateView and in that class form_valid I am returning return super().form_valid(form) so how can I return also redirect when user is creating(asking) question?, while cant return 2 things, because it's returning tuple -
Showing the students that belong to a trainer
I want to get all the students that belongs to a specific teacher in django-rest-framework. I have 2 classes that are in one to many relationship.Here is my code: models.py class Trainer(models.Model): name = models.CharField(max_length=30,null=True) surname = models.CharField(max_length=30,null=True) age = models.IntegerField(default=0) username = models.CharField(max_length=20) email = models.CharField(max_length=30) password = models.CharField(max_length=30) def __str__(self): return self.name + " "+self.surname class Student(models.Model): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) name = models.CharField(max_length=30,null=True) surname = models.CharField(max_length=30,null=True) age = models.IntegerField(default=0) username = models.CharField(max_length=20) email = models.CharField(max_length=30) password = models.CharField(max_length=30) def __str__(self): return self.name + " "+self.surname serializers.py from .models import Trainer, Student class TrainerSerializer(serializers.ModelSerializer): class Meta: model = Trainer fields = ("__all__") views.py from django.shortcuts import render from django.http import HttpResponse from .models import Trainer,Student from rest_framework import generics from .serializers import TrainerSerializer class TrainerList(generics.ListAPIView): queryset = Trainer.objects.all() serializer_class = TrainerSerializer class TrainerSingle(generics.RetrieveAPIView): queryset = Trainer.objects.all() serializer_class = TrainerSerializer class TrainerCreate(generics.CreateAPIView): queryset = Trainer.objects.all() serializer_class = TrainerSerializer What I want is when I get the Trainer objects,I also want to see the students of a trainer (like when we do trainerobj.query_set.all() ) Thanks in advance. -
Upload a file from an URL
I am trying to upload a file from an URL to Facebook server. It wants a PathLike object, but I can only get an URL due to the storage setup. I get an error that says: expected str, bytes or os.PathLike object So I tried this Django-specific solution, using the image field instead of the url: package = Package.objects.get(id=package_id) image_data = bytes(package.logo_image.image.read()) This gives an embedded null byte error. Here is the final failure point (in Facebook's API code), on the: def open_files(files): opened_files = {} for key, path in files.items(): opened_files.update({key: open(path, 'rb')}) # error is on this line yield opened_files for file in opened_files.values(): file.close() Second last code to run before failure: def __enter__(self): # do not keep args and kwds alive unnecessarily # they are only needed for recreation, which is not possible anymore del self.args, self.kwds, self.func try: return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") from None Third last: if self._fields: params['fields'] = ','.join(self._fields) with open_files(self._file_params) as files: response = self._api.call( method=self._method, path=(self._path), params=params, files=files, Any idea how to do this? -
Passing a parameter of foreign key while filtering objects in django
I am having a django website. I have the following models: class Category(models.Model): type=models.CharField(max_length=30) class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) This is my url for the products page: path("products/<str:type>/",views.category,name="category"), What I am wanting to do is that I want to display the products of the type passed in url.This is my views.py: def category(request,type): prods=Product.objects.filter(category.type=type) context = { 'categories':Category.objects.all(), 'prods' : prods, } return render(request,"category.html",context) but this is giving me error that I need to use == in filter. and if I just use prods=Product.objects.filter(category=type) then it asks for the category id from the category model rather than the type of category. What can be a fix to that such that if i pass leather in filter (in url as type) then only the products with category.type= leather show up in my template. -
Search field in Django is not redirecting to detail view
I am adding a search field in my blog so people can put the name of the blog they want to read and a list of items come up and after clicking on any of the list items, it will redirect to the detail view. However, in my case,If I put anything in search, it is not redirecting to a detail view but going to http://127.0.0.1:8000/home/search/2 instead of http://127.0.0.1:8000/home/list/2/. I have posted my models, views, URLs and template files below. Is there any reverse method I need to use here to redirect and what changes I need in my template file? models.py from django.db import models class Category(models.Model): cat_name = models.CharField(max_length = 256, blank = True) def __str__(self): return self.cat_name class Blog(models.Model): name = models.CharField(max_length = 256, blank = True) pub_date = models.DateTimeField('date published') text = models.TextField(blank = True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='categories', verbose_name = 'blog_categories') def __str__(self): return self.name views.py from django.shortcuts import render from homepage.models import Blog from django.views.generic import TemplateView, ListView, DetailView from homepage import models from django.db.models import Q class Home(TemplateView): template_name = 'homepage/index.html' class BlogListView(ListView): context_object_name = 'blogs' model = models.Blog template_name = 'homepage/blog_list.html' class BlogDetailView(DetailView): context_object_name = 'blogs_detail' model = models.Blog template_name = … -
Django AllAuth Social Login with Postman
I have only recently started working with DRF with ReactJS as my front-end and came across django allauth for social logins. Since all my UI is with React and the only way I know to integrate the two is with JSON-based API calls, I wonder if AllAuth's Social Login requests can be made via PostMan so I can replicate the same in ReactJS? -
Django - How to get current url from template and replace parameter value or delete parameter and append after
In my django template I need to get the current url and modify a parameter value or add this parameter if not present. here's an url example : /articles/pdf?perpage=2&page=2 All I know so far is how to retrieve the whole url : {{ request.get_full_path }} But what I need to do is to be able to create a new url that I will use as an href in which if "page" parameter present, I change its value, or if not present, I append this parameter to the url. -
Sock File Doesn't Appear To Be Loading - Nginx/Gunicorn
Running python3 ./manage.py runserver 0.0.0.0:8000 works. Running the below from /opt/envs/django_terraform works: gunicorn --bind 0.0.0.0:8000 django_forms.wsgi I've installed and configured Nginx to act as a proxy to Gunicorn. According to the guide (https://rahmonov.me/posts/run-a-django-app-with-nginx-and-gunicorn/), the below should work, but doesn't: gunicorn --daemon --workers 3 --bind unix:/opt/envs/django_terraform/django_terraform.sock django_forms.wsgi I've removed the 'daemon' flag as well and restarted the Nginx service to no avail. My /etc/nginx/sites-available/django_terraform file is as follows: server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /opt/envs/django_terraform; } location / { include proxy_params; proxy_pass http://unix:/opt/envs/django_terraform/django_terraform.sock; } } Nothing is generated in the Nginx access or error logs. Is there anything else I can check? -
error while working with routing and consumers
i've been going along with this tutorial https://www.youtube.com/watch?v=RVH05S1qab8, and after i've setted up my routing, my consumers and my ASGI_APPLICATION in settings.py, i've had this error. System check identified no issues (0 silenced). August 24, 2020 - 17:44:25 Django version 3.1, using settings 'building_access.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\edward\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\edward\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\dev_test\building_access\tag_venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\dev_test\building_access\tag_venv\lib\site-packages\channels\management\commands\runserver.py", line 101, in inner_run application=self.get_application(options), File "D:\dev_test\building_access\tag_venv\lib\site-packages\channels\management\commands\runserver.py", line 126, in get_application return StaticFilesWrapper(get_default_application()) File "D:\dev_test\building_access\tag_venv\lib\site-packages\channels\routing.py", line 29, in get_default_application module = importlib.import_module(path) File "C:\Users\edward\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 122, in import_module raise TypeError(msg.format(name)) TypeError: the 'package' argument is required to perform a relative import for '.routing' I tried googling it, and I didn't find any answer, also, here's my routing and consumers. routing: from django.conf.urls import url from channels.routing import ProtocolTypeRouter from channels.routing import URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from channels.security.websocket import OriginValidator from building_access.building_access.consumers import ChatConsumer application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^(?P<username>[\w.@+-]+)", ChatConsumer), ] … -
How to access JWT token claims from django request object?(simplejwt)
I want to put user permissions in JWT claims, and check them inside has_permission. Docs of SimpleJWT did not specify how to achieve this goal. How can i get token object from request? -
check that the dates are entered correctly in a form
I have a form to create events and I want to check that the dates are correct: end date greater than the start date or dates not before the actual date, etc... I was checking on the internet if there was any check with django for django.contrib.admin widgets but I can't find anything. In form.hmtl: <form method="post"> {% csrf_token %} <table class="form form-table"> {{ form }} <tr><td colspan="2"><button type="submit" class="btn btn-info right"> Submit </button></td></tr> </table> </form> In forms.py: class EventForm(ModelForm): class Meta: model = Event fields = ('classrom', 'title', 'description', 'start_time', 'end_time', 'calendar') def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_time'].widget = widgets.AdminTimeWidget() self.fields['end_time'].widget = widgets.AdminTimeWidget() In models.py: class Event(models.Model): classrom = models.CharField(max_length=200) title = models.CharField(max_length=200) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() calendar = models.ForeignKey(Calendar, on_delete = models.CASCADE) -
Cannot upload images in Django Models
Hello I have a project where I want user to upload a title and body text and a picture named question, however when I submit the form only the title and body are saved the picture not. I changed the form tag in my template but it didn't help. Thanks in advance. models.py class Question(models.Model): author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='question_author') question=models.ImageField(upload_to='question/',blank=True,name="question") created_on = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=20, unique=True) title = models.CharField(max_length=128) body = models.CharField(max_length=400) class Meta: ordering = ['-created_on'] def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class Answer(models.Model): author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='answer_author') question = models.ForeignKey('Question', on_delete=models.CASCADE, related_name='question_answer') answer=models.ImageField(upload_to='question/',blank=True) created_on = models.DateTimeField(auto_now_add=True) body = models.CharField(max_length=400) class Meta: ordering = ['-created_on'] def get_absolute_url(self): return reverse("comment_detail",kwargs={'pk':self.pk}) forms.py class QuestionForm(forms.ModelForm): class Meta: model=Question fields=['question','author','title','body'] class AnswerForm(forms.ModelForm): class Meta: model=Answer fields=['author','answer','body'] views.py class QuestionDetail(FormMixin, generic.DetailView): model = Question template_name = 'question_detail.html' context_object_name = 'question' form_class = AnswerForm def get_context_data(self, **kwargs): context = super(QuestionDetail, self).get_context_data(**kwargs) context ['anwsermodel_list'] = Answer.objects.filter(question=self.object).order_by('created_on') context['form'] = AnswerForm(initial={'question': self.object}) return context def post(self, request, *args, **kwargs): question.html {%if user.is_authenticated%} <form method="post" style="margin-top: 1.3em;"> {% csrf_token %} <label for="post">Başlık:</label> <br> <input type="text" name="title" size=50 maxlength="128"> <br><br> <label for="body">Soru:</label> <br> <textarea id="textarea" maxlength="400" name="body" rows="8" … -
How to filter in models.py
I have a question is this possible filtering in http://127.0.0.1:8000/admin/ ? models.py class Category(models.Model): name = models.CharField(max_length=10) class Tag(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) name = models.CharField(max_length=10) class Post(models.Model): title = models.CharField(max_length=10) category = models.ForeignKey(Category, on_delete=models.PROTECT) tag = models.ForeignKey(Tag, on_delete=models.PROTECT) category = [vegetable, meat] tag = [beef, onion, carrot] when I make new post in http://127.0.0.1:8000/admin/. Then if I crick [vegetable], is this possible filtering tag for only choose [onion, carrot] ? like tag = models.ForeignKey(Tag, filter=(tag__name=pk) on_delete=models.PROTECT) this. thank you for reading. -
How do I manage multiple submit buttons in Django?
I am currently working on a Django quiz app and I want to do manage the submit button for each option. <form method='POST'> {% csrf_token %} <div class='row'> <div class='col'> <button class="btn btn-primary btn-lg btn-block button" name='option1' onclick=''>{{ option1 }}</button> </div> <div class='col'> <button name='option2'class="btn btn-primary btn-lg btn-block button" onclick=''>{{ option2 }}</button> </div> </div> <div class='row'> <div class='col'> <button name='option3' class="btn btn-primary btn-lg btn-block button" onclick=''>{{ option3 }}</button> </div> <div class='col'> <button name='option4' class="btn btn-primary btn-lg btn-block button" onclick=''>{{ option4 }}</button> </div> </div> </form> -
Apache Server Error: ImportError: No module named site
I am trying to serve my django project over Apache using mod_wsgi. Apache will start but my project in inaccessible. When Apache launches I see ImportError: No module named site in the log. There is also a php site being served by Apache and that is accessable. On the RHEL7 server I have python 2.7.5 AND python 3.6.8 installed, Apache 2.4 and the mod_wsgi module. The project is running in a pipenv virtual environment on django 2.2 and using python 3.6.8. Here is my django.conf file... <VirtualHost *:8002> DocumentRoot /app/eam/gaic/new_support_tools/support_tools ServerName [ServerName] WSGIScriptAlias / /app/eam/gaic/new_support_tools/support_tools/wsgi.py <Directory /app/eam/gaic/new_support_tools/support_tools> Options +ExecCGI Order allow,deny Allow from all </Directory> </VirtualHost>```