Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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>``` -
Django: Could not parse the remainder: '{{ ' from '{{ ' Template variable inside a variable
I'm trying to put call a variable using another variable in django. More specifically line 12. How would this be done as obviously an error has occurred when I tried to do this. <h2>Stage {{ forloop.counter }} - {{ career_stage.title }}</h2> <p>{{ career_stage.description }}</p> <hr> <form method="post"> {% with stage="stage{{ forloop.counter }}" %} {% csrf_token %} {% for written_question in career_stage.text_questions.all %} <h3>Question - {{ forloop.counter }}</h3> <p>{{ written_question.text }}</p> <p>Your Answer</p> {{ stage_forms.{{ stage }}.question{{ forloop.counter }} }} <hr> {% endfor %} </form> Stage_forms is a son object, containing multiple forms. The {{ stage }} part gets the variable required for the tab that is currently active. question{{ forloop.counter }} Will get the current question for the for loop. Error Could not parse the remainder: '{{ stage' from 'stage_forms.{{ stage' -
Is there any way to use any user-defined Python method in the Case-When query of Django ORM?
I have defined a class along with its necessary methods, which is as following. class Location(models.Model): latitude = models.DecimalField(max_digits=20, decimal_places=8, default=Decimal("0.00"), null=True) longitude = models.DecimalField(max_digits=20, decimal_places=8, default=Decimal("0.00"), null=True) @staticmethod def prepare_location_hotlink(latitude=None, longitude=None): returm mark_safe(s="<a class='inline-link' href='https://maps.google.com/maps?z=17&q={lat},{lng}' target='_blank'>{lat}, {lng}</a>".format(lat=latitude, lng=longitude)) @classmethod def retrieve_location_data(cls): annotated_case_query = { "location": Case( When(Q(location__isnull=False, longitude__isnull=False), then=cls.prepare_location_hotlink(latitude=F("latitude"), longitude=F("longitude")) ), default=Value("Not Available"), output_field=CharField() ) } return [loc for loc in cls.objects.annotate(**annotated_case_query).values_list("location", flat=True)] Here, in the retrieve_location_data method, I have tried to use a user-defined (prepare_location_hotlink) Python method in Case query to retrieve all of the location data as hotlinked. It seems not working in the above way. But I need to use the user-defined python method in the Case query anyway, as it retrieves and prepares data much faster. I already researched and read the Django documentation, but unfortunately, I could not find any solution for this case. Is there any proper and accurate way on how to use any user-defined Python method in the Case query of Django ORM? -
how to i get models id from onclick
Hi i am new to django and trying to build a zomato like site.i want to poplulate a restaurants menu on click on the restaurant button.i have Business model where all restaurants data is saved and menu model where menu of a restaurants is saved with restaurant name as a foreign key , i have populated the restaurants to the home.html, how do i populate menu of specific restaurants into store.html after click on a specific restaurant hope i'm asking the right question here is my code models.py class Business(models.Model): bname=models.CharField(max_length=200,null=False) specialities=models.CharField(max_length=200,null=True) location=models.CharField(max_length=200,null=False) # image=models.ImageField(null=True,blank=True) def __str__(self): return self.bname @property def imageURL(self): try: url=self.image.url except: url= '' return url class Menu(models.Model): business=models.ForeignKey(Business,on_delete=models.CASCADE,blank=True,null=False) dish_name=models.CharField(max_length=200,null=False) price=models.IntegerField(null=False) def __str__(self): return self.dish_name views.py def home(request): businesses= Business.objects.all() context={'businesses':businesses} return render(request,"foodapp/home.html",context) def store(request): menus=Menu.objects.get.all() context={'menus':menus} return render(request,"foodapp/store.html",context) home.html {% for business in businesses %} <div class="col-md-4"> <div class="box-element product"> <img class="thumbnail" src="{% static 'images/assets/placeholder.png' %}" alt=""> <hr> <h6><strong>{{business.bname}}</strong></h6> <hr> <h6>{{business.specialities}}</h6> <h6>{{business.location}} &nbsp;&nbsp; <button data-product={{business.id}} data-action="add" class="btn btn-outline-secondary add- btn update-cart"> <a href="{% url 'store' %}"> View</a></button> </h6> {% endfor %} store.html {% block content %} <div class="row"> <div class="container"> {% for menus in menu %} <div style="margin-top: 20px;" class="col-md-4"> <div class="box-element product"> <img class="thumbnail" src="{% … -
Getting pytest.mark.django_db error when trying to use parametrize
I am trying to run the following tests: # @pytest.mark.django_db def create_single_shift_record() -> Response: data = createShiftData() return client.post(reverse(revLink.shifts_single), data, format='json') @pytest.mark.django_db @pytest.mark.parametrize( 'dbName, createApi', [ (Shifts, create_single_shift_record()), # Other tests from other DB's here ] ) def test_create_single_record(dbName, createApi): res = createApi assert res.status_code == status.HTTP_201_CREATED assert dbName.objects.count() == 1 And get the error: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Even when I add @pytest.mark.django_db above the first function (shown as commented out) I still get the error Any idea if I would be able to get this to work, or another way of doing it? -
Django REST + React + Social Auth (Twitter)
I am working on an academic project. The project must have DRF as back end and react as front end. What I try to achieve here is have a react SPA containing a "Login with Twitter" button. User gets to authorize app with twitter then he lands on a home page with a message like "Hello user: ". And then I have to build it further but for now I am stuck here. I followed this tutorial and managed to create the back end API. There is a second part but no matter how hard I tried I couldn't make it work with twitter. Any help will be greatly apreciated -
What are the best ways to make your website faster such that it loads up faster and consumes less data in django
Currently I am working on a django website. I had two queries about speeding up my website. I have a products page in which I display products. Currently when I tested it with 15 pics each sizing around 8-10mb the page took too much time to load. What should be the appropriate size of the image such that it follows the above conditions and also the image quality does not get very bad. 2)I am having a page where all the products are displayed of all categories and its view look like below qs = Product.objects.select_related('category').order_by(*sorting) types = [ (k, list(vs)) for k, vs in groupby(qs, attrgetter('category')) ] I wanted to know will having different pages for different categories will help to load the site faster by filtering the products such as p=Product.objects.filter() . Or filtering would take the same time as to show all products in one single page? -
Why jquery.each(function() {} ) does not iterate through the loop at the first time?
I defined a dropbox selector which after selecting a country gives me a list of cities as checkboxs. I am using jquery and ajax to preview it and select it as follow. This is the mytemplate.html(which almost does what I expect): <div> <div id="preview-items"> </div> </div> <script> $("#id_country").change(function () { var countryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: '/ajax/ajax_load_cities', data: { 'countries': countryId // add the country id to the GET parameters }, dataType: 'json', success: function (data) { // `data` is the return of the `load_cities` view function $('#preview-items').html(''); for (var i in data.tags) { $('#preview-items').append(` <label class="btn btn-primary mr-1"> <input type="checkbox" id="checklist" value="` + data.tags[i][0] + `"> <span> ` + data.tags[i][1] + ` </span> </label><br />` ).find(':checkbox').change(function(e) { var cities_array = $(":checkbox:checked").map( function() { return $(this).next().html(); }).get(); $("#preview-items").html(cities_array.join(', ')); } } }); }); </script> and in django view.py: def load_cities(request): .... data = { 'tags': list(cities) } return JsonResponse(data) The problem is that, it does not keep the selected cities after changing the country selectors. after googling, I found that cookies are a good choice. I added the following code right after $("#id_country").change(function () { … -
ValueError at /category/leather/all/ Field 'id' expected a number but got 'leather'
This is my views.py. def category(request,type): prods=Product.objects.filter(category=type) context = { 'categories':Category.objects.all(), 'prods' : prods, } return render(request,"category.html",context) This is my models.py for reference class Category(models.Model): type=models.CharField(max_length=30) class Product(models.Model): category = models.ForeignKey(Category, on_delete = models.CASCADE) What is happening is that when I pass leather(or any other category) as type parameter in url it gives me the error.What I am wanting to do is that if I pass leather then the products should filter by leather category which I am not able to make happen. If I pass an id corresponding to the category then it works fine. I wanted to know a way so that the type can be read properly and then filter accordingly. -
Why does my python POST request return the following error: Invalid URL: No host supplied?
The question may seem a little silly, so I'll dig deeper. I have two EC2 instances of AWS running, one of them is Django and the other is Express, both with SSL certificate. I require Django to make a POST request to send a file to Express (following the instructions of: https://requests.readthedocs.io/en/master/user/quickstart/#post-a-multipart-encoded-file) now this whole process works well in my local environment, but it is not working in production, I already tried several options: Configured nginx to set host with proxy_set_header passed headers in the post request (https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers) I wonder if there is something in the ec2 instances that i am ignoring -
How to pass a set of objects in between two views?
I'm building a quiz app in which I'm storing questions in the database by creating a model class. I am retrieving a random question set for each user from the database and then rendering them on an HTML page. The problem is after logging a user in, a random set of questions appears but that random set is lost after refreshing the page. How do I solve this One thing that I thought was retrieving the object set in another view....say after logging a user in and passing it as a dictionary to another view. But I can't find the syntax or any function (if it exists). Please help. I'm using django 3.1 and MySQL as my database. My views.py looks like this: from django.shortcuts import render, redirect from .models import * from .forms import UserForm from django.contrib.auth.forms import AuthenticationForm import random from django.contrib.auth import login, logout, authenticate # Create your views here. def home(request): return render(request, 'testapp/home.html') def loginuser(request): #form = UserForm() if request.method == 'GET': form = AuthenticationForm() return render(request, 'testapp/login.html', {'form':form}) else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request, 'testapp/login.html', {'form':AuthenticationForm(), 'error':'Username or password incorrect'}) else: login(request, user) return redirect('paper') def paper(request): #objects …