Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Use cookiecutter-django-mysql to initialize the project and execute python manage.py migrate to report an error
everyone. This is my first time asking a question on stackoverflow, please take care~ First I created the project through cookiecutter https://github.com/mabdullahadeel/cookiecutter-django-mysq and chose mysql5.7 as the storage database Second I specified the environment variable export DATABASE_URL=mysql://root:123123123@127.0.0.1:3306/polo_testing_platform export CELERY_BROKER_URL=redis://localhost:6379/0 export USE_DOCKER=No and I made sure my local mysql version is 5.7 mysql version is 5.7 Then I get an error when I execute python manage.py migrate error messages: Operations to perform: Apply all migrations: account, admin, auth, authtoken, contenttypes, django_celery_beat, sessions, sites, socialaccount, users Running migrations: Applying sites.0003_set_site_domain_and_name...Traceback (most recent call last): File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from django_site_id_seq' at line 1") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/polo/all_project/python学习/polo_testing_platform/manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/polo/all_project/python学习/polo_testing_platform/polo_testing_platform/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in … -
Django scaling using Docker
I would like to ask how does Django scale using docker ( including using docker-compose ). For Example, a e-commerce app with 1K actif users to like ~10K visits / day.(Or Should I consider the number of request / second) In the other side, I also want to know how much does Django need (hardware requirements : Number of Core CPU, Ram, Network Traffic ..) for like 10K actif user / day. Many thanks in advance -
Store class instance in mysql
I get the response from the API. Normally, I fetch the data from the response and store it into the mysql It's enough. However, in this case I want to store the response instance itself. Maybe some serializing is necessary though, Generally speaking , is there any way to store the instance itself by python?? -
Django for loop to iterate a dictionary [closed]
enter image description here enter image description here enter image description here I want to display all three records in the table but it is not working... can anyone help me regarding this? -
Django unmanaged postgres view got deleted automatically
I have created a Postgres database view by joining 4 tables. Then created a Django model which is based on this view. It has managed=False It was working fine from a week and today I am seeing the view is missing from database. It has got deleted. Is there any technical reason behind it? -
Django custom display in html of a query
I want to query database and showing in html, but in my database it's an int like 1233405061023 and i want to display in my template like this 12334050XXX23, it's that possible or i have to create another column with the custom formating like i mentioned above and display that column instead of clean one ? -
DRF- Got assertion error when I give Post Request
Error AssertionError: The `.create()` method does not support writable dotted-source fields by default. Write an explicit `.create()` method for serializer `hrm_apps.configuration.serializers.CurrencySerializer`, or set `read_only=True` on dotted-source serializer fields. models.py, class CurrencyMaster(models.Model): code = models.CharField(max_length=3, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) def __str__(self): return self.name class Currency(models.Model): currency_master = models.OneToOneField(CurrencyMaster, on_delete=models.RESTRICT) conversion_rate = models.FloatField(null=False) def __str__(self): return self.currency_master.name views.py, class CurrencyViewSet(viewsets.ModelViewSet): queryset = Currency.objects.all() serializer_class = CurrencySerializer lookup_field = 'id' serializers.py, class CurrencySerializer(serializers.ModelSerializer): currency_master = serializers.CharField(source="currency_master.name") class Meta: model = Currency fields = ['id', 'currency_master', 'conversion_rate'] When i give post request i got assertion error like above, class CurrencySerializer(serializers.ModelSerializer): currency_master = serializers.CharField(source="currency_master.name") class Meta: model = Currency fields = ['id', 'currency_master', 'conversion_rate'] def create(self, validated_data): return Currency.objects.create(**validated_data) def update(self, instance, validated_data): instance.currency_master = validated_data.get('currency_master', instance.currency_master) instance.conversion_rate = validated_data.get('conversion_rate', instance.conversion_rate) return instance I tried above i got this error "ValueError: Cannot assign "{'name': 'ALL - Albania Lek'}": "Currency.currency_master" must be a "CurrencyMaster" instance". How to resolve this??? -
inspectdb unrecognized arguments PackageWeight
Is it possible in Django 1.8 to inspect specific table? When I run (according to this): $ python manage.py inspectdb --database=default PackageWeight It writes: usage: manage.py inspectdb [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--database DATABASE] manage.py inspectdb: error: unrecognized arguments: PackageWeight -
Want to save image URL in Python Django
This is my model class MenuOptions(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) This is my form class MenuOptionsForm(forms.ModelForm): class Meta: model = MenuOptions fields = ['name', 'description'] And this is my view if request.method == 'POST': form = MenuOptionsForm(request.POST) if form.is_valid(): form.save() return redirect('menu-options') else: form = MenuOptionsForm() I want to have the image field in the forms only so that I can upload the image on S3/Google storage I know how to do that and after uploading the image to the storage I want to save only the image_url to the DB, not the image. So it can not be an image_filed in the Django model it has to be a string. -
sqlanydb.OperationalError column not found
When I run python manage.py inspectdb it ends with error messsage Traceback (most recent call last): File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/base.py", line 98, in execute ret = self.cursor.execute(trace(query), trace(args)) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 796, in execute self.executemany(operation, [parameters]) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 767, in executemany bind_count = self.api.sqlany_num_params(self.stmt) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 701, in __stmt_get self.handleerror(*self.parent.error()) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 695, in handleerror eh(self.parent, self, errorclass, errorvalue, sqlcode) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlanydb.py", line 379, in standardErrorHandler raise errorclass(errorvalue,sqlcode) sqlanydb.OperationalError: (b"Column 'a' not found", -143) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/commands/inspectdb.py", line 25, in handle for line in self.handle_inspection(options): File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/core/management/commands/inspectdb.py", line 64, in handle_inspection relations = connection.introspection.get_relations(cursor, table_name) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 62, in get_relations my_field_dict = self._name_to_index(cursor, table_name) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 55, in _name_to_index return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))]) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/sqlany_django/introspection.py", line 46, in get_table_description cursor.execute("SELECT FIRST * FROM %s" % File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/pd/sybase_project/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 62, in … -
rendering form in html django
I have this app and its working but i'm confused whether to use form method or POST.get method. with form i'm getting so many challenges like rendering form on custom html suppose i have this change password screen, for that i need to create form then use this on html template and with custom html it gets more complicated to use form fields. forms.py: class ChangePasswordForm(PasswordChangeForm): old_password = forms.CharField(label="Old Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) new_password1 = forms.CharField(label="New Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) new_password2 = forms.CharField(label="Confirm Password", strip=False, widget=forms.PasswordInput( attrs={'class': 'formField password-genrInput'})) class Meta: model = User fields = ('old_password', 'new_password1', 'new_password2') views.py: # Password Change View def changePassword(request): if request.method == 'POST': form = ChangePasswordForm(request.user, request.POST) print(form) if form.is_valid(): print("form valid") user = form.save() update_session_auth_hash(request, user) messages.success(request, "Password Changed Successfully") return redirect('changePassword') else: messages.error(request, "Something Went Wrong, Please Try Again ") return redirect('changePassword') else: form = ChangePasswordForm(request.user) return render(request, 'admin/user_auth/change_password.html', { 'form': form }) html: {% extends "admin/layouts/default.html" %} {% load static %} {% block content%} <div class="row"> <div class="col"> <div class="titleBlock"> <a href="{{request.META.HTTP_REFERER|escape}}"><h1><i class="fas fa-chevron-circle-left mr-3"></i>Back</h1></a> </div> <div class="card"> {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" … -
Django distinct query is still returning duplicates
I have a shopping list which I can fill by adding all the ingredients from a recipe. I want to query Shopping to see get all unique recipes present in a Shopping List, however my distinct query is returning duplicates? #query ShoppingItems.objects.filter(user=account, shoppingList=shoppingList, recipe__isnull=False).values('recipe').distinct() #returns > <ShoppingItemsQuerySet [{'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}]> #shopping/models.py class ShoppingLists(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) class ShoppingItems(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shoppingList = models.ForeignKey(ShoppingLists, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=220, blank=True, null=True) # chicken # recipes.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) # grilled chicken pasta -
How to join like sql in django models
I have these three models which has not contained foreign key class SchoolReg(models.Model): # TODO: Define fields here user = models.ForeignKey('front.User', on_delete= models.CASCADE) fullname = models.CharField(max_length= 100) dob = models.CharField(max_length= 50) class CandidateCode(models.Model): candidateCode = models.IntegerField() regId = models.IntegerField() regCategory = models.CharField(max_length=20) class Sec1(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, blank= True, null = True) centreName = models.CharField(max_length= 50, blank= True, null = True) compRegNo = models.CharField(max_length= 50, blank= True, null = Tru now I want join these models and make a queryset of student like this SELECT * from school_reg s LEFT JOIN sec1 c on s.user_id = c.user_id LEFT JOIN candidate_code cc on cc.reg_id = s.school_id WHERE c.center_name = "centreName" -
Partially Shifting to react from Django
Basically I have a project in Django, in all it has 7 apps. I want to shift one of them in react. Say app 'Student' is the one which I want in React. I want to know if its possible to do so, if yes then how? Here is what I tried, I created a react project and using npm run build command I got a build of that react project. Now for base url of Student i rendered template which was in react build folder. Something like this. urls.py urlpatterns = [ ... ... path('student/', views.Student, name='student'), .... ] views.py def Student(request): return render(request, 'build/index.html') Where index.html is the file present in build folder. Using this approach i was able to render the react template but the other url routes were not working. Please let me know what's wrong in this approach, if this approach is wrong then do suggest another approach. -
How can i make my python with django website be used my many users? for now it only logs in one user at a time
Developed python website with django but i have a challenge, whenever i'm logged in and another user tries to log in he/she is taken to my dashboard(currently logged in user) instead of being asked to log in to his/her account. So my website is like only one person can use at a time, have tried using decorators (@login required) but still facing same problem. What i'm i lacking kindly -
Copy current form data into new form using django
I have two views, PostCreateView and PostUpdateView. They both route through the same html template, post_form.html. I want to create a Copy button that only appears if I am accessing a record through PostUpdateView. Pressing the Copy button will create a new record pre-filled with all the data from record that I was just on. PostCreateView code: class PostCreateView(LoginRequiredMixin, FormView): template_name = 'trucking/post_form.html' form_class = RecordForm def form_valid(self, form): form.instance.author = self.request.user obj = form.save(commit=False) obj.save() messages.success(self.request, f'RECORD: {obj.container_no} was saved') return super().form_valid(form) def get_success_url(self): if self.request.POST.get('Save_Exit'): return reverse('close') elif self.request.POST.get('Save'): return reverse('post-create') else: return reverse('database') PostUpdateView code: class PostUpdateView(LoginRequiredMixin, UpdateView): form_class = RecordForm model = Post def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) history = Post.objects.filter(id = self.object.id).first().history.all().reverse() data['history'] = get_status_changes(history) return data # checks to make sure the user is logged in def form_valid(self, form): form.instance.author = self.request.user obj = form.save(commit=False) messages.success(self.request, f'RECORD: {obj.container_no} was updated') return super().form_valid(form) def get_success_url(self): if self.request.POST.get('Save_Exit'): return reverse('close') # return render(self.request, 'trucking/email_close.html') elif self.request.POST.get('Save'): return reverse('post-update', kwargs={'pk': self.object.id}) else: return reverse('database') Based on this post I tried creating a view like so: def copy(request): post = Post.objects.get(pk = request.users.post.id) my_form = RecordForm(instance = post) return render(request, 'trucking/post_form.html', {'form': my_form}) However, I get an … -
How to filter in django to get each date latest record
Example Record Table id value created_datetime 1 10 2022-01-18 10:00:00 2 11 2022-01-18 10:15:00 3 8 2022-01-18 15:15:00 4 25 2022-01-19 09:00:00 5 16 2022-01-19 12:00:00 6 9 2022-01-20 11:00:00 I want to filter this table 'Record Table' as getting each date latest value.For Example there are three dates 2022-01-18,2022-01-19,2022-01-20 in which latest value of these dates are as follows Latest value of each dates are (Result that iam looking to get) id value created_datetime 3 8 2022-01-18 15:15:00 5 16 2022-01-19 12:00:00 6 9 2022-01-20 11:00:00 So how to filter to recieve results as the above mentioned table