Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating the model instances in a particular order
I am working on a django application. I have a process flow in which I have steps and their respective status. I have a model for steps. Below is my flow diagram As soon as the status of step 1 changes to complete, status of all the following steps gets updates. I wrote a post_save signal for the status change of the steps. @receiver(post_save, sender=WorkflowStep) def updateWorkflowStep(sender, instance, created, **kwargs): # updated step 2, step 5, and step 8 statuses Problem: As soon as I will update the status of step "2", the post_save signal will get triggered and update the status of Step "3", followed by step "4". So my. step "5" and step "8" will never get updated as by the time code could update their status, post_save again got triggered because of step "2" status change. How can I make sure that all the three branches gets updated in sequence. Say first step 2, step 3 and step 4 gets updated. Then step 5, 6, and 7. And then step 8, 9, and 10. These are my models: class WorkflowStep(models.Model): name = models.CharField(max_length=200) workflow = models.ForeignKey('Workflow', null=True, blank=True, on_delete=models.CASCADE) step_type = models.ForeignKey('WorkflowStepType', null=True, blank=True, on_delete=models.SET_NULL) allowed_status = … -
access multiple many to many relationships in a django template
class Account(models.Model): accountId = models.CharField(max_length=20, primary_key=True) username = models.CharField(max_length=30) def __str__(self): return self.username class Project(models.Model): projectId = models.CharField(max_length=20, primary_key=True, default=idgen) projectName = models.CharField(max_length=20) projectOwner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") projectSize = models.IntegerField(default=25) projectGuests = models.ManyToManyField(User, related_name="guests") projectAccounts = models.ManyToManyField(Account, "accounts") def __str__(self): return self.projectId In this code, users can have multiple projects and projects can have multiple accounts. Is there any way to pass just the 'user' to the template (or without passing anything since we can get the user using the request) to get all the accounts in all the projects that the user owns? for example, if the user had 2 projects and each project had 2 accounts... is there any way to get the final value 4 in the template just using the user object? -
Django mysql sphinxsearch 'SELECT @@SQL_AUTO_IS_NULL' returns empty error and fails with 'invalid literal for int() with base 10: ''
I have a new setup with DJango and sphinxsearch. When mysql backend initializes connection it calls is_sql_auto_is_null_enabled, which fails with "invalid literal for int() with base 10: ''". Within mysql the query executes as following: mysql> SELECT @@SQL_AUTO_IS_NULL; +--------------------+ | @@sql_auto_is_null | +--------------------+ | | +--------------------+ 1 row in set (0.00 sec) It looks like fetched empty string value is being converted into integer and an exception is thrown. My sphinxsearch version is: Sphinx 2.2.11-id64-release (95ae9a6) I also have a working setup, where the same query returns no rows: mysql> SELECT @@SQL_AUTO_IS_NULL; Query OK, 0 rows affected (0.00 sec) There, sphinxsearch version is: Sphinx 2.2.10-id64-release (2c212e0) Both setups have the same mysqlclient version: mysqlclient==1.3.13 Is there a way to fix this by making SELECT @@SQL_AUTO_IS_NULL return no rows? Or is there another way around this problem? -
Why one url the doesn't require an auth asks for token when placed below a url that requires auth
I obeserved a weird error(maybe) while testing my apis. I have three views handleing the api requests. Two doen't require auth (searchListing, listListing) and on requires auth (retrieveListing). Weirdly if I keep the 'search' below the 'str:slug'' url (urlpatern_1) it says Authentication credentials were not provided. However if I move the search above the 'str:slug'' it works perfectly. urlpatterns_1 = [ path('', views.listListing , name= 'listListing'), path('<str:slug>', views.retrieveListing , name= 'retrieveList'), path('search', views.searchListing , name= 'searchList'), ] urlpatterns_2 = [ path('', views.listListing , name= 'listListing'), path('search', views.searchListing , name= 'searchList'), path('<str:slug>', views.retrieveListing , name= 'retrieveList'), ] But weirdly again the 'listListing' is unaffected by its position. Please explain me why is this happening views.py @api_view(['GET']) def listListing(request): pass @api_view(['GET']) @permission_classes([IsAuthenticated]) def retrieveListing(request, slug): pass @api_view(['GET']) def searchListing(request): pass -
Blog style pages in Django with different content types. Best model structure
I'm relatively new to Django development. I'm building a website where there is a section with tutorials. Lets say for my question a tutorial for Linked List. Since all the tutorials will be basically the same outline, it looks like that templates will do a good job here. What I want to achieve is that I can create new pages (tutorial entries ) in the admin panel, with text fields and so on (kind of like a blog without the relevance of the dates rather then the tutorials content). The challenge for me is, that there is a different amount of different types of data in one tutorial entries. For example one might have the structure: text code text image text code and another one: text image code And if I made a new entry it should get generated with a template as it is done usually in Django. I thought about three ways to meet this dynamic behavior but I see difficulties in each and want to know what the best practice would be. So the structure would be similar to a Blog: class TutorialPost(models.Model): title = models.CharField(max_length=200, unique=True) text_content = models.TextField() code_block = models.TextField() #.... The problem here … -
How to get queryset of objects in many to many field in Django
I have two models Student and Classroom in models.py class Classroom(models.Model): classroom_subject = models.CharField(max_length=100) classroom_code = models.CharField(max_length= 5, default = '00000') teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_name = models.CharField(max_length=100) classes = models.ManyToManyField(Classroom, blank = True) I have three tables in my database student: user_id student_name 1 4 2 4 3 1 classroom: id classroom_subject classroom_code 1 maths 12345 2 english 12345 3 biology 12345 student_classes: id student_id classroom_id 1 4 1 2 4 2 3 1 1 In my views.py class StudentClassesView(ListView): model = Classroom template_name = 'student_classroom_list.html' context_object_name = 'classroom_list' def get_queryset(self): student_id = self.request.user.id return Student.classes.through.objects.filter( ) This code returns all the classrooms in student_classes, but i want it to return all the classrooms where the student_id = self.request.user.id So for example self.request.user.id returns 4, I want all the classrooms in student_classes table where student_id = 4. -
Django: To combine and retrieve rows from different models
1.We have two similar models, and I would like to be able to retrieve these at the same time and sort them by posting date and time, etc. Is it possible? 2.Or should both redundant fields be combined into one model? # 1. class Model1(models.Model): title = ... thumbnail = ... description = ... ... class Model2(models.Model): title = ... image_url = ... product_id = ... reivew = ... # 2. Combine into one model class Model(models.Model) title = ... thumbnail = ... description = ... image_url = ... product_id = ... reivew = ... -
Filter rows from Excel on import with Django Import-Export
I have a new Django web-application (My first one in python) and im using Import-export in the admin section to take an excel file and upload it to my database.the upload works perfectly, but I need to add two features: Is there a way to truncate all the existing data in the application database table before the upload? What is the best way to filter out rows from the Excel file that don't match a condition (if column value of a row != X) I have read the documentation and it seems like for question 2, the only option is to implement an for_delete method. I find it hard to believe this is the best way, but im brand new to python and Django. -
MultipleObjectsReturned at /sport/1/ get() returned more than one Product -- it returned 3
I am sorting products by categories. When I am viewing product's details, the program outputs following error: MultipleObjectsReturned at /default/1/ get() returned more than one Product -- it returned 2! Users/artemiikhristich/PycharmProjects/Eshop-original/store/views.py, line 114, in product_detail product = get_object_or_404(Product, slug=slug) product.html This template is used for viewing product details % extends "store/main.html" %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Tutorial</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet"> <!-- CSS --> <link href="static/css/style.css" rel="stylesheet"> <meta name="robots" content="noindex,follow" /> </head> <body> <main class="container"> <!-- Left Column / Headphones Image --> <!-- Right Column --> <div class="right-column"> <!-- Product Description --> <div class="product-description"> <span></span> <h1>{{product.name}}</h1> <div class="left-column"> <img data-image="black" src="{{ product.imageURL }}"> </div> <p>"{{product.description}}"</p> </div> <!-- Product Configuration --> </div> <!-- Product Pricing --> <div class="product-price"> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <div class="product-configuration"> <a href="#">How to take the measurements</a> </div> </div> </div> </main> <!-- Scripts --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" charset="utf-8"></script> <script src="static/js/script.js" charset="utf-8"></script> </body> </html> {% endblock %} views.py Here I have views for product_detail and category_detail class ProductList(ListView): model = Product def product_detail(request, category_slug, slug): product = get_object_or_404(Product, slug=slug) context = … -
Django back end and Wix front end
I have been working on a project for a while with a developer on apps. He was the coder and did most of the programming. I really just brought the design together and managed everything else. He has now moved on and left me with the code. Or more to the point I have a Django database on a server. Using a postgre db with all of the data in I have built easy websites using things like Wix and wordpress. But I am wondering is there a simple way to migrate the data to my new front end. I can keep the digital ocean droplet or move everything to Wix. If possible just a quick way to do it. The dB contains images, video and text. I am not too fussed right now about making a super duper website. The layout and simplicity to build a Wix site is fine for me. Any ideas. Is this something I can learn? Or should I just get a pro in? -
How to filter a model in case of too complicated database structure?
I want to make a flexible online shop which will allow it's admins to create products and add custom product fields without need to program. I did it, but the final database structure is so complicated that I can't figure out how to filter it. Let's say there are categories with some products attached to it. Each category has only one unique template, the template holds custom fields names and types(int, char). When a product is created, the corresponding template-like fields are written to another model that holds custom fields names and values. So, how to filter the product model considering its custom fields values? To clarify, let's say someone created smartphones category, created template with fields "Brand" and "Screen size", added some smartphones and wants to filter phones with brand="Apple" and screen size > 4.5 inches. I hope that makes sense ^_^ Database structure: class Category(models.Model): name = models.CharField(max_length=63) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=63) price = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(1073741823)], null=True, blank=True) #Template class CategoryTemplate(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255, null=True, blank=True) #Model that holds template custom fields class TemplateField(models.Model): template = models.ForeignKey(CategoryTemplate, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True, blank=True) is_integer = models.BooleanField(blank=True, default=False) #Values … -
Django Admin show same database name when i am using custome user class
I am creating a custom user class and then I am inheritance this user class to another two classes called Customer and Agent. from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.deletion import CASCADE class User(AbstractUser): username = models.CharField(max_length=50, blank=False, null=False, unique=True) email = models.EmailField(('email address'), blank=False, null=False, unique=True) phone_no = models.CharField(max_length=10) isAgent = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'phone_no'] def __str__(self): return self.username class Customer(User): pass class Agent(User): company_name = models.CharField(max_length=150, default="", null=False, blank=False) company_desc = models.CharField(max_length=1000, default="") and then i am register this model class in admin pannel like this... from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Customer, User, Agent, Destination, Trip, Payment admin.site.register(User, UserAdmin) @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): list_display = ['username', 'email'] @admin.register(Agent) class AgentAdmin(admin.ModelAdmin): list_display = ['username', 'email', 'company_name'] NOTE : I am also create a model classes like Destination,Trip,Payment just ignore this class... but in my adminsite http://127.0.0.1:8000/admin/ it is how like this... https://i.stack.imgur.com/D8sX3.png ==> user class name as "User" , Customer class name as "User" as well as Agent class name as "User" soo why my orignal model class name is not occure..? -
Can we convert django application views to django restframework views just like 2to3 python library?
I have a application which is built in django 1.11 with templates. I want to convert that application views in django-rest-framework views, Is there any way we can do it easily or i have to rewrite all django views to django-rest-framework views -
Django DecimalField form field errors not shown in template
I have a silly problem. I have a decimal field with 1 decimal place allowed. I need to manually iterate over the form fields in the template and render them. If in the template I set the input to type="text" and enter a number with two decimal places in the form the error message ("Ensure that there are no more than 1 decimal place.") is displayed in the template. However, when I set the input to type="number" and step="0.1", then the error is not displayed in the template. I can just set it as text, but that means users can enter any characters. I prefer not to do that and have it as a type="number" so that they can only enter digits. Any help would be appreciated. Minimal code: # forms.py class TimeForm(forms.Form): time = forms.DecimalField(max_digits=3, decimal_places=1, label = 'Time') # template <form method="POST"> {% csrf_token %} <div> <input type="number" step="0.1" class="form-control {% if form.time.errors %} is-invalid {% endif %}" name="{{form.time.name}}" id="{{ form.time.id_for_label }}" {% if form.time.value %} value="{{form.time.value}}" {% else %} placeholder="Total Time" {% endif %}> {% if form.time.errors %} {% for error in form.time.errors %} <span class="invalid-feedback">{{error}}</span> {% endfor %} {% endif %} </div> <button type="submit" class="btn btn-primary">Submit</button> … -
ModelChoiceField: Select a valid choice. That is not one of the available choices. Only when answer is wrong
I have a ModelChoice Field that contains 4 vocabulary words' definitions as the options for "what is the definition of __". When you submit the form I get: "Select a valid choice. That choice is not one of the available choices", but this only happens if the answer selected is wrong. Otherwise, it works fine. Forms.py class Questions(forms.Form): choice = forms.ModelChoiceField( widget=forms.RadioSelect, queryset=QuesModel.objects.all(), to_field_name='display', initial = 0 ) Models.py class QuesModel(models.Model): display = models.CharField(max_length=200,null=True) def __str__(self): return self.display views.py deck = Word.objects.all() deck_list = list(Word.objects.all()) cards = deck.filter(xdef = 0) options = [] options.append(cards[0]) random.shuffle(deck_list) options.extend([deck_list[1], deck_list[2], deck_list[3]]) [enter image description here][1]random.shuffle(options) QuesModel.objects.filter(id = 1).update(display = 'adjective') QuesModel.objects.filter(id = 2).update(display = 'noun') QuesModel.objects.filter(id = 3).update(display = 'verb') QuesModel.objects.filter(id = 4).update(display = 'adverb') q = "What part of speech is " + cards[0].name + "?" if request.method == "POST": form = Questions(request.POST) if form.is_valid(): i = form.cleaned_data.get('choice') #is object input = i.display answer = cards[0].pos print(input) print(answer) if (input == answer): print('correct') print('updating: ' + cards[0].name) Word.objects.filter(name = cards[0].name).update(xpos = 1) messages.info(request, answer + " is correct!") return redirect("learn") else: print('wrong') print('updating: ' + cards[0].name) Word.objects.filter(name = cards[0].name).update(xpos = 2) messages.info(request, "The correct answer was: " + answer) return redirect("learn") else: … -
How to save user certain user data into the session?
Scenario: User clicks a link on some forum or ad and he lands on any page of our website. I have to store that landing page url and timestamp when he landed in session. User can then browse the site ( unregistered ) - and then he might decide to sign up - and we want that information stored. The question is how to make it so that the data is written to the session, regardless of the page the user went to -
send message to Django admin from save method
I want to write function in Django models when save object sends a message to Django admin panel I tried to use 'django.contrib.meseseges' but it needs a request and I cant give request to func! what can I do?! def my_func(self) if my_condition == false: messages.warning(request= ??? ,"my message") def save(self,*args,**kwargs): self.my_func() super().save() -
CustomUserModel has no user_doctors
I have a detail page of clinical operation. And i want to make it accessible for only staff's and doctor's related with this operation with ManyToManyField For do this i did class OperationPanelView(LoginRequiredMixin,View): login_url = reverse_lazy("doctor:login") def get(self,request,id): operation = OperationModel.objects.get(id=id) if request.user.user_doctors not in operation.doctor.all(): if DoctorModel.objects.filter(user = request.user).exists(): return redirect("doctor:panel",request.user.id) elif request.user.is_staff == True: return redirect("disease:panel",operation.id) context = { "operation":operation, } return render(request,"operation_detail.html",context) this has worked for if request.user.user_doctors is not related with this operation's doctors then it will redirects the user to their own panel. And also has worked for if request.user.user_doctors is related with operation's doctors then page will open. But didn't worked for if user is staff and gave this error: RelatedObjectDoesNotExist at /disease/panel/1 CustomUserModel has no user_doctors. in line 35: if request.user.user_doctors not in operation.doctor.all(): Then i add this condition: if request.user.user_doctors: but this gave the same error too DoctorModel: class DoctorModel(models.Model): BLOOD_TYPE_CHOICES = [ ("A+","A+"), ("A-","A-"), ("B+","B+"), ("B-","B-"), ("O+","O+"), ("O-","O-"), ("AB+","AB+"), ("AB-","AB-"), ] GENDER_CHOICES = [ ("Male","Male"), ("Female","Female"), ] user = models.OneToOneField("account.CustomUserModel",on_delete=models.CASCADE,null=False,blank=False,related_name="user_doctors") first_name = models.CharField(verbose_name="Ad:",max_length=40,null=False,blank=False) last_name = models.CharField(verbose_name="Soyad:",max_length=60,null=False,blank=False) gender = models.CharField(choices=GENDER_CHOICES,max_length=6) working_field = models.ForeignKey(DoctorField,on_delete=models.SET_NULL,null=True,blank=False,related_name="field_doctors") phonenumber = PhoneNumberField(null=False,blank=True) about = models.TextField(verbose_name="Haqqinda:",null=True,blank=True) is_active = models.BooleanField(default=True) blood_type=models.CharField(choices=BLOOD_TYPE_CHOICES,max_length=10, null=True,blank=False) born_date = models.DateField(null=True,blank=False) OperationModel: class OperationModel(models.Model): name = … -
I says E/Volley: [65] NetworkUtility.shouldRetryException: Unexpected response code 404 for http://10.0.2.2:8000/api/rooms/
**Here I have been trying to post in my data base using volley but it say "E/Volley: [65] NetworkUtility.shouldRetryException: Unexpected response code 404 for http://10.0.2.2:8000/api/rooms/" and bad request 400 in backend, and i have tried everything I can but i can't solve it. Also it shows null pointer in method uploadtodb where i have bolded below. public class HouseOwner extends Fragment { CircleImageView circleImageView; ImageView imageView; private static final int PICK_Image = 1; Button button; Bitmap bitmap; String encodeImage; EditText a, b, c, d, e, f; CheckBox g, h; private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; public HouseOwner() { // Required empty public constructor } public static HouseOwner newInstance(String param1, String param2) { HouseOwner fragment = new HouseOwner(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_house_owner, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); a = view.findViewById(R.id.edtTitle); b = view.findViewById(R.id.edtdescription); c = view.findViewById(R.id.edtEmail); d = view.findViewById(R.id.edtphone); e = view.findViewById(R.id.edtLocation); f = view.findViewById(R.id.edtPrice); g = view.findViewById(R.id.rad1); h … -
django display filefield on tables2 and django_filters
I am trying to display table that includes filefield with filter but it doesn't seem to work. It says filter is not defined and even if I remove filter completely, it says filefield is not right format or something. How do I make this work? I am trying to display table with uploaded file displayed on table(click to download) and filter it by date range(from start date to end date) and subject. model.py class TestModel(models.Model): id = models.AutoField(primary_key=True) date_created = models.DateTimeField('Date Created', auto_now_add=True) subject = models.CharField('Subject', max_length=150, null=True) posted_by = models.CharField('Posted By', max_length=30, null=True) description = models.FileField(upload_to='test/Description/') attachment = models.FileField(upload_to='test/Attachment/') tables.py class TestTable(tables.Table): class Meta: model = TestModel fields = ('date_created', 'subject', 'posted_by', 'description', 'attachment') view.py class TestView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = TestTable paginate_by = 10 model = TestModel template_name = "display/test.html" filterset_class = TestFilter filters.py class TestFilter(django_filters.FilterSet): start_date = DateFilter(name='date_created ',lookup_type=('gt'),) end_date = DateFilter(name='date_created ',lookup_type=('lt')) date_range = DateRangeFilter(name='date_created ') class Meta: model = TestModel fields = { 'subject': ['icontains'] } -
Django aggregation Many To Many into list of dict
It's been hours since I tried to perform this operation but I couldn't figure it out. Let's say I have a Django project with two classes like these: from django.db import models class Person(models.Model): name=models.CharField() address=models.ManyToManyField(to=Address) class Address(models.Model): city=models.CharField() zip=models.IntegerField() So it's just a simple Person having multiple addresses. Then I create some objects: addr1=Address.objects.create(city='first', zip=12345) addr2=Address.objects.create(city='second', zip=34555) addr3=Address.objects.create(city='third', zip=5435) person1=Person.objects.create(name='person_one') person1.address.set([addr1,addr2]) person2=Person.objects.create(name='person_two') person2.address.set([addr1,addr2,addr3]) Now it comes the hard part, I want to make a single query that will return something like that: result = [ { 'name': 'person_one', 'addresses': [ { 'city':'first', 'zip': 12345 }, { 'city': 'second', 'zip': 34555 } ] }, { 'name': 'person_two', 'addresses': [ { 'city':'first', 'zip': 12345 }, { 'city': 'second', 'zip': 34555 }, { 'city': 'third', 'zip': 5435 } ] } ] The best i could get was using ArrayAgg and JSONBAgg operators for Django (I'm on POSTGRESQL BY THE WAY): from django.contrib.postgres.aggregates import JSONBAgg, ArrayAgg result = Person.objects.values( 'name', addresses=JSONBAgg('city') ) But that's not enough, I can't pull a lit of dictionaries out of the query directly as I would like to do, just a list of values or something useless using: addresses=JSONBAgg(('city','zip')) which returns a dictionari with random keys and the … -
Retrieve specific user's profile information
In my web App I'm trying to add the function of clicking on the author of a certain post and being able to see their profile and also the posts said user has created. I've managed to get the post list working just fine but when I try to call specific user data, it gives me the data of the logged in user. Here's how I call the user profile in HTML: <section class="py-5"> <div class="container my-5"> <div class="row justify-content"> <div class="col-lg-6"> <div class="content-section"> <div class="media"> <img class="rounded-circle profile-img" src="{{ user.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ view.kwargs.username }} {{ user.last_name }}</p> <p class="text-secondary">{{ user.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ user.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ user.date_joined }}</p> <p class="text-secondary">Última vez visto: {{ user.last_login }}</p> <p class="mb-0">{{ user.profile.about }}</p> </div> </div> </div> </div> </div> Here is my views: class UserPostListView(ListView): model = Post template_name = 'forum/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') Here is how the problem looks: As you guys can see, that's Yonas1420's profile, but it's only returning the correct username, because the profile picture, the … -
Validation for unique in form
I have model and form like this class Article(models.Model): key = models.CharField(max_length=20,null=False,unique=True) class ArticleForm(forms.ModelForm): class Meta: model = Article key = forms.CharField(required=True) This key is unique in table, so I want to validate in form too. If I put the existing key, it comes to the 1062, "Duplicate entry 'inquiry' for key error in yellow screen However it also doesn't work, forms.CharField(required=True,unique=True) How can I make this validation? -
In Django : How can I multiply two columns and save to another column in update query?
class A(models.Model): revenue = models.FloatField() list_price = models.FloatField() unit_sold = models.FloatField() I have this model which has 1M records in list_price and unit_sold I want to fill revenue column using list_price * unit_sold -
How to check if record exists in django mysql before insert into database
Please pardon me, am still new to djando framework. This error i always get i run it. The view finance_lens_app.views.acct_type didn't return an HttpResponse object. It returned None instead. This is my model class Acct_type(models.Model): Aid=models.AutoField(primary_key=True) acct_type_name=models.CharField(max_length=200) class Meta: db_table="Acct_Type" This is my VIEW. def acct_type(request): if request.method=='POST': request.POST.get('acct_type_name') acct_type_record=Acct_type() acct_type_record.save() messages.success(request, 'Account Type Added Successfully...') return render(request, "admin_opera/acct_type.html") My Interface HTML <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <select name="acct_type_name" id="acct_type_name" class="form-control"> <option value="Assets">Assets</option> <option value="Liabilities">Liabilities</option> <option value="Equities">Equities</option> <option value="Incomes">Incomes</option> <option value="Expenses">Expenses</option> <option value="Expenses2">Expenses2</option> <option value="Expenses3">Expenses3</option> </select> </div> <input class="btn btn-primary btn-lg" type="submit" name="submit" value="Add Account"> </form>