Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In which Model should I include approved status of a labour getting a particular job?
So I have created 2 models namely JobModel and LabourModel and I have used Many-to-Many relation between them because 1 labour can apply for multiple jobs and there can be multiple labours applying for 1 job. Now I want to add a feature where the jobcreator can accept/reject a particular labour applying for that particular job and then the labour should be able to see the status regarding approval. I am confused about how should I make a model about this. Here's my current model from django.db import models from django.contrib.auth.models import User from django.urls import reverse_lazy, reverse # Create your models here. class UserModel(models.Model): user = models.OneToOneField(User,related_name = 'user_profile',on_delete=models.CASCADE) CATEGORY_CHOICES = (('Labour','Labour'),('Owner','Owner')) category = models.CharField(max_length=100,choices=CATEGORY_CHOICES,default='NA') is_Labour = models.BooleanField(default=False) is_Owner = models.BooleanField(default=False) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("basic_app:landing") class JobModel(models.Model): user = models.ForeignKey(UserModel,related_name='assigned_job',null=True,on_delete=models.CASCADE) title = models.CharField(max_length=255,null=True) description = models.CharField(max_length=500,null=True) def __str__(self): return self.user.user.username def get_absolute_url(self): return reverse("basic_app:landing") class LabourModel(models.Model): user = models.OneToOneField(UserModel,related_name = 'assigned_labour',null=True,on_delete=models.CASCADE) registered = models.BooleanField(default=False) job_add = models.ManyToManyField(JobModel,related_name = 'labours') def __str__(self): return self.user.user.username def get_absolute_url(self): return reverse("basic_app:landing") -
queryset add more data return in django rest framework
I have issue in django and I want query in table follow to get data performance. this is my problem I have a table follows in django: class Follows(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) user_following = models.ForeignKey(User, related_name="follower", on_delete=models.CASCADE) class Meta: ordering = ["created"] unique_together = ("user_follower", "user_following") verbose_name = "Follows" this is my serializer: class FollowsSerializer(serializers.ModelSerializer): class Meta: model = Follows fields = "__all__" This is my view query set: class FollowsApiView(generics.ListCreateAPIView): serializer_class = serializers.FollowsSerializer def get_queryset(self): user = self.request.user query_set = Follows.objects.filter(user_following=user).annotate(followed=(Follows(user_follower=user))) self.serializer_class = serializers.FollowersSerializer return query_set when I have 1 record A is user_follower, B is user_following and 1 record B is user_follower, A is user_following then when get list Follow how to I can check this condition in query set view: if A followed B and B followed A then return followed = True else False -
How do you containerize a Django app for the purpose of running mulptiple instances?
The idea is to create a Django app what would serve as the backend for an Android application and would serve an web admin interface for managing the mobile application's data. Different sites of the company sometimes need different backends for the same android app (data has to be manageable completely separately). Application will be hosted on Windows server/s. How can I containerize the app so I can run multiple instances of it (listening on different ports of the same IP) and I can move it to different servers if needed and set up a new instance of it there? The Django development part I'm familiar with but I have never used Docker(nor other) containers before. What I need: Either a tutorial or documentation that deals with this specific topic OR Ordered points with some articles or tips how to get this done. Thank you. -
Django: How to add another form to my homepage when the homepage already has a template
On my homepage(http://127.0.0.1:8000/) I created a template and its function in views.py and the URL of the homepage directs to it, however, there is a form that I want also to show on the homepage. -
TypeError: Direct assignment to the forward side of a many to many set is prohibited. Use groups.set() instead
I am currently getting this error when making a POST request, and I am not sure what is causing it because I have not explicitly declared anything as a many-to-many relationship. What's also confusing me is that I don't have any object/relation called group, so why is it saying use groups.set()? I am using nested serializers, as when creating a student I want it to create a user object underneath it. I have attached an image of the GET request succeeding, as it shows the format in which data should be POST'ed Here is an image of the error I'm getting as well These are the two current relations in question that are giving me problems Users(id(PK), username, password, first_name, last_name, dob, role, email, house, comments) Students(id(PK), user_id(FK), grade, enrollment_year) Here is the serializer create method and the view's POST method def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) student = Student.objects.create(**validated_data, user=user) return student def post(self, request): """ Create new student """ serializer = StudentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django migration: `AlterUniqueTogether` fails with `constraint does not exist` but I think it's there
I'm trying to run the following migration using Django 2.2: class Migration(migrations.Migration): dependencies = [ ('actstream', '0002_remove_action_data'), ] operations = [ migrations.AddField( model_name='follow', name='flag', field=models.CharField(blank=True, db_index=True, default='', max_length=255), ), migrations.AlterUniqueTogether( name='follow', unique_together=set([('user', 'content_type', 'object_id', 'flag')]), ), ] The model before the git commit that adds the migration has the following constraint: unique_together = ('user', 'content_type', 'object_id') And after the git commit that adds the migration: unique_together = ('user', 'content_type', 'object_id', 'flag') (flag is a new field and it's also been added to the unique_together constraint). When I try to apply the migration, I get the following error message: psycopg2.errors.UndefinedObject: constraint "actstream_follow_user_id_content_type_id_object_id" of relation "actstream_follow" does not exist Inspecting my database as it is without the migration, tho, I see the following: What am I missing? Thanks! -
Related Field got invalid lookup: name
I am trying to implement Q search on my APIView, but it says invalid lookups name which is strange. I have added the search fields according to the fields of the models. My view: from django.db.models import Q class PrdouctSearchAPIView(ListAPIView): permission_classes = [AllowAny] # def list(self, request, *args, **kwargs): def get(self, request, *args, **kwargs): qur = self.request.query_params.get('search') item = Product.objects.filter(Q(category__name__icontains=qur)| Q(brand__name__icontains=qur)| Q(description__icontains=qur)| Q(collection__name__icontains=qur)| Q(variants__name__icontains=qur)) serializer = ProductSerializer(item,many=True) return Response(serializer.data) My models: class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? class Category(models.Model): #parent = models.ForeignKey('self',related_name='children',on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Brand(models.Model): brand_category = models.ManyToManyField(Category,blank=True,null=True) name = models.CharField(max_length=100, unique=True) class Collection(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) My url is : path('api/productsearch',views.PrdouctSearchAPIView.as_view(),name='api-productsearch'), As we can see there are fields "category__name" and such not only "name", but the error says invalid lookup "name". -
What am I doing wrong that leads to a NOT NULL constraint failed: error on django form submission?
I am working on a little self project and I need some help. I have a doctor model and every time I create a doctor I want to create a new user as well. So a doctor is a user of the system as well. My view has 2 forms, 1 for the doctor part and 1 for the user part, but every time I submit my form I get this error NOT NULL constraint failed: medical_doctor.user_id. If I look in the db afterwards, it has created the user and the doctor but there is no data about the user or the doctor. Any help would appreciated. Here is my model.py file: class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) doctor_name = models.CharField(max_length=200) doctor_surname = models.CharField(max_length=200) contact_number = models.CharField(max_length=10) def __str__(self): return self.doctor_name + ' ' + self.doctor_surname def get_absolute_url(self): return reverse('medical:doctor-details', args=[str(self.id)]) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Doctor.objects.create(user=instance) else: instance.doctor.save() Here is my form.py file: class DoctorCreationForm(forms.ModelForm): class Meta: model = Doctor fields = ['doctor_name', 'doctor_surname', 'contact_number'] class UserCreationForm(forms.ModelForm): class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name'] Here is my view.py file: def createDoctorUser(request): if request.method == 'POST': doctor_form = DoctorCreationForm(data=request.POST, prefix='docForm') user_form … -
Django get_fields() Not Returning Parent Fields
I have an abstract class called CustomBaseModel. It contains 2 fields that record when an entry is created and updated. The Country model inherits this CustomBaseModel. class CustomBaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract=True class Country(CustomeBaseModel): ID = models.BigAutoField(primary_key=True) name = models.CharField(max_length=250) currency = models.CharField(max_length=3) piTag = models.CharField(max_length=4) I also have 2 admin classes that handle model behavior in the admin interface. class CustomAdmin(ImportExportModelAdmin): def get_fields(self, request, obj=None, **kwargs): fields = super().get_fields(request, obj, **kwargs) print(fields) #For debugging ... Additional Operations (ex. fields.remove('created_at')) ... class CountryAdmin(CustomAdmin): resource_class = CountryResource Using get_fields() in the Django Shell, you can see that the parent fields created_at, and updated_at are returned. >>> from aboveSites.models import Country >>> Country._meta.get_fields() (<django.db.models.fields.DateTimeField: created_at>, <django.db.models.fields.DateTimeField: updated_at>, <django.db.models.fields.BigAutoField: ID>, <django.db.models.fields.CharField: name>, <django.db.models.fields.CharField: currency>, <django.db.models.fields.CharField: piTag>) However, the application itself crashes when run due to the following error. list.remove(x): x not in list The print statement in CustomAdmin class confirms that the updated_at, and created_at fields are not returned. [08/Jul/2021 09:17:57] "GET /admin/country/ HTTP/1.1" 200 40484 ['name', 'currency', 'piTag'] Internal Server Error: /admin/aboveSites/country/add/ myApp | Traceback (most recent call last): .... Is it clear to anyone why get_fields in the shell works as expected, but not … -
Django: How to define Transform with more than 1 args?
I'm trying to create a custom Transform for the PostgreSQL specific GET_BYTE() function, so that I can query a bytea column by byte position. I want to be able to do the following SQL: SELECT * FROM my_table WHERE GET_BYTE(my_bytea_column, 0) = 1; The way I imagine it should be handled in Django: MyModel.objects.filter(my_bytea_field__gb0=1) I have tried subclassing Transform and overriding get_transform() on models.BinaryField as the Django documentation on custom lookups suggested. from django.db.models import Transform, BinaryField class GetByte(Transform): function = 'get_byte' # function should take 2 arguments # If set to 1, it fails with 'TypeError: can't escape int to binary' arity = 2 def get_byte_transform(byte_pos): """ This function should return a Transform subclass """ # return GetByte(byte_pos) # TypeError: 2 arguments needed + TypeError: not callable # return GetByte(field, byte_pos) # how do I get the field? + TypeError: not callable return GetByte # this works, but now I lost the byte_pos info class FingerprintField(BinaryField): def get_transform(self, lookup_name): if lookup_name.startswith('gb'): try: byte_pos = int(lookup_name[2:]) # return only works if it returns GetByte, but not GetByte() # but then fails, because it expects 2 args return get_byte_transform(byte_pos) except ValueError: pass return super().get_transform(lookup_name) However, it seems that Transforms expect functions … -
Django web socket not start in server
Help me for above error while i am trying to send message using django channel i am getting above error on server -
Django forms. Make ChoiceField required on frontend <select>
I have created a Django form, which uses a ChoiceField: control_model = forms.ChoiceField(choices=(), required=True) (The reason 'choices' are empty is because they are set using a function based on my backend database) The following is the entire form: class CreateWorkflowForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateWorkflowForm, self).__init__(*args, **kwargs) self.request = kwargs.pop("request") self.fields['control_model'].choices = my_function() control_model = forms.ChoiceField(choices=(), required=True) class Meta: model = CreateWorkflowModel fields = ['control_model'] The model used looks the following: class CreateWorkflowModel(models.Model): control_model = models.CharField(max_length=100) I use this form in a Django template the following way: <div class="form-content"> {{ form.media }} {{ form.as_p }} <input type="submit" id="id_submit" value="Submit" /> </div> However on my webpage the <select> that corresponds to my ChoiceField doesn't have the attribute 'required': This means that my form will fail if no value is input into the ChoiceField (because its required in the form) However I would much prefer if a popup box appeared on frontend stating "You need to enter a value on this field". I know having the "required" value on the <select> would do this exact thing, however I don't know how to make django generate the <select> with this attribute. -
Create JSON object on conditional statement Django Restframework
Iam Working on Django Restframework. I want to create/POST into an API to create an object. The problem is the condition I want to make, is itself in the POST data. For example, I have 5 fields: Name Lastname Email is_member membership_id I want to create a membership_id, if the user "is_member== True" POST while Data receive. Iam until here def create_user(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') category = request.POST.get('category') timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) if is_member == True: membership_id = hashString(str(timestamp)) else: membership_id = "" try: user_object = MasterUser( firstname = firstname, lastname = lastname, email = email, contact = contact, is_member = is_member, date_joined = date_joined, last_signed_in = last_signed_in, is_subscription = is_subscription, category = category, membership_id = membership_id ) user_object.save() return HttpResponse('User successfully created') Is it possible or do I have to look out for some different apporach. Any ideas are welcomed! Thanks -
Heroku can't connect pdf fonts
I have downloaded fonts for html template that is converted with xhtml2pdf to pdf. I didn't manage to google for answer that works for me. I thought that path was changed but in heroku bash path isn't change. Here are some photos of my code: fonts are in invoices/static/invoices/fonts -
How to add @property to the base Group model in Django?
I want to be able to add a property to the group model This is what I have been trying from django.contrib.auth.models import Group class GroupExtensions(Group): class Meta: proxy = True @property def assigned_property(self): return 'something' I want to get this property from the base group model group_instance.assigned_property Where group is an instance of the Group model -
Bootstrap dropdown not appearing directly under navbar button
I am very new to bootstrap and html/css so sorry if this may be an obvious question. I am working on a Django project and I am currently trying to have a navbar button be a dropdown to have multiple different options. Like what you typically see in a profile dropdown in a lot of websites. Currently I am able to get that working but the dropdown appears on the far left side of the page and not directly under the button like what you expect. I followed bootstraps documentation on the navbar but it seems to still only show on the left side. Is there something I am missing? Here is what the output is currently like on the website: Here is the html code: <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-jj fixed-top"> <div class="container"> <a class="navbar-brand mr-4 jjfont" href="/"> <i class="material-icons">logo</i> WEBSITE NAME</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <!-- Navbar Left Side Goes Here --> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <!-- home icon --> <a class="nav-item nav-link" href="/"> <i class="material-icons">home</i> </a> <!-- create icon --> <a class="nav-item … -
'JSONRenderer' object has no attribute 'has_permission'
Error Screenshot I am working on react-native and django together in Pycharm. When I run the project. Attribute Error popped up! I don't know how to fix it and there's no related articles on Google for 'JSONRenderer object has no attribute has_permissions'. Also Internal Server Error is Displaying on terminal. Internal Server Error -
two project with same database user table problem
I have two projects and I have connected both to one database. One of these projects has an abstract user, which means I have overridden the user table. But in it I use one of the default Django tables. In this case, when I want to create a superuser in the second project, it gives this error: django.db.utils.OperationalError: no such table: auth_user What can I do? -
How to make ajax request for dependent drop down
I am new to programming and learning django. I am struggling to understand how to make ajax request to fetch data to create dependent dropdown lists. I have looked around on various google searches and stackoverflow but I get more confused looking at them. Hence, I could not move forward with fetching the dependent values My code for html looks like this <div class="form-group"> <select name ="service" id="service"> {% for item in serv %}" <option value="{{ item.id }}" >{{ item.name }}</option> {% endfor %} </select> <select name ="subcategory" id="subcategory"> {% for item2 in subcategory %}" <option value="{{ item2.id }}" >{{ item2.name }}</option> {% endfor %} </select> </div> My views.py looks like this def book(request): employees = Employee.objects.values_list('name',flat=True) services_ = Service.objects.values_list('name',flat=True) services = [] serv = Service.objects.all().order_by('-id') subcategory = SubCategory.objects.all().order_by('-id') # subcategory = SubCategory.objects.get(pk=request.GET('service_pk')) for i in services_: services.append(i) context = { 'employees':employees, 'services':services, 'serv':serv, 'subcategory':subcategory, } return render(request,'book.html',context=context) my urls.py is set like this among others path('service/<int:service>', services, name='services'), my models.py looks like this def rand_slug(): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) # Create your models here. def path_and_rename(instance, filename): upload_to = 'uploads/images' ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set … -
How to add a template folder to the Django project ? (in community pycharm)
How to add a template folder to the Django project ?(in community pycharm) -
How to make city recognition in urls in django app
What is best practice for django app to add city recognition in urls like: stite_name/moscow/ stite_name/city_name/ And how to make it found in google and e.t.c. -
Django error when filter by date "operator does not exist: date >= integer"
I'm using django framework with postgresql. I have virtual environment. My local machine Mac , server is on Debian 10. $ pip freeze amqp==5.0.6 asgiref==3.4.1 billiard==3.6.4.0 celery==5.1.2 certifi==2021.5.30 chardet==4.0.0 click==7.1.2 click-didyoumean==0.0.3 click-plugins==1.1.1 click-repl==0.2.0 Django==3.2.5 django-celery-beat==2.2.1 django-celery-results==2.2.0 django-timezone-field==4.1.2 greenlet==1.1.0 idna==2.10 kombu==5.1.0 lxml==4.6.3 multitasking==0.0.9 numpy==1.21.0 pandas==1.3.0 plotly==5.1.0 prompt-toolkit==3.0.19 psycopg2==2.9.1 psycopg2-binary==2.9.1 python-crontab==2.5.1 python-dateutil==2.8.1 pytz==2021.1 requests==2.25.1 six==1.16.0 SQLAlchemy==1.4.20 sqlparse==0.4.1 tenacity==7.0.0 urllib3==1.26.6 vine==5.0.0 wcwidth==0.2.5 yfinance==0.1.60 models.py from django.db import models from django.utils import timezone class Ticker(models.Model): symbol = models.CharField(max_length=12) description = models.CharField(max_length=100, blank=True, default='') avg_volume = models.DecimalField(max_digits=20, decimal_places=6) last_close_price = models.DecimalField(max_digits=20, decimal_places=6, default=0) last_update_date = models.DateField(default=timezone.now) def __str__(self): return self.symbol class TickerData(models.Model): date = models.DateField(default=timezone.now) open_price = models.DecimalField(max_digits=20, decimal_places=6) high_price = models.DecimalField(max_digits=20, decimal_places=6) low_price = models.DecimalField(max_digits=20, decimal_places=6) close_price = models.DecimalField(max_digits=20, decimal_places=6) adj_close = models.DecimalField(max_digits=20, decimal_places=6) volume = models.IntegerField() symbol = models.ForeignKey(Ticker, on_delete=models.CASCADE, related_name='infoset') def __str__(self): return f'{self.symbol}: {self.date}' views.py from datetime import date, datetime, timedelta from django.db import connection from django.shortcuts import render, get_object_or_404 from .models import Ticker, TickerData def ticker_data_view(request, pk): # dates enddate = date.today() startdatedays = enddate - timedelta(days=180) ticker = Ticker.objects.get(pk=pk) ticker_info = TickerData.objects.filter(symbol=ticker).filter(date__gte=startdatedays) context = { 'TickerData': ticker_info, } return render(request, 'tickerdata_list.html', context) When I open page with info DatabaseError at /ticker/2 Execution failed on sql 'SELECT "webapp_tickerdata"."id", "webapp_tickerdata"."date", "webapp_tickerdata"."open_price", … -
Video streaming from multiple users in Django
I am developing an exam platform website where people can create exams and take exams. I almost finished the examination part and wanted to add a proctoring system. I want that when people start any quiz, their video is displayed on the examiner's side. That is, when the users press (ex.) the "Start Quiz" button, their video is turned on. And examiners can watch all the exam passers in some url. I found that I could use OpenCV to do this, but couldn't figure out how to get multiple video sharings from different users. Please suggest me any ideas. What should I learn? Can this be implemented in Django? -
Django add child line to form for all related children
I have a django form for entering a turnover order (like a sales order). Each order, has one specified supplier, and the supplier supplies only certain lines. How can I add a list of children lines in the form for all products that supplier has? This is the order model (the Parent of the order) class Turnover(models.Model): created_date = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null = True, related_name = 'to_created_by') last_update = models.DateTimeField(auto_now=True) representative = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null = True) order_date = models.DateField(auto_now_add = True) customer_ref = models.CharField(max_length=20, blank=True, null = True) discount = models.DecimalField(decimal_places=1, max_digits=6) This is the lines for the order class TurnoverLine(models.Model): turnover = models.ForeignKey(Turnover, on_delete=CASCADE) pde = models.ForeignKey(Pde, models.SET_NULL, blank=True, null = True) units = models.IntegerField(default = 0) bonus = models.IntegerField(default = 0) The views can (if needed) create all of the lines for that supplier. Supplier x line 1. Product a "qty" line 2. Product d "qty" line 3. Product f "qty" The end user adds "Units" and "bonus", everything else is taken care of in views. -
Getting psycopg2.errors.DuplicateColumn error when applying Django Migrations on server
Trying to apply django migrations on server gives psycopg2.errors.DuplicateColumn error though it runs normal locally and creates all the appropriate db tables. Can the difference in Postgresql versions in local and server be the reason? or something else?