Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
matching query does not exist. Django Error
this is my code for my project, I just get this error I tried to figure it out but I don't get it, Django Error: DoesNotExist at /save_post/ Profile matching query does not exist. views.py, line 75, in save_post form.authore = Profile.objects.get(user=request.user) views.py @login_required def save_post(request): if request.method == "POST": form = Post(content=request.POST['content']) form.authore = Profile.objects.get(user=request.user) form.save() elif request.method == "PUT": data = json.loads(request.body) post_id = int(data["post_id"]) new_content = data["new_content"] post = Post.objects.filter(id=post_id).first() if post.authore.user != request.user: return HttpResponse(status=401) post.content = new_content post.save() return JsonResponse({ "result": True }, status=200) else: return JsonResponse({ "error": "post not found" }, status=400) return index(request) models.py class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Post(models.Model): content = models.TextField() timestamp = models.DateTimeField(default=timezone.now) authore = models.ForeignKey(Profile, on_delete=models.CASCADE) likes = models.PositiveIntegerField(default=0, blank=True, null=True) def serialize(self): return { "id": self.id, "content": self.content, "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"), "authore": self.authore.id, "username": self.authore.user.username, "likes": self.likes.count(), } -
Django DatabaseError Invalid connector for timedelta
Previously, I did implement the ExpressionWrapper to create a custom filter, It's working fine in the postgresql, but when I did run test with sqlite3, then the error said django.db.utils.DatabaseError: Invalid connector for timedelta: *.. class AccessDurationQuerySet(models.QuerySet): def filter_expiration(self, is_expired: bool = False): """ To filter whether AccessDuration already expired or yet. don't use the same `expiration_date` as expression key, because it will clash with `AccessDuration.expiration_date` property. Issue: https://stackoverflow.com/q/69012110/6396981 """ kwargs = {'_expiration_date__gte': Now()} if is_expired: del kwargs['_expiration_date__gte'] kwargs['_expiration_date__lt'] = Now() return self.all().annotate( _expiration_date=models.ExpressionWrapper( models.F('lab_start_date') + (timezone.timedelta(days=1) * models.F('duration')), output_field=models.DateTimeField() ) ).filter(**kwargs) class AccessDurationManager( models.Manager.from_queryset(AccessDurationQuerySet), DefaultManager ): def published(self): return super().published().filter( status=AccessDurationStatusChoices.active ) class AccessDuration(TimeStampedModel): course = models.CharField(max_length=100) duration = models.FloatField(default=settings.DEFAULT_DURATION, help_text=_('In days')) container_duration = models.CharField(max_length=100, default=_('Up 2 hours'), help_text=_('How long a container has to be running, ' 'value based on Docker API Status')) user = models.ForeignKey(User, on_delete=models.CASCADE) lab_start_date = models.DateTimeField(verbose_name=('Start Date'), null=True) status = models.CharField(max_length=20, choices=AccessDurationStatusChoices.choices, default=AccessDurationStatusChoices.inactive) objects = AccessDurationManager() ... Anyway, I'm using docker for my project: docker-compose -f local.yml run django pytest myproject/tests/flows/2_test_invite_student.py::test_invite_student_by_superuser Then the error said: self = <django.db.backends.sqlite3.operations.DatabaseOperations object at 0x7f203c6313a0>, connector = '*', sub_expressions = ['86400000000', '"webssh_accessduration"."duration"'] def combine_duration_expression(self, connector, sub_expressions): if connector not in ['+', '-']: > raise DatabaseError('Invalid connector for timedelta: %s.' … -
How to retrieve user data from djoser endpoint (.../users/me)
How do I retrieve users info from using djoser url /users/me/? I tried to follow the example in this documentation but nothing works out, I keep getting 403 forbidden. I used Bearer, JWT, and Token in the authorization header but none of them worked. https://djoser.readthedocs.io/en/latest/base_endpoints.html -
extending the abstractuser model for two different user types (customer,vendor)
models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): is_customer = models.BooleanField('customer status', default=False) is_vendor = models.BooleanField('vendor status', default=False) class Customer(models.Model): customeruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) username = None email = models.EmailField(_('email address'), unique=True) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) mobileno = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Vendor(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) username = None email = models.EmailField(_('email address'), unique=True) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) mobileno = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] … -
How to create regular text in Sphinx and DocString
I added Sphinx auto-documenting to my vanilla Django project. The vanilla Django project has a DocString that I want to keep: """URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ However, Sphinx is trying to process it and gives me these errors: /usr/src/app/porter/urls.py:docstring of porter.urls:5: WARNING: Definition list ends without a blank line; unexpected unindent. /usr/src/app/porter/urls.py:docstring of porter.urls:7: WARNING: Unexpected indentation. /usr/src/app/porter/urls.py:docstring of porter.urls:9: WARNING: Block quote ends without a blank line; unexpected unindent. How can I tell Sphinx to just render the text as-is (just a very long description) and don't process it? -
Has django-coverage a bug in calculation coverage?
I am measuring my test coverage using coverage tool of django. I use coverage html command to see coverage but the result is strange. For example a part of the result is: click to see The question is: How the lines 102 & 104 are not runned? is it possible or it's a bug? Django == 3.2.8 djangorestframework == 3.12.4 coverage == 5.5 -
how to make custom serializer which can handle nested post data for Create API endpoint?
Due to unique business needs, I have to customize the Create API endpoint. Default behavior in django-rest-framework is like this. class Customer(models.Model): fieldA = models.IntegerField(null=True, blank=True) fieldB = models.CharField(max_length=5, blank=True) ... ... class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' class CustomerListCreateAPIView(generics.ListCreateAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer post data { fieldA: 1, fieldB: 'some string' } it sends respond with Created status { id: 1, fieldA: 1, fieldB: 'some string' } However, I want to post data with nested data like this { "customer": { "fieldA": 1, "fieldB": "some string" } } and expected response should be { "customer": { "id": 1, "fieldA": 1, "fieldB": "some string" } } How can I archieve this? -
Django auto increasing PositiveIntegerField per model
In the below django model is it possible to make the position field auto increment per ForeignKey to the ChatGroup model class Channel(Model): chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE) name = models.CharField(max_length=50) description = models.TextField(max_length=255, null=True, blank=True) position = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( fields=("chat_group", "position") ) ] Thanks! -
Use all the values in a model to create a chart in Django
I'd like to create a chart with all the information stored in my databse. Specifically I'd like to have in my X axis all the days of the weeks and in the Y axis all the number stored in my database. I've menaged to create sucessufully the labels for the week but when I try to render the data value nothing is showed. Also, if I tried to use data = list(Month.objects.values_list())[2:] to remove the file field and id field my list just return empty. What am I doing wrong? Thank you all MODEL class Week(models.Model): file = models.OneToOneField(File, on_delete=models.CASCADE) monday = models.PositiveIntegerField(null=True) tuesday = models.PositiveIntegerField(null=True) wednesday = models.PositiveIntegerField(null=True) thursday = models.PositiveIntegerField(null=True) friday = models.PositiveIntegerField(null=True) saturday = models.PositiveIntegerField(null=True) sunday = models.PositiveIntegerField(null=True) VIEW def week_data(request, pk): labels = [f.name for f in Week._meta.get_fields()] data = list(Week.objects.values_list()) context = { 'labels': labels, 'data': data } return render(request, 'data.html', context) HTML <!DOCTYPE html> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="doughnut-chart" width="800" height="450"></canvas> new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels: [{% for label in labels %} '{{ label|capfirst }}', {% endfor %}], datasets: [ { label: "Population (millions)", backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", ,"#c45850", ,"#c45850"], data: [{% for value in data %} {{ value }} {% endfor %}] … -
Django create parent model and child model in one form
I am learning Python and Django, and I am trying to create a recipe with a form. The problem is I have two models, Recipe and RecipeIngredient and I don't know how to add recipe ingredients to the form since it requires the primary key of the recipe and from what I understand, the key is not created until after the form is saved? So how can I create a recipe with both the Recipe and RecipeIngredient when Recipe is not yet initialized? Models.py: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # Lasanga description = models.TextField(blank=True, null=True) notes = models.TextField(blank=True, null=True) cookTime = models.CharField(max_length=50, blank=True, null=True) timeStamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) @property def title(self): return self.name def get_absolute_url(self): return reverse("recipes:detail", kwargs={"id": self.id}) # recipes is from url.py app_name def get_hx_url(self): return reverse("recipes:hx-detail", kwargs={"id": self.id}) # recipes is from url.py app_name def get_edit_url(self): return reverse("recipes:update", kwargs={"id": self.id}) def get_image_upload_url(self): return reverse("recipes:recipe-ingredient-image-upload", kwargs={"parent_id": self.id}) def get_delete_url(self): return reverse("recipes:delete", kwargs={"id": self.id}) def get_ingredients_children(self): return self.recipeingredient_set.all() def get_instruction_children(self): return self.recipeinstruction_set.all() class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) quantity = models.CharField(max_length=50, blank=True, null=True) unit … -
django rest framework field validation return value
Where does the return value go for validated fields for serializers with Django rest framework? I looked at the source code, and I thought it was passed to 'attrs' for the main validation method so that I could do manipulation of the field in field_validation for more DRY code. The code below does not work, as the returned value is not passed to attrs, but where does it go? Does it go anywhere? From Sourcecode, it really looks like it does. from anapp.models import CustomObject, CustomUser from anapp.utils import token_hander from rest_framework import serializers class CustomObjectSerializer(serializers.Serializer): uid = serializers.CharField(required=True) token = serializers.CharField(required=True) def validate_uid(self, value) -> CustomObject: uid:str = force_text(urlsafe_base64_decode(value)) myobject: CustomObject = CustomObject.objects.get(id=int(uid)) return myobject def validate(self, attrs:OrderedDict) -> OrderedDict: myobject: CustomObject = attrs.get('uid') user: CustomUser = CustomObject.user if not token_hander.check_token(user, attrs.get('token')): raise serializers.ValidationError({'token': f'invalid token'}) return attrs -
How to see the comments inside Posts in the admin page
Posts class class Posts(models.Model): caption = models.CharField(max_length=2200) date_posted = models.DateTimeField(default=timezone.now()) user = ForeignKey(User, on_delete=models.CASCADE ,related_name='UserPosts') def __str__(self): return f"Post {self.id} ({self.user.username})'s" Comment class has inside the post related_name='comments' class Comment(models.Model): text = models.CharField(max_length= 2200) post = models.ForeignKey(Posts, on_delete=models.CASCADE , related_name='comments' ) user = models.ForeignKey(User, on_delete=models.CASCADE) I want to know how can I see Posts comments inside the admin page when going in Posts -
How to add a many-to-many relationship after save in django?
I'm trying to build a simple ToDo app in django: A 'box' contains multiple 'tasks', has an 'owner' (the person who created the box and has administrative privileges) and multiple 'users' (persons who can access the box and add/edit tasks). I want to automatically add the owner to the users set. I've tried this multiple ways: Overwriting the save(): class Box(models.Model): owner = models.ForeignKey(User, related_name='boxes_owned', on_delete=models.CASCADE, null=True, blank=False) users = models.ManyToManyField(User, related_name='boxes_assigned') title = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) def save(self): super().save() self.users.add(self.owner) This does not work and neither does working with a post-save signal. @receiver(post_save, sender=Box) def update_box(sender, instance, **kwargs): instance.users.add(instance.owner) The owner won't be added to the users set. What am I doing wrong, how can I fix this? Is this the right approach at all? -
Django: order_by column from another table
I am building a forum and have the next model for messages: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=100000) date_publication = models.DateTimeField(auto_now_add=True) class Discussion(Message): title = models.CharField(max_length=500) views = models.PositiveBigIntegerField(default=0) class Response(Message): topic = models.ForeignKey(Discussion, on_delete=models.CASCADE) reply_to = models.ForeignKey( Message, on_delete=models.CASCADE, related_name='message_replied', null=True) I wonder how can I get a list of Discussions order_by date_publication from Response. -
Trouble with urls mapping to view functions in Django
I want to group all of my URLs within my todo list app into the project/todolist/urls.py file. So I have a button and a String field where you can add the item to the list, and when you push the button it should send the string to the data model and redirect back to the homepage with the updated list. This works when I have all of the urls placed in the project/urls.py file like below: urlpatterns = [ url(r'^admin/', admin.site.urls), url('todo_list/', include('todolist.urls')), url('addItem/', addItem), url('deleteItem/(?P<i>[0-9]+)', deleteItem) ] But I wanted to use the include() function instead and group all of the add, delete and todo_list views into a single file in project/todolist/urls.py. But when I do this I get Page not found errors and such: Using the URLconf defined in test_django.urls, Django tried these URL patterns, in this order: ^admin/ todo_list/ The current path, addItem/, didn’t match any of these. Below is the code that is throwing the error. I have tried to change things in the html template so that the form action goes to /todo_list/addItem/ instead of /addItem/, but this for some reason doesn't solve the problem. *** project/todolist/urls.py *** from django.urls import path from . import … -
Ubuntu : FATAL : can't find command '/home/ubuntu/env/bin/gunicorn'
I am trying to set up my gunicorn config file for my Ubuntu server , however I keep running into a guni:gunicorn FATAL can't find command '/home/ubuntu/env/bin/gunicorn' error when trying sudo supervisorctl status Here is the config files code: [program:gunicorn] directory=/home/ubuntu/spookie command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/spookie/app.sock spookie.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn I have tried whereis gunicorn and it does return the /env/bin/gunicorn file I have tried ls /home/ubuntu/env/bin/gunicorn and that gives an error stating that the directory doesn't exist -
Django Import Export, Filter ForeignKey objects connected to users
I'm building an import excel files system for every leads whit import export library. In the Website each user must be able to import his leads and make sure that they are viewed only by him. In all other cases I filtered the "organisation" field linked to a UserProfile model through the views.py. But now I don't know how to filter the field organisation for a specific user.At the moment I can import the excel files from the template but leaving the organisation field blank. Help me please I'm desperate Models.py class Lead(models.Model): nome = models.CharField(max_length=20) cognome = models.CharField(max_length=20) luogo=models.CharField(max_length=50, blank=True, null=True, choices=region_list) città=models.CharField(max_length=20) email = models.EmailField() phone_number = models.CharField(max_length=20) description = models.TextField() agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="leads", null=True, blank=True, on_delete=models.SET_NULL) chance=models.ForeignKey("Chance",related_name="chance", null=True, blank=True, on_delete=models.CASCADE) profile_picture = models.ImageField(null=True, blank=True, upload_to="profile_pictures/") converted_date = models.DateTimeField(null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE,null=True, blank=True) objects = LeadManager() age = models.IntegerField(default=0) def __str__(self): return f"{self.nome} {self.cognome}" class User(AbstractUser): is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username Views.py def simple_upload(request): if request.method == 'POST': Lead_resource = LeadResource() dataset = Dataset() newdoc = request.FILES['myfile'] imported_data = dataset.load(newdoc.read(),format='xlsx') #print(imported_data) for data in imported_data: … -
How to return an array inside of a function?
I created a class in my Django project and I call it from views. I need a result of a function in this class but I cannot return the array. I tried to equalize a array from outside but it returns: <module 're' from 'C:\\Users\\edeni\\AppData\\Local\\Programs\\Python\\Python39\\lib\\re.py'> How can I use this array in my views? views.py def setup_wizard(request): ... functions.myClass(setup.n_username, setup.n_password, setup.n_url, setup.n_port, setup.db_password, username=request.user.username) **functions.py** class myClass(): def __init__(self, n_user, n_password, n_url, n_port, db_password, username): ... self.elastice_yolla(username) ... def elastice_yolla(self, username): self.report_final = [] array_length = len(glob.glob(self.location + "\*\*.nessus")) self.static_fields = dict() for in_file in glob.glob(self.location + "\*\*.nessus"): try: i = 0 with open(in_file) as f: if os.path.getsize(in_file) > 0: np = NES2(in_file, self.index_name, self.static_fields, username) report_final = np.toES() time.sleep(0.02) i = i + 1 except: pass print("report") print(report_final) class NES2: def __init__(self, input_file, index_name, static_fields, username): .... def toES(self): ... for ... for ... try: if bas['cve']: self.es.index(index=self.index_name, doc_type="_doc", body=json.dumps(bas)) rep_result.append(json.dumps(bas)) except KeyError: pass -
How do I get more details from uWSGI process Segmentation Fault?
I decided to follow the "uwsgi, Django, and nginx tutorial"; But I didn't get too far before I received a segmentation fault message. I can't seem to figure out how to get more details. How do I get more details from uWSGI process Segmentation Fault? Here are the steps to help reproduce the same issue. Tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html Setup OS: alpine3.13 Python: 3.10 Django: 3.2.9 Dockerfile: https://github.com/docker-library/python/tree/8e591562e4e9ea0c2ab27d428918007abbc688a1/3.10/alpine3.13 RUN apk update && apk add gcc musl-dev python3-dev libffi-dev libressl-dev cargo bash vim && \ apk add pcre pcre-dev supervisor openssl curl ca-certificates nginx && \ pip install --upgrade pip && \ pip install Django==3.2.9 && \ pip install -I --no-cache-dir uwsgi After starting up the container and logging into it: git clone https://github.com/do-community/django-polls.git cd django-polls/ uwsgi --http :8000 --module mysite.wsgi The output and No details to the Segmentation Fault *** Starting uWSGI 2.0.20 (64bit) on [Sun Nov 14 18:30:03 2021] *** compiled with version: 10.2.1 20201203 on 14 November 2021 08:43:40 os: Linux-5.10.47-linuxkit #1 SMP Sat Jul 3 21:51:47 UTC 2021 nodename: 39e77de2e1ed machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: /app/django-polls detected binary path: /usr/local/bin/uwsgi uWSGI running as root, you can use … -
How can i do, When user come my site than show "page is UnderConstruction"?
I went to do, whan any user come my wabsite than only one url/view show him page is UnderConstruction ???? I know full site UnderConstruction but don't only one page ..... This is my middelware.py:- class UnderConstruction: def __init__(self,get_response): self.get_response = get_response def __call__(self,request, *args, **kwargs): response = reverse("about") return response I went to show him only about view so, i provide only about views views.py:- from .middelware import UnderConstruction from django.utils.decorators import decorator_from_middleware @decorator_from_middleware(UnderConstruction) def about(request): return render(request, 'blog/about.html') setting.py:- By the way my app name is blog MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #.......This middelware for site UnderConstruction........# 'blog.middelware.UnderConstruction' ] urls.py:- path('base/', base, name='base'), So, i think i went to change/add in middelwaer.py file , i don't understand what need plz help anyone.... Thanks.... -
How to handle login API in Django web app
I have already implemented a list of shop API including user api, product api etc using Rest Framework. User api include basic login/logout/register methods. Login require username and password, so API call looks like requests.post('api/api_user/login', {username='name', password='password'}). Post method returns auth token like following: Post result The issue is how can i handle @login_required in web app using my API. The idea of login is intuitive, i can send post request and get token which can be stored in cookies, but Django use it's own authentication system to handle user login on viewes (@login_required decorator), so i left with an idea to get token from cookies in every request and check it for correctness, but is it right way to do such things? I'm looking for examples or suggestions how this thing should be implemented. -
I don't understand why! show me that error local 'variable referenced before assignment' Django?
I don't understand why! show me that error local 'variable referenced before assignment' Django? it works fine till the homeTeam, awayTeam, referees that i cant pass in results dict. i tried some solutions like using variable as GLOBAL but fails. def my_api(request): matches = Matches.objects.all().prefetch_related('score', 'homeTeam', 'awayTeam', 'referees').order_by('-id') all_results = [] for match in matches: # Works fine id = match.id utcDate = match.utcDate status = match.status matchday = match.matchday stage = match.stage group = match.group lastUpdated = match.lastUpdated for score in match.score.all(): #Works fine sco = {} sco['winner'] = score.winner sco['duration'] = score.duration sco['fthomeTeam'] = score.fthomeTeam sco['ftawayTeam'] = score.ftawayTeam sco['hthomeTeam'] = score.hthomeTeam sco['htawayTeam'] = score.htawayTeam sco['exthomeTeam'] = score.exthomeTeam sco['extawayTeam'] = score.extawayTeam sco['phomeTeam'] = score.phomeTeam sco['pawayTeam'] = score.pawayTeam for homeT in match.homeTeam.all(): # Here is the problem local variable 'hometeams' referenced before assignment hometeams = { # i can't pass this variable to result 'id': homeT.id, 'name': homeT.name, } #hometeams['id'] = homeT.id #hometeams['name'] = homeT.name for awayT in match.awayTeam.all(): # Here is too problem awayteam = {} awayteam['id'] = awayT.id awayteam['name'] = awayT.name for referees in match.referees.all(): # And here too problem refer = {} refer['id'] = referees.id refer['name'] = referees.name refer['role'] = referees.role refer['nationality'] = referees.nationality result = { … -
Why am I getting name 'request' is not defined?
I'm following a Django tutorial and have reached the point of using return renderand currently my views.py looks like this: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def construction_view(*args, **kwargs): return HttpResponse("<h1> This site is currently being constructed. Please check back later </h1>") def home_view(*args, **kwargs): return render(request, "home.html", {}) I am getting an error whien trying to go to my home page: views.py", line 9, in home_view return render(request, "home.html", {}) NameError: name 'request' is not defined Not sure what is causing this as according to Django docs request is part of render which is imported above. -
Django annotate Count over queryset results
Let's imagine the next model: class Product(models.Model): name = models.CharField(max_lenght=255) category = models.ForeignKey(Category, ...) type = models.ForeignKey(Type, ...) platform = models.ForeignKey(Platform, ...) [...] Users can filter by every ForeignKey__id field and the filtered queryset is used to construct a dynamic filter for the frontend with next structure: "filter": { "categories": [ { "category__id": 1, "category__name": "videogames", "total": 12 }, { "category__id": 2, "category__name": "funkos", "total": 3 } ], "types": [ { "type__id": 3, "type__name": "accessory", "total": 2 }, { "type__id": 2, "type__name": "console", "total": 4 } ] } Where total is the number of Products associated with each category, type, etc.. The values are calculated as following: categories = queryset.values('category__id', 'category__name').annotate(total=Count('id')) queryset can also be filtered by, for example, products with a price grater than 25.00$. Is there any way to get the total field value (currently annotate(total=Count('id'))) based on queryset values, not on database values? -
How do I create a queue of records in django?
In general, when I experimented with the capabilities of Django, I had a question how I can add a queue for model records, for example, I have a couple of blocks and I need to display the model that was registered first and on the second block it should be displayed next entry. How can I do this? here is an example query_set class IndexView(generic.ListView): template_name = 'article/sale.html' model = Goods context_object_name = 'goods' def get_queryset(self): return Goods.objects.order_by('-pub_date')[:1] In html, I output the entry like this {% for good in queryset %} <h1 class="price" >{{ good.price2_text }}</h1> {% endfor %} this is code of models.py class Goods(models.Model): description_text = models.CharField(max_length=200) price_text = models.CharField(max_length=200) image_sale = models.ImageField(blank=True, upload_to='images/') description1_text = models.CharField(max_length=200) price1_text = models.CharField(max_length=200) image1_sale = models.ImageField(blank=True, upload_to='images/') description2_text = models.CharField(max_length=200) price2_text = models.CharField(max_length=200) image2_sale = models.ImageField(blank=True, upload_to='images/') pub_date = models.DateTimeField('date published') def __str__(self): return self.description_text def __str__(self): return self.price_text def __str__(self): return self.description1_text def __str__(self): return self.price1_text def __str__(self): return self.description2_text