Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
want fetch existing data from db in django. 1054 "Unknown column 'traders.id' in 'field list'" error getting. Id is automatically generate in db
def Fetch_data(request): if 'q' in request.GET: q = request.GET['q'] #enter image description here'q' is name given in form data = Traders.objects.filter(traders_name__icontains=q) else: data = Traders.objects.all() return render(request,"fetch_data.html", {'data':data}) html file(tempplate)- <tbody> {% for data in data %} <tr> <th scope="row">1</th> <td>{{data.traders_name}}</td> <td>{{data.email}}</td> <td>{{data.registration_no}}</td> <td>{{data.address}}</td> </tr> --> {% endfor %} </tbody> -
How to validate fields in Django?
I'm new to Django. I was a .NET developer. I've created a form for new users' registration, but my problem is that I need some validation controls to validate my fields. I could not find any resources or examples. Any help, please? My newuser.html is in the below: {% block content %} <form method="POST"> {% csrf_token %} <table> <tr> <td> <lable>Name </lable> </td> <td> <input type="text" name="name"> </td> </tr> <tr> <td> <lable>Username </lable> </td> <td> <input type="text" name="username"> </td> </tr> <tr> <td> <lable>Password </lable> </td> <td> <input type="password" name="password"> </td> </tr> <tr> <td> <lable>Confirm password </lable> </td> <td> <input type="password" name="confirmPassword"> </td> </tr> <tr> <td> <lable>email </lable> </td> <td> <input type="email" name="email"> </td> </tr> <tr> <td> <input type="submit" name="save" value="Save" colspan=2> </td> </tr> </form> {% endblock content %} -
in Django: How to get and display in template verbose_name of a model that their value is true, while name of field unknown?
I have a model than has a lot of models.BooleanField declarations. class a_lot_of_booleans(model.Models): old_or_new = models.BooleanField(default=False,verbose_name="is it an old or a new item") product_for_teens = models.BooleanField(default=False,verbose_name="is this product for teens") in_original_package = models.BooleanField(default=False,verbose_name="is this product in original package?") Which then is used in some other classes like: class product_for_sale(a_lot_of_booleans): U_Id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) product_name=models.CharField(max_length=50) class product_for_buying(a_lot_of_booleans): U_Id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) product_name=models.CharField(max_length=50) The class a_lot_of_booleans might change over time. Some booleans might get added some might get removed. What I need is to display a list of several entries, of the verbose_name, of only the true fields on one of the classes that inherit the a_lot_of_booleans class and the value of product_name, belonging to specific user. What I"m trying in the views.py is the following: def view_rfps(request): list=product_for_sale.objects.all().filter(U_Id=request.user) for item in list: values=item._meta.fields for value in values: res=item.objects.filter(**{value:'True'}) ##<< lines that fail print(res) the above code fails on res=item.objects.filter(**{value:'True'}) on "Manager isn't accessible via search_for_constructor_rfp instances" The idea later to pass on the res variable to view, however I cannot pass this point. I have several items in list and for every list several boolean fields, that I"m not sure what they names gonna be in a future, so … -
How to coordinate randomly chosen objects in a DRF APIView?
I am building an API for a game and need to select a random game round for a randomly chosen resource. Choosing the random resource works. What I am trying to do now, in order to coordinate players is to filter the game rounds by the resource that has been chosen randomly and then return a random game round. The code below shows what I have tried so far, namely to access the resource for which a game round has been played over the method with the @property decorator. models.py class Gameround(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gamesession = models.ForeignKey(Gamesession, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) objects = models.Manager() def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) def create(self): pass @property def tags(self): tags = self.taggings.values('tag') return tags.values('tag_id', 'tag__name', 'tag__language', 'resource_id') class Tagging(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, related_name='taggings') resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='taggings') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) origin = models.URLField(max_length=256, blank=True, default='') objects = models.Manager() def create(self, tag): tagging = self.create(tag=tag) def __str__(self): return str(self.tag) or '' def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) I am then … -
I want to filter a model but their are many filters and all aren't required django?
In my project, I want to build a filter system and the filter is not by 1 field it is by about 6 fields but every field isn't required but at backend I have to use many queries like if 3 fields are coming: field1 = form.field1 field2 = form.field2 field3 = form.field3 field3 = form.field4 field4 = form.field5 field5 = form.field6 if field1 is None: filter_by_other_field but by doing this method it will make many queries so can u pls help me In this case I want to use less code Thanks -
Django Email alert after User creation
The user must receive a mail when the user was created if the post button was pressed in Django rest framework and below is my code. I'm Creating API for this project ERROR AttributeError at /api/User/ 'User' object has no attribute 'is_active' Request Method: POST Request URL: http://127.0.0.1:8000/api/User/ Django Version: 2.2.12 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'is_active' class User(models.Model): CHOICES= ( ('manager','Manager'), ('hr', 'HR'), ('hr manager','HR Manager'), ('trainee','Trainee') ) firstname = models.CharField(max_length=210) lastname = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) password=models.CharField(max_length=100,default=None) joiningDate=models.DateTimeField(max_length=8) userrole=models.CharField(max_length=20,choices=CHOICES,null=True) def __str__(self): return self.firstname @receiver(post_save, sender=User, dispatch_uid='active') def active(sender, instance, **kwargs): if instance.is_active and User.objects.filter(pk=instance.pk, is_active=True).exists(): subject = 'Active account' mesagge = '%s your account is now active' %(instance.username) from_email = settings.EMAIL_HOST_USER send_mail(subject, mesagge, from_email, [instance.email], fail_silently=True) class Project(models.Model): name = models.CharField(max_length=20) description=models.TextField() type=models.TextField() startDate = models.DateTimeField(max_length=10) endDate=models.DateTimeField(max_length=10) user=models.ManyToManyField(User) def __str__(self): return self.name class Timesheet(models.Model): project=models.ManyToManyField(Project) Submitted_by=models.ForeignKey(default=None,related_name="SubmittedBy",to='User',on_delete=models.CASCADE) status=models.CharField(max_length=200) ApprovedBy=models.ForeignKey(default=None,related_name="ApprovedBy",to='User',on_delete=models.CASCADE) Date=models.DateField() Hours=models.TimeField(null=True) def __str__(self): return self.id class Client(models.Model): clientname=models.CharField(max_length=20) comapny=models.CharField(max_length=200) location=models.CharField(max_length=200) email=models.EmailField(max_length=25,default=None) def __str__(self): return self.clientname -
Dynamic variables in json with Django settings values
I am working with a python library for a certain api service. And in order to connect to their account, they use the json file. This is how the API connection looks like. api = VoximplantAPI('credentials.json') credentials.json { "account_email": "my email", "account_id": "ac_id", "key_id": "key_id", "private_key": "private" } I removed the values. I have a question, how can I add dynamic variables to json so that I can take values from Django settings, for example using Jinja. I have been looking for an answer for several hours, but I have not found an answer. -
How to create 2 roles for the same user in Django
I am creating a job portal system where a user can either be a employee or employer.This is my models.py in account app in django, it is not working. from django.contrib.auth.models import AbstractUser from django.db import models from account.managers import CustomUserManager JOB_TYPE = ( ('M', "Male"), ('F', "Female"), ) ROLE = ( ('employer', "Employer"), ('employee', "Employee"), ) class User(AbstractUser): username = None email = models.EmailField(unique=True, blank=False, error_messages={ 'unique': "A user with that email already exists.", }) role = models.CharField(choices=ROLE, max_length=10) gender = models.CharField(choices=JOB_TYPE, max_length=1) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email def get_full_name(self): return self.first_name+ ' ' + self.last_name objects = CustomUserManager() -
Local variable reference before assignment - Python Django
I am having an issue in calculating a field in Model. Basically what I need to do is to calculate, based on the user HTML input, a certain date and a certain price. The functions are giving me problem are the functions inside the models.py file. The code is as follows: models.py from django.db import models from datetime import datetime as dt from datetime import timedelta # Create your models here. RAMO_POLIZZA = ( ('ITAS DANNI', 'ITAS DANNI'), ('ITAS ELEMENTARI', 'ITAS ELEMENTARI'), ('SARA DANNI', 'SARA DANNI'), ('SARA ELEMENTARI', 'SARA ELEMENTARI'), ) FRAZIONAMENTO = ( ('Annuale', 'Annuale'), ('Semestrale', 'Semestrale'), ('Quadrimestrale', 'Quadrimestrale'), ('Mensile', 'Mensile'), ) class Cliente(models.Model): nome = models.CharField(max_length=50) cognome = models.CharField(max_length=50) note = models.TextField(blank=True, null=True) creata = models.DateTimeField(auto_now_add=True) aggiornata = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Cliente' ordering = ['cognome', ] def __str__(self): return self.nome + ' ' + self.cognome class RamoPolizza(models.Model): nome = models.CharField(max_length=50, choices=RAMO_POLIZZA) creata = models.DateTimeField(auto_now_add=True) aggiornata = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Ramo Polizza' def __str__(self): return self.nome class Frazionamento(models.Model): nome = models.CharField(max_length=50, choices=FRAZIONAMENTO) creata = models.DateTimeField(auto_now_add=True) aggiornata = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Frazionamento' def __str__(self): return self.nome class Polizza(models.Model): cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE) numero_polizza = models.CharField(max_length=100) data_decorrenza = models.DateField() data_scadenza = models.DateField(blank=True, null=True) ramo_polizza = … -
Django import fail
Good day, 10 minutes ago everything worked fine. I changed nothing except running the server again and now I get the error line 2, in <module> from .forms import LoginForm, RegisterForm ImportError: attempted relative import with no known parent package I am in the views.py and want to import forms.py -
Command line isn't working with any Django commands
I am trying to call any django command, but it is just empty row below What kind of problem could it be? -
having trouble getting desired response from django restframework
I am working on an app based on Flutter (frontend), django (backend), mongodb atlas (database). In my app users can add posts, like, or comment on those posts (just like facebook!) in django my models.py has separate tables for Posts, Reacts on Posts (for like button), comments on posts. here is the code for my models.py class PostsComments(models.Model): commentID = models.AutoField(primary_key=True) content = models.TextField() createTime = models.TextField() updateTime = models.TextField() approved = models.BooleanField(default= True, editable= True) userID = models.ForeignKey('Users', on_delete=models.CASCADE, name="userID") postID = models.ForeignKey('Posts', on_delete=models.CASCADE, name="postID") class PostsReacts(models.Model): reactID = models.AutoField(primary_key=True) createTime = models.TextField() updateTime = models.TextField() react = models.BooleanField(default= False, editable= True) userID = models.ForeignKey('Users', on_delete=models.CASCADE, name="userID") postID = models.ForeignKey('Posts', on_delete=models.CASCADE, name="postID") class Posts(models.Model): postID = models.AutoField(primary_key=True) content = models.TextField() createTime = models.TextField() updateTime = models.TextField() approved = models.BooleanField(default= True, editable= True) hasVideo = models.BooleanField(default= False, editable= True) hasImage = models.BooleanField(default= False, editable= True) #images = ListField(models.TextField) #videos = ListField(models.TextField) images = models.TextField() videos = models.TextField() #comments = [PostsComments()] #reacts = [PostsReacts()] customerID = models.ForeignKey('Customers', on_delete=models.CASCADE, name="customerID") def __str__(self): return f"ID: {self.postID}" view.py from django.http.response import HttpResponseRedirect from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.serializers import Serializer #seerializers from .serializers import BookingHistorySerializer, BookingSerializer, CommentsSerializer, CustomerSerializer, ExpertSerializer, PostsSerializer, … -
Ingress routing misses prefix for django redirects
I deployed a Django app in a K8s cluster and have some issues with the routing by Ingress. Ingress config: apiVersion: projectcontour.io/v1 kind: HTTPProxy metadata: name: main namespace: ${namespace} spec: routes: - conditions: - prefix: /my-app services: - name: my-app-backend port: 80 timeoutPolicy: response: 60s pathRewritePolicy: replacePrefix: - replacement: / my-app/urls.py from django.urls import include, path from overview import views app_name = "overview" urlpatterns = [ path("", views.index), path("overview", views.overview) ... ] I have a url like example.com, where the paths are redirected to several K8s services. URL example.com/my-app/ should be resolved to my service "my-app". So far so good, i can see the entry page of my app. But if i start clicking buttons from here, the relative redirects done by Django don't work as expected: A Button click which is expected to navigate me to example.com/my-app/overview, targets to example.com/overview which results in 404 obviously. I would expect a /my-app/ prefix for all redirects in my-app. I'm an Ingress rookie, but i would assume that my-app shouldn't be responsible for this information, as I would have to change two repos when the domain path changes eventually (and i want to avoid routers or hardcoding the url prefixed to /my-app/). … -
ValueError: source code string cannot contain null bytes with django
So, i have been getting this error for a week now, and every time I reopen or resume a django project, then i run a python command like python manage.py runserver i get this unusually error $ python manage.py runserver Traceback (most recent call last): File "C:\kate\manage.py", line 22, in <module> main() File "C:\kate\manage.py", line 11, in main from django.core.management import execute_from_command_line File "C:\Python39\lib\site-packages\django\__init__.py", line 1, in <module> from django.utils.version import get_version ValueError: source code string cannot contain null bytes Meanwhile i saw a solution online that says i should convert it to UTF-8 which i don't know where to change that or convert that since i use pycharm, VS Code and Sublime for my projects -
making a retrieve api for a manytomany field
I am making an API with django rest framework and what it's supposed to do is, it has to return the movies that have a certain genre. And I dont know how to do that. because the film model has a manytomany field called filmGenre and I want to preferably make this api by extending the ModelSerializer class. # Models.py class Genre(models.Model): genreID = models.AutoField(primary_key=True) nameOf = models.CharField(max_length=100, unique=True) details = models.TextField(null=True) class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) filmGenre = models.ManyToManyField(Genre) # Serializers.py class GenreRetrieveSerializer(serializers.ModelSerializer): # TO BE DONE can anyone help me with this problem? -
Python ImproperlyConfigured Error - Django
I am trying to use a Flask application to connect to a Django application using this tutorial https://flask.palletsprojects.com/en/2.0.x/patterns/appdispatch/ that uses application dispatching to connect both applications together. But I am receiving an ImproperlyConfigured error when I try to connect three applications together inside vega_flask_run.py. I have tried looking at other posts such as ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings, django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured, and Set DJANGO_SETTINGS_MODULE as an Environment Variable in Windows permanently and have tried all such solutions accordingly but all my attempts have thus far have failed, for better context, these solutions include setting the DJANGO_SETTINGS_MODULE=veganet.settings using the set command in Windows, changing the PYTHON_PATH to that of my project, and including import utils.file_utils.read_file. Here is the error that I am receiving: Exception has occurred: ImproperlyConfigured Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. File "C:\Users\trevo\OneDrive\Desktop\veganet\profiles\models.py", line 2, in <module> from django.contrib.auth.models import User File "C:\Users\trevo\OneDrive\Desktop\veganet\profiles\forms.py", line 2, in <module> from .models import ExperimentContext, Profile File "C:\Users\trevo\OneDrive\Desktop\veganet\vega_ai\VegaMain.py", line 25, in <module> from profiles.forms import ProfileModelForm, ExperimentModelForm File "C:\Users\trevo\OneDrive\Desktop\veganet\vega_flask_run.py", line 6, … -
TypeError: __call__() got an unexpected keyword argument 'message_id' Dajngo
HTML code <a href="{% url 'front_end:office_message' message_id=message.id %}"><img src="{{message.profile_image.url}}" alt="" /></a> views.py def office_message(request, message_id): message = OfficeStaffMessage.objects.filter(id=message_id) context = {"messages": message} return render(request, "about-us.html", context) urls.py path("messages/<int:message_id>/", office_message, name="office_message"), -
How to update new file in file field in model without deleting the file of other file field
I am having a model which contains 3 file fields along with other field as below. class Feature(models.Model): Migration_TypeId = models.CharField(max_length=50) Version_Id = models.SmallIntegerField(default=0) Object_Type = models.CharField(max_length=50) Feature_Id = models.BigAutoField(primary_key=True) Feature_Name = models.CharField(max_length=100) Source_FeatureDescription = models.TextField() Source_Code = models.TextField() Source_Attachment = models.FileField(upload_to='media/', blank=True, null=True) Conversion_Description = models.TextField() Conversion_Code = models.TextField() Conversion_Attachment = models.FileField(upload_to='media/', blank=True, null=True) Target_FeatureDescription = models.TextField() Target_Expected_Output = models.TextField() Target_ActualCode = models.TextField() Target_Attachment = models.FileField(upload_to='media/', blank=True, null=True) def save(self, *args, **kwargs): self.Version_Id = self.Version_Id + 1 super().save(*args, **kwargs) I am trying to update the record of the model along with the file fields, but when i am trying to update any one of the file field, other file field files are updating as null at the updation time. Kindly let me know, how to not loose the files of other file fields of model. serializers.py class commonSerializer(serializers.ModelSerializer): class Meta: model = Feature fields = '__all__' def create(self, validated_data): abc = Feature.objects.create(**validated_data) return abc def update(self, instance, validated_data): instance.Migration_TypeId = validated_data.get('Migration_TypeId', instance.Migration_TypeId) instance.Object_Type = validated_data.get('Object_Type', instance.Object_Type) instance.Feature_Name = validated_data.get('Feature_Name', instance.Feature_Name) instance.Source_FeatureDescription = validated_data.get('Source_FeatureDescription', instance.Source_FeatureDescription) instance.Source_Code = validated_data.get('Source_Code', instance.Source_Code) instance.Conversion_Description = validated_data.get('Conversion_Description', instance.Conversion_Description) instance.Conversion_Code = validated_data.get('Conversion_Code', instance.Conversion_Code) instance.Target_FeatureDescription = validated_data.get('Target_FeatureDescription', instance.Target_FeatureDescription) instance.Target_Expected_Output = validated_data.get('Target_Expected_Output', instance.Target_Expected_Output) instance.Target_ActualCode = validated_data.get('Target_ActualCode', instance.Target_ActualCode) instance.Source_Attachment … -
let me know what the benefits of a nested serializer are with using it non-seperated apis
Does someone let me know what the benefits of a nested serializer are with using it non-seperated apis? FYI, I'm trying to make 3 nested serializer for create and update methods. like, # models.py class Foo(Model): title = CharField(...) class Bar(Model): foo = ForeignKey("Foo", ...) class Bar2(Model): bar = ForeignKey("Bar", ...) # serializers.py class Bar2WriteSerializer(ModelSerializer): def create(self, validated_date): ... def update(self, instance, validated_date): ... class BarWriteSerializer(ModelSerializer): bar2 = ListField( child=Bar2WriteSerializer(), ... ) def create(self, validated_date): bar2_serializer = self.fields["bar2"].child bar2_serializer.create(self, validated_data): def update(self, instance, validated_date): bar2_serializer = self.fields["bar2"].child bar2_serializer.update(self, instance, validated_data): class FooWriteSerializer(ModelSerializer): bar = ListField( child=BarWriteSerializer(), ... ) def create(self, validated_date): bar_serializer = self.fields["bar"].child bar_serializer.create(self, validated_data): def update(self, instance, validated_date): bar_serializer = self.fields["bar"].child bar_serializer.update(self, instance, validated_data): -
Filtering data from joining table in Django by foreign key
I have model classes that look like: class Wine(models.Model): wine_id = models.IntegerField(blank=True, null=False, primary_key=True) wine_name = models.TextField(blank=True, null=True) wine_type = models.TextField(blank=True, null=True) wine_year = models.IntegerField(blank=True, null=True) wine_alcohol = models.FloatField(blank=True, null=True) wine_country = models.TextField(blank=True, null=True) wine_price = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'wine' class Flavor(models.Model): flavor_id = models.IntegerField(primary_key=False) flavor_name = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'flavor' and one joining table between these two: class FlavorWine(models.Model): flavor_wine_id = models.IntegerField(blank=True, null=False, primary_key=True) flavor_group = models.TextField(blank=True, null=True) flavor_count = models.IntegerField(blank=True, null=True) wine_id = models.ForeignKey('Wine', on_delete=models.DO_NOTHING) flavor_id = models.ForeignKey('Flavor', on_delete=models.DO_NOTHING) class Meta: managed = False db_table = 'flavor_wine' Now, whenever I try to retrieve the data I get errors. I tried exampled used in: Django Filter by Foreign Key and Django: join two tables, but to no success. I tried: wines = Wine.objects.filter(wine_id=wine_id) wine_flavor = FlavorWine.objects.filter(wine_id__in=wines.values('wine_id')) return HttpResponse(serializers.serialize('json', wine_flavor, fields=('wine_id', 'flavor_group', 'flavor_count', 'flavor_id'))) and wine_flavor = serializers.serialize('json', FlavorWine.objects.filter(wine_id_id__gt=wine_id), fields=('wine_id', 'flavor_group', 'flavor_count', 'flavor_id')) and wine_flavor = serializers.serialize('json', FlavorWine.objects.filter(wine_id__flavorwine__exact=wine_id), fields=('wine_id', 'flavor_group', 'flavor_count', 'flavor_id')) And different combinations that were offerred, but none of them work, either it fails when joining tables or it cannot find the required field. I always get the hint: HINT: Perhaps you meant to reference the … -
Not able to export data in the original format using xlwt library(django)
When i am exporting sql query data in excel using xlwt in django, the NULL's are getting converted to blanks and Boolean values to True and False. But i want data to be exported as it is. -
Need a migration when changing from nullbooleanfield to booleanfield?
I'm using an older version of django and I'm trying to upgrade to the latest version of django. While proceeding, I encountered the following error. (fields.E903) NullBooleanField is removed except for support in historical migrations. HINT: Use BooleanField(null=True) instead. Do I need to migrate when changing models.NullBooleanField() to models.BooleanField(null=True)? The table has many columns. Migration is a big burden. Is there any other way to bypass that issue? The DB is using Mysql. -
How to implement soft delete in Django admin?
I have a model and I have implemented soft delete in it. but while deleting from Django admin, it is deleting from the database. How will I bring soft delete in the Django admin also? class modelForm_1(forms.ModelForm): class Meta: model = Model_1 exclude = ("field_1", "field_2", "field_3",) class ModelAdmin_1(admin.ModelAdmin): model = Model_1 list_display = ("jobid", "job_title", "position", "employer") change_form_template = 'admin_panel/detail.html' form = modelForm_1 admin.site.register(Model_1, ModelAdmin_1) -
Django -models Email notification to the User after a change
After registration, Need to send a mail to the user after their account was created in the database. Code is running in the server and the database was connected but the email was not received to the Users. Need help in fixing this issue class User(models.Model): CHOICES= ( ('manager','Manager'), ('hr', 'HR'), ('hr manager','HR Manager'), ('trainee','Trainee') ) firstname = models.CharField(max_length=210) lastname = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) password=models.CharField(max_length=100,default=None) joiningDate=models.DateTimeField(max_length=8) userrole=models.CharField(max_length=20,choices=CHOICES,null=True) def __str__(self): return self.firstname @receiver(pre_save, sender=User, dispatch_uid='active') def active(sender, instance, **kwargs): if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists(): subject = 'Active account' mesagge = '%s your account is now active' %(instance.username) from_email = settings.EMAIL_HOST_USER send_mail(subject, mesagge, from_email, [instance.email], fail_silently=False) -
Django object unique id value in Template
in this modal I have a foreign Key Named stockCode That key has duplicated values and I want to get only one of them(unique). class Product(models.Model): stockCode = models.CharField(primary_key=True,max_length=50,null=False, blank=False) Name = models.CharField(max_length=120,null=False, blank=False) Desc = models.CharField(max_length=120,null=True, blank=True) price1 = models.FloatField(null=False, blank=False) price2 = models.FloatField(null=False, blank=False) publish = models.BooleanField(default=True) def __str__(self): return str(self.stockCode) class Stock(models.Model): id = models.AutoField(primary_key=True) productId = models.ForeignKey(Product,null=False, blank=False,on_delete=models.PROTECT) sizeId = models.ForeignKey(Varyasyon,null=True, blank=True,on_delete=models.PROTECT) colorId = models.ForeignKey(Renk,null=False, blank=False,on_delete=models.PROTECT) grubId = models.ForeignKey(Grub,null=True, blank=True,on_delete=models.PROTECT) stock = models.IntegerField(null=True, blank=True) photo = models.ImageField(null=False, blank=False) def __str__(self): return str(self.grubId) I've tried this: @xframe_options_sameorigin def product(request): stock = Stock.objects.all().values('productId').distinct() return render(request,"product.html",{"products":stock}) but it gives me only the id value ant tried to add .values('productId','productId__Name') it gives me productId__Name unique value and I don't want this. I want only productId to be unique.