Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fat`s formula on python
I have a formula: %fat=495/(1.29579-0.35004(log(hips+waist-neck))+0.22100(log(growth)))-450 How did this fat formula on python? I make it: from math import log fat = 495 / (1.29579 - 0.35004 * log(self.hips + self.waist - self.neck) + 0.22100 * log(self.user.profile.growth)) - 450 But the meanings are far from the truth. Link on calculator https://www.scientificpsychic.com/fitness/diet-calculator-ru.html -
If your program executing second.py file. How would you access variable with data of second.py file? [duplicate]
I've seen many post regarding this but doesn't found solution. You have first.py def AI_click(self): string="" os.system('python second.py') self.lineEdit.setText(string) If this method called, second.py will execute. In second.py you have, string="mntk" How will you use second.py string in first.py function? I also asked here This is nothing to do with import because in real second.py contain AI model and it predicts alphabets using ocr and store string value in variable. That's what I want to access in first.py -
Django mapping urls to views
ModuleNotFoundError: No module named 'playground/urls' I am going through the ultimate django series by mosh hamedani and i came across a problem. I did exactly as he did and it didn't work for me. Here are my urls.py and installed apps. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground' ] playground/urls.py from django.urls import path from . import views #URLConf urlpatterns = [ path('hello/', views.say_hello) ] storefront/urls.py """storefront URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.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')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground/urls')) ] -
get the related records in a serializer - django
I am trying to obtain in a query the data of a client and the contacts he has registered I tried to do it in the following way but it did not work. class ClientReadOnlySerializer(serializers.ModelSerializer): clientcontacts = ClientContactSerializer(many=True, read_only=True) class Meta: model = Client fields = "__all__" Is there any way to make this relationship nested? these are my models clients model # Relations from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU from apps.clients.api.models.broker.index import Broker from apps.authentication.models import User class Client(models.Model): id = models.CharField(max_length=255, unique=True,primary_key=True, editable=False) type_client = models.ForeignKey(TypeCLient, on_delete=models.CASCADE, blank=True) type_identity = models.ForeignKey(TypeIdentity, on_delete=models.CASCADE, blank=True) document_number = models.CharField(max_length=255, blank=True, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) social_reason = models.CharField(max_length=255, blank=True, null=True) city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True) address = models.CharField(max_length=255, blank=True) email = models.CharField(max_length=255, blank=True, unique=True) phone_number = models.CharField(max_length=255, blank=True, unique=True) ciiu = models.ForeignKey(CIIU, on_delete=models.CASCADE, blank=True) broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) income = models.SmallIntegerField(blank=True, default=0) state = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True, default=None) client contacts model # Relations from apps.clients.api.models.index import Client class ClientContact(models.Model): id = models.CharField(max_length=255, primary_key=True, unique=True, editable=False) client = models.ForeignKey(Client, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone_number = models.CharField(max_length=255) state = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) … -
drf: serializers.ModelField > How can i get user_id appropriately?
I want to implement the 'user_id' to be automatically saved at the backend without receiving it from the client. (when create object!) This is my code. models.py class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() social_profile = models.URLField(null=True,blank=True) realname = models.CharField(max_length=50, blank=True) nickname = models.CharField(max_length=50, null=True, unique=True) address = models.CharField(max_length=200, blank=True) phone = models.CharField(max_length=100, blank=True) def __str__(self): return self.email class Item(models.Model): user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING) description = models.TextField() feature = models.TextField() product_defect = models.TextField() size = models.CharField(max_length=6) height = models.DecimalField(max_digits=4, decimal_places=1, default=0) weight = models.DecimalField(max_digits=4, decimal_places=1, default=0) condition = models.CharField(max_length=20) price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) sold_out = models.BooleanField(default=False) def __str__(self): return self.description view.py class ItemViewSet(ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = [SearchFilter, OrderingFilter] search_fields = ['description'] # ?search= ordering_fields = ['created_at'] # ?ordering= ordering = ['-created_at'] authentication_classes = (JWTCookieAuthentication,) # create def create(self, request, *args, **kwargs): city = request.data['city'] gu = request.data['gu'] dong = request.data['dong'] if city is not None and gu is not None and dong is not None: location = Location.objects.get( Q(city=city) & Q(gu=gu) & Q(dong=dong) ) else: return Response( {"message": "주소정보를 모두 입력해주세요."}, status=status.HTTP_400_BAD_REQUEST ) … -
Django - Unexpected behaviour with default ordering after annotations
I've discovered a rather odd case where if I set default ordering on a model to id or -id then add distinct annotations to the query, the default ordering is ignored and instead orders by id ascending regardless of what it is set as in the model Meta. However, when I choose a field that isn't specifically id as the default ordering of the model and do the same thing, the queryset is ordered correctly. It only seems to by id. What gives? I'm not sure if this is Django weirdness or postgres weirdness, is it because it's the primary key? If I use .order_by('-id') afterwards it orders as desired and if the ordering gets broken by annotating it, how come it doesn't always break? Example Django version: 4.1 Postgres version: 13.4 class OrderQuerySet(models.QuerySet): def annotateItemCounts(self): return self.annotate( num_items=Count('order_items', distinct=True), num_items_draft=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.DRAFT)), num_items_back_order=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.BACK_ORDER)), num_items_confirmed=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.CONFIRMED)), num_items_in_progress=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.IN_PROGRESS)), num_items_ready=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.READY)), num_items_packed=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.PACKED)), num_items_shipped=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.SHIPPED)), num_items_completed=Count('order_items', distinct=True, filter=Q(order_items__state=OrderItem.OrderItemState.COMPLETE)), ) class OrderManager(models.Manager): def get_queryset(self): return OrderQuerySet(self.model, using=self._db) def annotateItemCounts(self): return self.get_queryset().annotateItemCounts() class Order(models.Model): class Meta: ordering = ['-id'] ... -
Get top rows by one column Django
I'm making a job to categorize earnings and expenses, from app of movimentations. To this, i need get the category to tile, with more cases. For example, in this Scenario: | title | category | count | | ----- | -------------- | ----- | | Pizza | food | 6 | | Pizza | others_expense | 1 | | Pizza | refund | 1 | I want return just the first row, because the title is the same, and category food is used with most frequency. Code example I want get the result using just Django ORM, because i have diferent databases and is more fast than iterate over a large list. Model: class Movimentation(models.Model): title = models.CharField(max_length=50) value = models.FloatField() category = models.CharField(max_length=50) Consult: My actual consult in Django ORM is. Movimentation.objects \ .values('title', 'category') \ .annotate(count=Count('*')).order_by('title', '-count') Result: [ {'title': 'Pizza', 'category': 'food', 'count': 6}, {'title': 'Pizza', 'category': 'others_expense', 'count': 1}, {'title': 'Pizza', 'category': 'refund', 'count': 1}, {'title': 'Hamburguer', 'category': 'food', 'count': 1}, {'title': 'Clothing', 'category': 'personal', 'count': 18}, {'title': 'Clothing', 'category': 'home', 'count': 15}, {'title': 'Clothing', 'category': 'others_expense', 'count': 1} ] Expected result: In this case, i get just one row by title, with the most used … -
HTML background image on full screen: I try to put a picture as background but it cuts the picture for me I want it to stay full size
The image works for me and is displayed on the screen, but when I make it the background, it cuts off part of it, which lowers the quality of the image and looks bad. I would appreciate your help, thanks <!DOCTYPE html> {% load static %} <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> html { background: url("{% static 'images/second.JPG' %}") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } </style> </head> <body> </body> </html> -
Django Models between apps
Do I need is to import a model from app tienda and show the data in my home.html page My Project name is Proyectoweb My project apps are Proyectowebapp, Tienda I have nothing in Proyectowebapp.models.py In tienda models.py I wrote: from django.db import models class CategoriaProd(models.Model): nombre=models.CharField(max_length=50) imagen = models.ImageField(upload_to="catimgs", null=True, blank=True) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name="categoriaProd" verbose_name_plural="categoriasProd" def __str__(self): return self.nombre class Producto(models.Model): nombre = models.CharField(max_length=50) categorias = models.ForeignKey(CategoriaProd, on_delete=models.CASCADE) imagen = models.ImageField(upload_to="tienda", null=True, blank=True) precio = models.FloatField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name="Producto" verbose_name_plural="Productos" def __str__(self): return self.nombre In Proyectowebapps views.py i wrote: from django.shortcuts import render from tienda.models import CategoriaProd def home(request): return render(request, "Proyectowebapp/home.html") def tienda(request): prodcats=CategoriaProd.objects.all() return render(request, "Proyectowebapp/home.html", {"prcat":prodcats}) In my home.html I wrote: {% for categoriaProd in prcat %} <img src="{{categoriaProd.imagen.url}}"> <h7>{{categoriaProd.nombre}}</h7> {% endfor %} Thanks, Sorry but Im new in Django world -
Calculating serializers read only fields
Here is an example: # models.py class MyModel(models.Model): ... metadata = models.JSONField() # serializers.py class MetadataSerializer(serializers.Serializer): x = serializers.IntegerField() y = serializers.IntegerField(read_only=True) # views.py class MyAPIView(APIView): def post(self, request): serializer = MetadataSerializer(data=request.data) serializer.is_valid() create_mymodel(metadata=serializer.validated_data) return Response(status=201) I would like to calculate y based on x using "complex" business logic y = const * x and save result to json field. Q: Where should i place this business logic? before serializer init, intercepting immutable request.data inside serializer validate() or validate_y() method. using get_y() of SerializerMethodField. inside create_mymodel() service. -
How to disable the grid in Openseadragon (Deepzoom) image
I'm working with deepzoom OpenSeaDragon and a grid keeps showing in some browsers Screenshot Screenshot2 Please help if anyone has an idea about a possible solution.. Thank you so much -
Django WSGI Apache
I am developing a Django Application and currently experiencing issue during WSGI + Apache integration. Below are my server configuration RHEL : 8.6 Python : 3.6.8 Apache : 2.4.37 After following various tutorials i have the following configurations under my httpd.conf, app.wsgi My httpd.conf file look like this LoadModule wsgi_module modules/mod_wsgi.so WSGIDaemonProcess django_project python-path=/home/project user=apache group=developers WSGIProcessGroup django_project WSGIScriptAlias / /home/project/myapp/wsgi.py process-group=django_project <Directory /home/project/myapp> <Files wsgi.py> Require all granted </Files> </Directory> My wsgi file look like this import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_wsgi_application() Here is the error message which i get under my httpd log [Mon Aug 29 09:49:19.786017 2022] [mime_magic:error] [pid 721666:tid 140511423796992] [client 192.168.1.112:49310] AH01512: mod_mime_magic: can't read `/home/project/myapp/wsgi.py' [Mon Aug 29 09:49:19.786118 2022] [mime_magic:error] [pid 721666:tid 140511423796992] [client 192.168.1.112:49310] AH01512: mod_mime_magic: can't read `/home/project/myapp/wsgi.py' [Mon Aug 29 09:49:19.786443 2022] [wsgi:error] [pid 721665:tid 140511574705920] (13)Permission denied: [remote 192.168.1.112:49310] mod_wsgi (pid=721665, process='django_project', application='192.168.1.114|'): Could not read/compile source file '/home/project/myapp/wsgi.py'. [Mon Aug 29 09:49:19.786503 2022] [wsgi:error] [pid 721665:tid 140511574705920] [remote 192.168.1.112:49310] mod_wsgi (pid=721665): Exception occurred processing WSGI script '/home/project/myapp/wsgi.py'. [Mon Aug 29 09:49:19.786564 2022] [wsgi:error] [pid 721665:tid 140511574705920] [remote 192.168.1.112:49310] PermissionError: [Errno 13] Permission denied: '/home/project/myapp/wsgi.py' My project directory have the following permission chown -R … -
django queryset select all from multiple tables
I want to select all columns from multiple table join using django queryset corresponding to following sql select user.*, address.*, contact.* from user left join address on user.id = address.userid left join contact on user.id = contact.userid I have following python User.objects.values() to get all user data. User.objects.values(first_name, last_name, contacts__number, addresses__zip) to get specific columns But I dont know how to get all columns from all 3 tables something like User.objects.values(*, contacts__*, addressess__*) -
How to access to attrbuite of another model or table using ManyToMany in django
Please, I need your help. How can I access to attribut of another model or table using ManyToMany I need to get data through this method but it's not retrieved ---=> this is Models.py class Mission(models.Model): nom=models.CharField(max_length=50,null=False,blank=False) description=models.CharField(max_length=150,null=False,blank=False) date_publier=models.DateTimeField() class Participer(models.Model): id_benevole = models.ManyToManyField(User) id_mission = models.ManyToManyField(Mission) est_participer = models.BooleanField(default=False) class User(AbstractUser): est_association = models.BooleanField(default=False) est_benevolat = models.BooleanField(default=False) username = models.CharField(max_length=30,unique=True) email = models.EmailField() password1 = models.CharField(max_length=20,null=True) password2 = models.CharField(max_length=20,null=True) class ProfileBenevole(models.Model): user = models.OneToOneField(User,related_name="benevole", on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) --=> this is Views.py def demande_participer(request): participers=Participer.objects.all() return render(request,'Association/success.html', {'participers':participers},print(participers)) ----=> success.html {% extends 'home/base.html'%} {% block content %}{% load static %} <div class=" mt-4 pb-5"> <h1 style="text-align:center;">Confirmation de Participation </h1> <div class="container"> <div class="card mt-5 pb-5"> {% for parti in participers %} {{parti.mission_id.nom}} <br> {{parti.id_benevole.username}} <br> {{parti.est_participer}} {% endfor%} </div> <a class="btn btn-secondary mt-2 " href="{% url 'benevole' %}">Retour </a> </div> </div> {% endblock content %} -
Django template double the data [closed]
I would need to display the information but it displays twice. Does anyone know how to put (list and disci) together as I know the error is in my code with the for i, for j and {% endfor %} in double. Employe and Disciplinaire are 2 different table with is own data. page.html <tr> <th scope="col">Matricule</th> <th scope="col">Prenom</th> <th scope="col">Nom</th> <th scope="col">Avis Verbal</th> <th scope="col">1er Avis Écrit</th> <th scope="col">2er Avis Écrit</th> <th scope="col">Suspension</th> <th scope="col">Fin d'emploi</th> <th scope="col">Actions</th> </tr> {% for i in liste %} {% for j in disci %} <tr> <td>{{i.Matricule}}</td> <td>{{i.Prenom}}</td> <td>{{i.Nom}}</td> <td>{{j.Avis_verbal}}</td> <td>{{j.Avis_ecrit}}</td> <td>{{j.Avis_ecrit2}}</td> <td>{{j.Suspension}}</td> <td>{{j.Fin_emploie}}</td> <td><a href="">Editer </a>/<a href=""> Supprimer</a></td> </tr> {% endfor %} {% endfor %} views.py def disciplinaire(request): disci = Disciplinaire.objects.all() liste = Employe.objects.all() return render(request, 'accounts/page.html', {'disci':disci, 'liste':liste}) Screenshot of page.html -
How to properly use multiprocessing module with Django?
I'm having a python 3.8+ program using Django and Postgresql which requires multiple threads or processes. I cannot use threads since the GLI will restrict them to a single process which results in an awful performance (especially since most of the threads are CPU bound). So the obvious solution was to use the multiprocessing module. But I've encountered several problems: When using spawn to generate new processes, I get the "Apps aren't loaded yet" error when the new process imports the Django models. This is because the new process doesn't have the database connection given to the main process by python manage.py runserver. I circumvented it by using fork instead of spawn (like advised here) so the connections are copied to the other processes but I feel like this is not the best solution and there should be a clean way to start new processes with the necessary connections. When several of the processes simultaneously access the database, sometimes false results are given back (partly even from wrong models / relations) which crashes the program. This can happen in the initial startup when fetching data but also when the program is running. I tried to use ISOLATION LEVEL SERIALIZABLE (like … -
Django does not throw ValidationError when required fields are not present
I am currently testing my django model using pytest (and pytest-django), but I can not write a failing test case in which a required field is missing. My Person-model requires solely a name and a company. The other fields are nullable and therefore optional. models.py: from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=64) company = models.CharField(max_length=128) position = models.CharField(max_length=64, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) def __str__(self): return (f"{self.name}" + (f", {self.position}" if self.position is not None else "") + f"({self.company})" + (f" born {self.date_of_birth}" if self.date_of_birth is not None else "") ) test.py from .models import Person import pytest from django.core.exceptions import ValidationError pytestmark = pytest.mark.django_db # Create your tests here. def test_minimal_person(): """Test if a minimal person can be created""" valid_person = Person(name="Max Mustermann", company="ACME") valid_person.save() assert len(Person.objects.get_queryset()) == 1 def test_insufficient_params(): with pytest.raises(ValidationError): invalid_person = Person() invalid_person.save() def test_missing_company(): with pytest.raises(ValidationError): invalid_person = Person(name="Max") invalid_person.save() def test_missing_name(): with pytest.raises(ValidationError): invalid_person = Person(company="ACME") invalid_person.save() def test_invalid_date_format(): """Test if an invalid date format throws a ValidationError""" with pytest.raises(ValidationError): invalid_person = Person(name="Max", company="ACME", date_of_birth="not-a-date") invalid_person.save() The test test_invalid_date_format and test_minimal_person succeed, but the other ones do not throw an (expected) error. What am I … -
My django form is showing that data is posted but data isnt being saved to database
So my form was working just fine until i played around with my frontend...changing the look of the system. But i dont think this has an effect on my forms but surprisingly all my forms are no longer saving data to the database!! Some help here guys. Here is my views.py from django.contrib.auth.models import User from django.contrib import messages from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from .forms import * # Create your views here. def register(request): form = RegistrationForm() if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'User successfully registered!') return redirect('home') else: form = RegistrationForm() return render(request, 'accounts/register.html', {'form': form} ) def login(request): if request.method == 'POST': username = username.POST['username'] password = request.POST['password'] try: user = Account.objects.get(username=username) except: messages.error(request, 'username does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid username Or Password') return render(request, 'accounts/login.html', {} ) models.py from distutils.command.upload import upload import email from django.db import models from django.conf import settings from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.base_user import BaseUserManager class MyAccountManager(BaseUserManager): def _create_user(self, email, username, profile_pic, address, phone_number, car, details, password): if not email: raise ValueError("User … -
Django is not collecting all my static files
I have 2 folders containing my static files (admin, and assets). However, when I run python manage.py collectstatic, only the static files in the admin folder are collected. Below is a code snippet for static files in settings.py STATIC_URL = 'static/' STATTICFILES_DIRS = [ BASE_DIR/ "asert" ] STATIC_ROOT = (BASE_DIR/"asert/") Below are some urls linking to the static files from an html page <link rel="stylesheet" type="text/css" href="{% static 'assets/css/assets.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendors/calendar/fullcalendar.css' %}"> <!-- TYPOGRAPHY ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/typography.css' %}"> <!-- SHORTCODES ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/shortcodes/shortcodes.css' %}"> <!-- STYLESHEETS ============================================= --> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/dashboard.css' %}"> <link class="skin" rel="stylesheet" type="text/css" href="{% static 'assets/css/color/color-1.css' %}"> -
I'm very new to Django. I am trying to desing my login module and trying to print the values i submit. its not working [closed]
def login(request): form =LoginForm() print(form,'0000000000') if request.method == "POST": form = LoginForm(request.POST) print(form,'1111111111') if form.is_valid(): user = authenticate( username = form.cleaned_data['username'], password = form.cleaned_data['password'], ) if user is not None: login(request, user) else: messages.error(request,"Invalid username or password") else: form =LoginForm() return redirect("post_list", pk=user.pk) return render(request,"blog/login.html", context={"form":form}) -
datalist in HTML new option adding
I have a datalist elements from my view in django model, and i want to have sticky option(option that it's there even if the user enter something not in the list with "add new button" inside or to track it using javascript) to add new record in my model. -
How can I change the "Delete?" label in a Djano Inline
I'd like to replace the default "Delete?" label in TabularInLine to be something like "X". Is there a way to do this in Django directly or do I have to change it after the page loads with JS? example image -
NoReverseMatch at /assetAdmin/ error in Django
I have created a table that contains details about all the Assets. I wish to update the details of the asset. So, from the table, a made asset_id as URL to update page as happens in Django Administration. But after I added the URL pattern to update the asset, I am receiving this error: Reverse for 'asset-update' with keyword arguments '{'id': UUID('cd7edefa-796d-428e-bcec-c90ceecc7fc3')}' not found. 2 pattern(s) tried: ['assets/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/update/\\Z', 'assets/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/\\Z'] Here is my urlpatterns from urls.py: urlpatterns = [ path('home/', home, name='home'), path('assets/', assets, name='assets'), path('assetAdmin/', adminAssetView, name='assetsAdmin'), path('createAsset/', createAssetView, name='createAssets'), path('assets/<uuid:pk>/update/', assetUpdateView.as_view(), name='asset-update'), path('register/', register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='assets/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='assets/logout.html'), name='logout'), path('accounts/profile/', profile, name='profile'), path('admin/', admin.site.urls), ] Here are the views involved: @user_passes_test(lambda u: u.is_superuser) def adminAssetView(request): context = { 'assets': asset.objects.all(), 'users':User.objects.all(), } return render(request, 'assets/assetAdmin.html', context) class assetUpdateView(SuperUserCheck, LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = asset fields = ['currentOwner',] def form_valid(self, form): return super().form_valid(form) def test_func(self): asset = self.get_object() if self.request.user.is_superuser == True: return True return False And here is the part in assetAdmin.html where I am using asset-update urlpattern {% for asset in assets %} <tr> <td><a href="{% url 'asset-update' id=asset.id%}">{{ asset.id }}</a></td> <td>{{ asset.asset_type }}</td> <td>{{ asset.asset_name }}</td> <td>{{ asset.brand }}</td> <td>{{ asset.isActive }}</td> <td>{{ asset.currentOwner }}</td> … -
Issue with django factory for GenericForeignKey
models.py class GoogleCreative(models.Model): name = models.CharField creative_type = models.CharField url = models.URLField table_url = models.URLField status = models.CharField tags = GenericRelation( 'CreativeTag', object_id_field='creative_id', content_type_field='creative_content_type' ) class Tag(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, allow_unicode=True) class CreativeTag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) creative_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) creative_id = models.PositiveIntegerField() creative = GenericForeignKey('creative_content_type', 'creative_id') class Meta: unique_together = ['tag', 'creative_content_type', 'creative_id'] factories.py class GoogleCreativeFactory(factory.django.DjangoModelFactory): class Meta: model = GoogleCreative name = factory.Faker('word') ..... class TagFactory(factory.django.DjangoModelFactory): class Meta: model = Tag django_get_or_create = ('name',) slug = factory.LazyAttribute(lambda o: slugify(o.name, allow_unicode=True)) class CreativeTagFactory(factory.django.DjangoModelFactory): class Meta: model = CreativeTag exclude = ['creative'] class Params: name = factory.Sequence(lambda n: f'tag {n}') tag = factory.SubFactory(TagFactory, name=factory.SelfAttribute('..name')) creative_id = factory.SelfAttribute('creative.id') creative_content_type = factory.SelfAttribute('creative.content_type') test.py @pytest.mark.django_db def test_tags_removed(google_creative_factory, creative_tag_factory, user): creative = google_creative_factory() creative_tag_factory(creative=creative, name='Big Fish') But getting error AttributeError: 'GoogleCreative' object has no attribute 'content_type' I try to solve it adding new field creative to CreativeTagFactory and comment Meta exclude field class CreativeTagFactory(factory.django.DjangoModelFactory): class Meta: model = CreativeTag # exclude = ['creative'] class Params: name = factory.Sequence(lambda n: f'tag {n}') tag = factory.SubFactory(TagFactory, name=factory.SelfAttribute('..name')) creative_id = factory.SelfAttribute('creative.id') creative_content_type = factory.SelfAttribute('creative.content_type') creative = factory.SubFactory(GoogleCreativeFactory) But got the same error -
How to use Django models with enumeration in REST APIs?
I am using User model to store user details: class User(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze') (MEMBERSHIP_SILVER, 'Silver') (MEMBERSHIP_GOLD, 'Gold') ] name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) membership = models.CharField(max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) When customer created using post api then i want to allow only these three values Bronze for MEMBERSHIP_BRONZE, Silver for MEMBERSHIP_SILVER & Gold for MEMBERSHIP_GOLD in membership field. When a user select membership choices lebel from ui then i need to insert the respected value. I don't know how to do this? serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name", "email", "phone", "membership"] views.py @api_view(["GET", "POST", "PUT"]) def userActions(request): if request.method == "GET": users = User.objects.all() serializer = UserSerializer(users, many=True) res = serializer.data if request.method == "POST": name = request.POST.get("name") email = request.user.email phone = request.POST.get("phone") membership = request.POST.get("membership") user = User.objects.create(name=name, email=email, phone=phone, membership=membership) serializer = UserSerializer(user) res = serializer.data return res