Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django put some objects in last of queryset
I have a queryset of objects with fields - is_out_of_stock, sales. What I want is to order this qs according to either sales but the objects having is_out_of_stock = True should always be in last of queryset. How to do it in django ? I have tried these - queryset.order_by('is_out_of_stock','sales') but this sort list by is_out_of_stock, I want to sort list by sales but all the objects having is_out_of_stock should be in last. -
How to implement multiple step form submission in djangorestframework?
I am developing a registration system for the education center. It has multiple step form submission. I have no idea how to achieve the multi-step form submission using djangorestframework. Any ideas or simple examples are welcome. Thanks for your time and consideration. -
django runserver can't find static files, but remote server can
I'm writing in Pycharm, pushing to PythonAnywhere via GitHub. Django3 and Python3.7. Working through the Django Girls tutorial. I have defined in settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I have a template with {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static "blog/css/blog.css" %}"> <meta charset="UTF-8"> <title>DG Tutorial</title> </head> ... I have tried python manage.py findstatic blog.css it can't find it. I try variations of static/blog/css/blog.css and /blog/css/blog.css and get a long error message that ends with: django.core.exceptions.SuspiciousFileOperation: The joined path >>>(/blog.css) is located outside of the base path component (/Users/alesha/.virtualenvs/blog/lib/python3.7/site-packages/django/contrib/admin/static) So, I'm wondering why it's not looking in the STATIC_ROOT, which is located outside the base path component. Or did it? I don't know. I then checked the django bug-tracker. Nope - it's me. So, the wacky part is that when I port the code to PythonAnywhere, it works just as it should, blog.css gets served and happiness abounds. I have read a millihelen of posts on this, all the django tutorial pages on staticFiles - that I'm aware of, I've quad checked for typos. I am stumpeth - coz it works! Just not on localhost. Thank you for helping with my first … -
requestsession not working in Django to pass html form variable to another function
I am trying to use request.session to pass a html form variable into another function in Django, I am currenlty having trouble because the result from the session is resulting in None. Would appreciate help fixing it or another suggestion to pass the html form variable from to another function as a string. Here is my views.py file def home(request): input_email = request.POST.get('emailvalue') request.session["input_email"] = input_email return render(request, 'file1.html') def pre_que_ip(request): actual_email = request.session["input_email"] print(actual_email) urls.py path('admin/', admin.site.urls), path('', views.home, name = 'login'), path('home/', views.home, name = 'home'), path('add_ipaddress/', views.pre_que_ip, name = 'pre_que_ip') file1.html <form action="/add_ipaddress/" method="post"> {% csrf_token %} <input type="text" name="emailvalue" required><br><br> <input type="submit" value="Submit"><br><br> </form> -
How to add endpoint to create, update and delete model field separately?
I have a model with many-to-many field: class MyModel(models.Model): name = models.CharField(max_length=30, blank=False) info = models.CharField(max_length=100, blank=False) field = models.ManyToManyField(AnotherModel) And I want to list all fields, but add or delete field in separate endpoint. I have two serializers: class MyModelFullSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields = ['id', 'name', 'info', 'field'] class MyModelInfoSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields = ['id', 'name', 'info'] Although there is a ModelView: class MyModelViewSet(viewsets.ModelViewSet): queryset = models.MyModel.objects.all() serializer_class = serializers.MyModelInfoSerializer def list(self, request): serializer = serializers.MyModelFullSerializer( self.queryset, many=True ) return Response(serializer.data) Such as router: router = DefaultRouter() router.register(r'models', views.MyModelViewSet) urlpatterns = [ path('', include(router.urls)), ] So now there are following endpoints: GET /models/ POST /models/ GET /models/{id}/ ... DELETE /models/{id}/ These endpoints allows to list or change only name and info fields. Now I want to have more endpoints: GET /models/{id}/field/ POST /models/{id}/field/ ... DELETE /models/{id}/field/ -
Fixing filtering function after changing models
I recently changed my models a bit and I need to fix my filtering function, because it doesn't work now. Here's my old models.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ManyToManyField(Category, blank=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() image = models.ImageField() and my current one: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') that's my function that is supposed to filter items, that are inside a category: def SearchView(request, category_id=None): if category_id: category = Category.objects.get(pk=category_id) item_list = Item.objects.filter(category__id=category_id) else: item_list = Item.objects.all() title = request.GET.get('title') if title: item_list = item_list.filter(title__iexact=title) else: query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) context = { 'item_list': item_list, 'category': category, } return render(request, "search.html", context) So when I click on the category it shows me all items that are inside this category and I have got a content filter on the side. When I … -
Django QuerySet lookup returning multiple objects
I have a QS lookup which is returning multiple (duplicate) objects: queryset = queryset.filter( Q(receiver__exact=user_emp_type)) | queryset.filter(Q(sender__exact=self.request.user)) It returns the same amount of objects as the length of the reciever M2M field. e.g. if there are 3 receivers in the M2M receiver field there will be 3 duplicate objects. Why is this happening? -
Windows Docker Python Path
I was succesfully able to run my container (django python) on an older version of the docker engine. I did not change any code, yet now I see this error. $ docker run --net container_net --ip 172.18.0.2 sift_pro python: can't open file './manage.py runserver 0.0.0.0:8001': [Errno 2] No such file or directory Here is what my dockerfile looks like: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN pip install ... ... ... COPY . . CMD ["python", "./manage.py runserver 0.0.0.0:8001"] I have also tried other variations of this code with no success. FROM python:3.8 WORKDIR c:\\windows\\sift ENV PYTHONUNBUFFERED 1 COPY . . CMD ["python", "C:\\windows\\sift\\manage.py runserver 0.0.0.0:8001"] Does anyone see what I am doing wrong? Thanks. -
CSRF verification failed. Request aborted. (Python Request Module)
I have this function in my views.py (Django project) def boardsJson(request): user=request.GET.get('user') password=request.GET.get('password') : : Bla Bla Bla : : return HttpResponse("Login Success") I am tryingto login by this request module. import requests URL = "http://35.196.206.72:8000/boardsJson/" PARAMS = { 'user':'1234567890', 'password':'kak', } r = requests.get(url = URL, params = PARAMS) print(r.text) Every thing is well until I am using the GET method to login. But if I use the POST(I Just replaced the "GET" with "POST" every where) method then I am getting the message something like bellow. <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for âsame-originâ requests.</p> So please help me to solve it. Thank you. -
Dynamic Choices (Those that get updated for new values entered.)
In this project, I got three types of users: ChalkSlateAdmin (this is not a superuser, administrator or staff, etc.), Student and Teacher. All of these can be considered ChalkSlateUser as each have a OneToOne Relationship with the model. ChalkSlateAdmin can be considered an institute and any time someone registers as a ChalkSlateAdmin, there is a new institute as ChalkSlateAdmin has that attribute. Teachers and Students can join institutes (ChalkSlateAdmin attribute) that are already registered. So, I need to create a form that has choices of institutes that are currently registered. My question is, how can I define choices that change depending on what institutes (ChalkSlateAdmin attribute) are registered? Before this, I used constant string values for choices like male & female. models.py, from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class MyAccountManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Users must have an email address.") if not username: raise ValueError("Users must have a username.") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user=self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.user_type = 1 user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) class ChalkSlateUser(AbstractBaseUser): # required to include email = models.EmailField(verbose_name='email', unique=True, … -
Django CORS_ORIGIN_WHITELIST not working while CORS_ORIGIN_ALLOW_ALL does
I am trying to use django-cors-header for my api but the whitelist is not working. If I set CORS_ORIGIN_ALLOW_ALL=True it works, but my white list does not. CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8000', ] Any suggestions as to what I am doing wrong? -
How to authenticate a Django session using captcha?
I have built a website, and a captcha. The captcha is generated by models and displayed on a template. Views from resumesite.models import Chess_board import json def home(request): return render(request, 'home.html', {}) def chess(request): board = Chess_board() data = mark_safe(json.dumps(board.rep)) return render(request, 'captcha_original.html',{'board': data}) I would like to redirect all requests to the captcha, and on completion of the captcha redirect to website and allow full access for duration of the session (i.e. for period of 20 minutes). How would you suggest going about this? Options Middleware/decorator authenticating by ip address (I have read this won't work if user is using a proxy) Custom login form, with decorator @login_required(login_url="/chess/") Integrating with REST and using token authentication -
django search on site taggit
model class Bb(models.Model): image = models.ImageField(upload_to=get_timestamp_path, verbose_name='Pic') author = models.ForeignKey(AdvUser, on_delete=models.CASCADE, verbose_name='Author') created_at = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Date') tags = TaggableManager() def delete(self, *args, **kwargs): for ai in self.additionalimage_set.all(): ai.delete() super().delete(*args, **kwargs) class Meta: verbose_name_plural = 'Posts' verbose_name = 'Post' ordering = ['-created_at'] view def index(request): query = request.GET.get('q') if query: query = request.GET.get('q') #.split(" ") posts = Bb.objects.filter( #tags__name__in=query # this is an invalid request logic: tags__name__iexact=request.GET.get('q') ).distinct() else: posts = Bb.objects.all() paginator = Paginator(posts, 1) page_number = request.GET.get('page') posts = paginator.get_page(page_number) return render(request, 'main/home.html', {'query': query, 'posts': posts}) it is necessary to display all the posts in which there are certain some tags. I'm trying to implement a tag-based site search, like on pornhub or rule34. I expect to get the result analog: enter image description here django-taggit is a reusable Django application designed to make adding tagging to your project. -
django-filter Filter based on year of a database column
I have a column (dob) as date in the database. How do I filter on the year of it? class PersonFilter(django_filters.FilterSet): class Meta: model = Person fields = ['first_name','last_name','dob',] -
FileNotFoundError - [Errno 2] No such file or directory: '/static/background.jpg' - Django
I wrote the following code, in Python, Django framework: class ImageGenerator: def __init__(self, tip): self.tip = tip def remove_transparency(self, im, bg_colour=(250, 250, 250)): if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info): alpha = im.convert('RGBA').split()[-1] bg = Image.new("RGBA", im.size, bg_colour + (255,)) bg.paste(im, mask=alpha) return bg else: return im def generate(self): print('Triggered') border = 3 home_url = self.tip.fixture.home.image_url away_url = self.tip.fixture.away.image_url home_name = self.tip.fixture.home.name away_name = self.tip.fixture.away.name response = requests.get(home_url) home = self.remove_transparency(Image.open(BytesIO(response.content))) home_w, home_h = home.size response = requests.get(away_url) away = self.remove_transparency(Image.open(BytesIO(response.content))) away_w, away_h = away.size background_image = Image.open('/static/background.jpg', 'r') When I execute this code I get the following error: FileNotFoundError at /fixtures/view/54848 [Errno 2] No such file or directory: '/static/background.jpg' Request Method: POST Request URL: http://127.0.0.1:8000/fixtures/view/54848 Django Version: 3.0.3 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/static/background.jpg' Exception Location: /home/sander/.local/lib/python3.6/site-packages/PIL/Image.py in open, line 2809 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/sander/git/football', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/sander/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Fri, 28 Feb 2020 18:56:54 +0000 I defiend the following variable in the django settings file: STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') I tried using the static function from from django.templatetags.static import static. … -
Django - aggregate fields value from joined model
my goal here seems to be simple: display the Sum (aggregation) of a foreign model particular field. The difficulty consist in the current set-up, kindly take a look and let me know if this need to be changed or I can achieve the goal with current model: class Route(models.Model): name = models.CharField(max_length=50) route_length = models.IntegerField() class Race(models.Model): race_cod = models.CharField(max_length=6, unique=True) route_id = models.ForeignKey(Route, on_delete=models.CASCADE, related_name='b_route') class Results(models.Model): race_id = models.ForeignKey(Race, on_delete=models.CASCADE, related_name='r_race') runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE, related_name='r_runner') Now, I am trying to have like a year summary: Runner X have raced in 12 races with a total distance of 134 km. While I was able to count the number of races like this (views.py) runner = Runner.objects.get(pk=pk) number_races = Results.objects.filter(runner_id=runner).count() For computing the distance I have tried: distance = Results.objects.filter(runner_id=runner).annotate(total_km=Sum(race_id.route_id.route_length)) This code error out stating that on views.py - distance line Exception Type: NameError Exception Value: name 'race_id' is not defined I am sure I did not u/stood exactly how this works. Anybody kind enough to clarify this issue? Thank you -
pass variable from one view to another (I don't think I need requests.sessions as I don't need global access to this value)
I'm building a job-board type of website. After searching a zip code on the index page, the user is taken to the search_results page. On this page is a list of jobs in the area and a form for users to subscribe by email to be alerted about new posts. Here is the view: def search_results(request): query =request.GET.get('query') # zip code jobs = [] # logic for querying Job objects and filling 'jobs' list omitted form = JobSeekerEmailForm() # pass email subscription form to template return render(request, 'job/search_results.html', {'query':query, 'jobs': jobs, 'form':form}) In the search_results.html template, if the user submits the JobSeekerEmail() they are redirected to the email_subscription view: <form action="{% url 'email_subscription' %}" method="POST"> <input type = 'text' placeholder="Email"/> <button type="submit" name="button">Submit</button> </div> {% csrf_token %} </form> In this view I just save the email and attempt to redirect back to search_results, so the user can continue browsing jobs in the zip code they searched for: def job_seeker_email(request): if request.method == 'POST': form = JobSeekerEmailForm(request.POST) if form.is_valid(): form.save() return redirect('search_results') # search results will throw an error because there is no longer a 'query' value but this will fail. Is there a way to pass the original query value … -
Adding django project root directory to installed apps
I tried to add a project-wide management command the way it was described in documentation. However django didn't register the command as the project root (directory containing settings.py) wasn't in INSTALLED_APPS, so I added it and it worked. Is it safe to do this? -
How to customize admin model save to insert values into multi tables in Djagngo Admin
I'm a beginner to Django . I have to Models : class AvailableReservation(models.Model): startDate = models.DateField() endDate = models.DateField() isActive = models.BooleanField(default=False) count = models.IntegerField(blank=False, null=False) class ReservationDetails(models.Model): reservationDate = models.DateField(); reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE)``` count = models.IntegerField(blank=False, null=False) The first class is registered in admin.py admin.site.register(AvailableReservation, AvailableReservationAdmin) and this is my admin interface for adding AvailableReservation Add AvailbleReservations Screen Now, after clicking the save button, inputs should be stored into AvailableReservation and ReservationDetails. But with some calculations. First, the user inputs go to the AvailableReservation. Second, I want to calculate the how many days between the startDate and the endDate. Then insert records(equal to the number of days between the startDate and the endDate) into the ReservationDetails -
Django-filters: Filtering on upper case values BooleanFilter
I want to filter on a field (say first_name). The user should be able to either input upper or lower case. Is this the right approach ? Instead, should I do icontains using this: https://django-filter.readthedocs.io/en/master/guide/usage.html#overriding-default-filters Thanks ! class PersonFilter(django_filters.FilterSet): first_name_upper = django_filters.BooleanFilter(field_name='first_name',method='filter_upper') class Meta: model = Person fields = ['first_name_upper',] -
How to turn a Django QueryDict into a list of Django ORM OR filters?
I would like to turn this: http://127.0.0.1:8000/fields_data/?field_name__exact=053&field_name__exact=064 into this: fields = Fields.objects.filter(Q(field_name__exact='053')| Q(field_name__exact=field'064)) There could be additional numbers of field_name__exacts, it's not known until runtime. In views.py, I can turn the URL into a QueryDict easily because request.GET is already a QueryDict object. According to the docs, QueryDict was designed in part so that the same key name could be used with multiple values, a common pattern in urls. I then try to turn the QueryDict into something compatible with **kwargs by using: fields = serialize('geojson', Fields.objects.filter(**request.GET.dict())), but request.GET.dict() looks like this: {'field_name__exact': ['053', '064']}. As a result, I only ever get back the second object. I'm starting to suspect I may need to write something more sophisticated involving comprehensions, but I feel like I'm really close. Can someone help me with the correct syntax to turn the QueryDict (multi-valued keys) into an OR'd set of Q()'s? -
Redirect to same view but remember the previous query value
I'm building a job-board type of website. After searching a zip code on the index page, the user is taken to the search_results page. On this page is a list of jobs in the area and a form for users to subscribe by email to be alerted about new posts. After subscribing by email, I want to redirect them to the same view but I no longer have access to their original zip code query. I use the following view: def search_results(request): # query db for Job objects to display (this code not important) query =request.GET.get('query') zcdb = ZipCodeDatabase() zipcode = zcdb[query] zip_codes_in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(query, 15)] jobs = [] for zip in zip_codes_in_radius: jobs_in_zip = Job.objects.filter(business__zip_code = zip) if jobs_in_zip: jobs += jobs_in_zip # Email subscription form if request.method == 'POST': form = JobSeekerEmailForm(request.POST) if form.is_valid(): form.save() return redirect('search_results') # will no longer have access to 'query' and thus cannot grab Job objects from db else: form = JobSeekerEmailForm() return render(request, 'job/search_results.html', {'query':query, 'jobs': jobs, 'form':form}) Upon subscribing to email alerts, I want to redirect the user to this same search_results view so they can continue browsing. If a user does submit the JobSeekerEmailForm(), they are … -
Accessing other user profile Django
Hi I was wondering how can I build a view that can shows the details of another user, for example their name, email address, and etc. Using Django views? Without compromising the user that is being viewed? For example user A can view user B profile when it requests mysite.com/B. Thanks in advance. -
DRF, queryset by a models choices field
I have the following Django rest framework model: from django.db import models from django.utils import timezone from Project_Level.CONSTANTS import AREAS class KnownLocation(models.Model): name = models.CharField(name="Name", unique=False, max_length=150, blank=False, help_text="Enter the name of the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=1) AREAS = [ ('210', '210'), ('769', '769'), ('300', '300') ] serializer: from rest_framework.serializers import Serializer from .models import KnownLocation class KnownLocationSerializer(Serializer): class Meta: model = KnownLocation fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude') I want to write a view with a query set ( maybe a get_queryset method will be better), where the query return all objects which has the same 'area' has the one past in by the user. -
Django model is truncating a decimal place when passed to the view when DecimalField is set
Django Model: class TwoDecimal(models.Model): two_decimal = models.DecimalField(decimal_places=2, max_digits=10) View: def two_decimal(request): test = TwoDecimal( two_decimal = 30.00 ) test.save() return render( request, "test-template.html", {"test": test} ) Template: {{ test.two_decimal }} #==> Displays as 30.0 instead of 30.00 (Despite it being a two decimal field.) This displays properly if it is a query from already saved data. Why is django truncating this decimal place?