Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Crispy Forms two columns in view.py
I have a form in my views.py with fields I have created in models.py. I would like to put 2 fields, 'subject' and 'rn_number' next to each other, like two columns in 1 row. How can I do that? It would be great if I could do it in my 'class PostCreateView'. I use crispy_forms. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content_don', 'subject', 'rn_number'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Django ORM, filter data from 3 different table
there are 3 models, how to form a request to retrieve all LocationCompany with a specific city or sector, + DomainService domain + Service service_type, name name = models.CharField(max_length=20, blank=True, null=True) service_type = models.ForeignKey(Service_type, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=0) slug = models.SlugField(max_length=30) class DomainService(models.Model): domain = models.CharField(max_length=30) sercices = models.ManyToManyField(Service, blank=True) title = models.CharField(max_length=200, blank=True) short_description = models.CharField(max_length=500, blank=True) long_description = models.CharField(max_length=1000, blank=True) specialization = models.ForeignKey(SpecializationService, on_delete=models.SET_NULL, blank=True, null=True) slug = models.SlugField(max_length=30) class LocationCompany(models.Model): company = models.ForeignKey(MyUser, on_delete=models.CASCADE, blank=True, null=True) doctors = models.ManyToManyField(MyUser, blank=True, related_name='company_doctors') domain = models.ManyToManyField(DomainService, blank=True) city = models.CharField(max_length=30) sector = models.CharField(max_length=30, blank=True, null=True) street = models.CharField(max_length=30, blank=True, null=True) google_maps_link = models.CharField(max_length=500, blank=True, null=True) slug = models.SlugField(max_length=30) slug_sector = models.SlugField(max_length=30)``` -
How do i update an array of objects inside an array
res[question.question_id]["question_parts"].append( { "part_desc": question.part_desc, "part_guided_answer": [ { "part_answer_id": question.part_answer_id, "part_model_ans": question.part_model_ans, "part_answer_mark": question.part_answer_mark, } ], "part_total_marks": question.part_total_marks, } ) @require_http_methods(["POST"]) @login_required def create_part_question(request): req = json.loads(request.body) description = req["description"] question_parts = req["question_parts"] part_guided_answers=req["part_guided_answer"] question, created = models.Questions.objects.get_or_create( description=description, ) for question_part in question_parts: part , created = models.QuestionsPart.objects.get_or_create( question_id=question, part_desc=question_part["part_desc"], part_total_marks=question_part["part_total_marks"], ) for question_part in question_parts: for part_guided_answer in part_guided_answers: models.PartModelAnswer.objects.create( question_id=question, part_id = part, answer_mark= question_part[part_guided_answer["answer_mark"]], model_ans= question_part[part_guided_answer["answer_mark"]], ) return success({"res": True}) how do i add an array of objects inside the array of objects so what i am trying to show here is that in one question part there can be multiple guided answers so what im trying to do is to add add mulitple guided answers into one question part however so far only the part_desc and the part_total_marks has been added as well as the description, the part_guided_answer has not been added, is there a solution or a better way to do this -
DRF Parse array of objects in form data with images
What is the best possible way to parse nested array objects along with images in drf? I am passing data from React js application -
django-modeltranslation seems to be breaking admin search_fields
I am using django-modeltranslation for a few attributes on some of my models & it seems to be breaking the Django admin search (and therefore also breaking autocomplete_fields on other objects). For example, if I have translated attributes in search_fields: search_fields = ("display_id", "name",) I get the error: "Related Field got invalid lookup: icontains" But if I remove the translated field to just: search_fields = ("display_id",) It works fine. This is using TranslationAdmin from modeltranslation.admin which per the docs "does some funky patching on all your models registered for translation" so I don't know what I am forgetting. -
How do i start the server in django?
When I type manage.py runserver in the shell, there only opens PyCharm, but I need to start the server of course. Why is this happening? -
Django mysql database display data from more than one table in a for loop in template problem
I have a old league web site php script with mysql database from 2006. This script not running depends to old php and mysql versions. Thats why I tried to get data from mysql database using django but I have a problem with match listing page. At database there is a table for league matches. I can fetch data and listing from using django template system like this : models.py class LeagueMatch(models.Model): objects = None idm = models.AutoField(primary_key=True) league = models.IntegerField() ids = models.PositiveIntegerField() judge = models.PositiveIntegerField() date = models.IntegerField() idg = models.PositiveIntegerField(blank=True, null=True) pos = models.IntegerField(blank=True, null=True) rnd = models.PositiveIntegerField(blank=True, null=True) idc1 = models.IntegerField() idc2 = models.IntegerField() type = models.CharField(max_length=20, blank=True, null=True) idpt = models.PositiveSmallIntegerField() points1 = models.IntegerField() points2 = models.IntegerField() frags1 = models.SmallIntegerField() frags2 = models.SmallIntegerField() win1 = models.PositiveIntegerField() draw = models.PositiveIntegerField() win2 = models.PositiveIntegerField() maps = models.CharField(max_length=70) scores = models.CharField(max_length=70) descr = models.TextField() server = models.CharField(max_length=30) views.py def all_matches(request): match_list = LeagueMatch.objects.all() return render(request, 'home_match.html', {'match_list': match_list}) {% for match in match_list reversed %} {% if match.league == 1 %} <div class="card" > <div class="card-body"> <h5 class="card-title"><a href="{% url 'match-detail' match.pk %}"> Match No {{ match.idm }} - Team A ({{ match.idc1 }}) vs Team B ({{ … -
Django: Toggle active users
here in this project, i want to show the active bar when admin is logged in and show blue color and when any other user is logged in, i want to show the active bar on it and others on red color when the users are not active. This is my html <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap" id="rooms"> <thead> <tr> <th>SN</th> <th>Users</th> <th>Email</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{forloop.counter}}</td> <td>{{user.username }}</td> <td>{{user.email}}</td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> <td> <span ><a class="btn btn-info mr-2" href="{% url 'dashboard:passwordreset' %}" ><i class="fa fa-edit m-1" aria-hidden="true" ></i>Reset Password</a ></span> </td> </tr> {% endfor %} </tbody> </table> </div> </div> Here I want to show green when admin is logged in and other active when other user is logged in -
DRF - filtering / customizing options in PUT request
I already tried to find some answers (#1) - with very little success. I want to filter the items the DRF api page returns in the PUT options: lets assume a simple model: class Product(models.Model): name = models.CharField(max_length = 10, default = '') user = models.ForeignKey(User, on_delete = models.CASCADE) class Price(models.Model): amt = models.PositiveIntegerField(default = 0) product = models.ForeignKey(Product, on_delete = models.CASCADE) so every product is linked to a user in the following way: Product | User ---------------- four | user2 three | user1 two | admin one | admin If I now define a ViewSet: class PriceViewSet(viewsets.ViewSet): serializer_class = PriceSerializer http_method_names = ['get', 'put', 'head'] def get_queryset(self): prods = Product.objects.filter(user = self.request.user) return Price.objects.filter(product__in = prods) def list(self, request): results = PriceSerializer(data = self.get_queryset(), many = True) results.is_valid() return Response(data = results.data) def put(self, request): prod = Product.objects.get(id = request.data["product"]) price = Price.objects.get(product = prod) price.amt = request.data["amt"] price.save() return Response(data = "OK") I see the following result (logged in as admin): Why is the user able to even see product three & four (not owned by admin, not in the get_queryset)? How can I filter them for the PUT dropdown? PriceSerializer for completeness sake: class PriceSerializer(serializers.ModelSerializer): class Meta: … -
Django: How to get most recent object from different model?
I m trying to display following output in which Cylinder, Issue & Return are different model, the view I m expecting is cylinder table, where only recently created entries of issue and return is appearing , For example : cylinderId=100 having two entries in issue table and return table but in cylinder table only the recently created is appearing which is :- cyId | createdAt | issuedDate | username | ReturnDate 100 | 5may,13:00| 6may,14:00 | anyone | 7may,15:00 Here is the view i m expecting:- for this result what should i do? Help please :) -
Passing parameter to form action in django?
Template : <form action="/wiki/{{ title }}/" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> And,views : def TitlePage(request, title): if request.method == "POST": title = request.POST.get('q') return render(request, "encyclopedia/titlepage.html", { "title" : title, "getentry": util.get_entry(title) }) URL : path("<str:title>/", views.TitlePage, name='titlepage') But when we submit the form, {{ title }} is not translated and url directs to /wiki// Are parameters not allowed in form actions? If its allowed then why is it not working here? Thanks. -
Error while implementing django tutorial - QuerySet is empty
Can someone explain how to manually enter data in "Choice" table? I am following the django tutorial and my QuerySet is empty like yugal sinha has mentioned here: A solution without an explanation How can I fix this issue? Thank you in advance -
Django static css wont Load
using {%static '' %} wont' work enter image description here already use + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) load template settingenter image description here -
Application error when I push django to heroku
I dont know why but please help me ASAP my setting.py import os.path from pathlib import Path import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-wtp-^w-z1w6h@(@ia85ookdojv2e^y5%4zg6sq!kzx0w@vbu1d' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'DPMweb', 'ckeditor', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'DPM.urls' TEMPLATES_DIR = os.path.join(BASE_DIR, 'DPMweb', 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DPM.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': 'localhost', 'PORT': '', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = … -
How to show fields of inherited model in django?
class BaseModel(models.Model): # base class should subclass 'django.db.models.Model' creation_date = models.DateTimeField(..) # define the common field1 class Meta: abstract=True # Set this model as Abstract Inherit this Base class in models After creating the abstract base class BaseModel, I inherited this class in my models. class MyModel1(BaseModel): # inherit the base model class # define other non-common fields here ... After creating an object of class 'MyModel1', I want the 'creation_date' field to be shown in admin interface. So that I can see the datetime when an object of class 'MyModel1' is created. -
how to overwrite save method in django model form
i'm trying to overwrite save method in my forms.py ,i have to prevent from creating duplicated objects , and if the object exists only update some fields class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() for example if i entered this data before : item = XYZ , quantity = 100 i want to prevent from creating another XYZ item , i want to just update the quantity , for example i'll enter this data item = XYZ , quantity = 200 i try to prevent from creating this duplicate data , i just try to update the quantity previous quantity + new quantity 100 + 200 = 300 i must update the quantity to 300 for that purpose i overwrite save() in my forms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['item','quantity'] def save(self,*args,**kwargs): if self.instance.item is None: #i also tried this if not self.instance.item return super().save(*args,**kwargs) else: Item.objects.filter(item__name=self.instance.item).update( quantity=F('quantity') + self.instance.quantity) my views.py def createNewProduct(request): form = ItemForm() if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() return render(request,'temp/add_item.html',{'form':form}) but it only update if it exists if not exists it doesn't create any new object , iexpect to create new object if it didn't exists … -
Using Protocols in django models raises metaclass conflict error
Let's say I have PEP-544 protocol called Summable : class Summable(Protocol): total_amount: Decimal And I have model Item that implements the Protocol class Item(Summable, models.Model): discount = models.DecimalField( decimal_places=2, validators=[MaxValueValidator(1)], default=Decimal('0.00'), max_digits=10 ) price = models.DecimalField( decimal_places=4, validators=[MinValueValidator(0)], max_digits=10 ) @property def total_amount(self): return sel.price - self.price * self.discount class Meta: ordering = ['id'] I get: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases The same happens even if I extend Item's Meta from Summable.Meta and models.Model.Meta as well. I am using python 3.9 Any ideas? -
I am trying to supply data to a serializer related filed but it throws validation error
I am trying to supply data to serializer related field but it keeps throwing a validation error which says the field is required even when I supply a value for it through postman. I honestly don't know what I am doing wrong. Here's are my serializer; class ProjectFileSerializer(serializers.ModelSerializers): class Meta: model = ProjectFile fields = ['project', 'file'] class ProjectSerializer(serializers.ModelSerializer): project_file = ProjectFileSerializer(write_only=True, many=True) class Meta: model = Project fields = ['title', 'category', 'budget', 'project_file'] -
filter changelist records based on model's field
I have a model that contains the following fields: I added two button in changelist page and want to filter the list based on "active" field by clicking each of buttons , but i don't know how do that. please help me, thankes -
Django too slow only for post request
MY Django app runs perfectly in local machine. But when I uploaded it to Heroku, Digital Ocean and AWS differently. First worked in digital ocean but now doesn't work in any of these platform. Get requests are too fast but post request are timed out. Is there any known problem like this. -
Migrate two different models from two different Django applications
Hi guys so i have a Django project with two application named, shopper, parcel, each of this app have one model also named Parcel and Shopper. there is a one-to-many relationship between the 2 models. the problem is i want to migrate the two models, if I was just one i could have gone with the normal way of migrating a model. This is what i have tried python manage.py makemigrations parcel python manage.py migrate the problem with the first one is it does not take the other models in the shopper app into consideration and that is not what i want. python manage.py makemigrations parcel python manage.py migrate python manage.py makemigrations shopper python manage.py migrate this was my second solution, the commands end up creating migration of each model but still i don't think that is the right thing to do. Any help in the right direction please -
Django Form Javascript read Boolean field
In my models.py I have urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje") And I wish to run a javascript function to change a text field depending on 'True' or 'False' on that Boolean field. Problem is, I can't get the value. When I use 'document.getElementById('id_urgency').value;' I always get 'on', no matter of clickbox check. Why is that? I guess I'm reading the value wrong? Or? <script type="text/javascript"> function makeReadOnly() { var a = document.getElementById('id_urgency').value; console.log(a); if (document.getElementById('id_urgency').value == 'True'){ document.getElementById('id_date_days').readOnly = true; }else if (document.getElementById('id_urgency').value == 'False'){ document.getElementById('id_date_days').readOnly = false; } } document.getElementById('id_urgency').addEventListener('change', makeReadOnly); This is a part of django form. If I go to 'inspect' on that page, that Checkbox doesn't even have value, why is that? 'input type="checkbox" name="urgency" class="checkboxinput form-check-input" id="id_urgency"' -
Count the number of customers in view in Django rest Framework
I have a multi-vendor eCommerce website, wherein seller dashboard I have to count the number of customers that has purchased that merchant product. I have tried somehow , but it is not correct. I have written my logic in my view which is as follows: class DashboardView(ListAPIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): count_1 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk']).count() count_2 = Token.objects.filter(user__is_customer=True).count() # Having problem in this count_9 count_9 = Order.objects.annotate(abc=Count('user')).filter(order_items__item__merchant=self.kwargs['pk']).count() return Response( {'active_users_now': count_2, 'total_customers': count_9, 'total_orders': count_1, }, status=status.HTTP_200_OK) My models: class Order(models.Model): ............... user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) class OrderItem(models.Model): ...................#other fields order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) Class Product(models.Model): ............ merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) I have two users model which are customers and sellers. I actually need to find out the number of customers which have purchased the products of a particular seller. Seller and Customer are one to one related with my CustomUser model: class Seller(models.Model): ................ seller = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) class Customer(models.Model): ............... customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) I just need to write the correct SQL join to determine the counts. Also 2nd question is: I need to write an api to see all the customers with details who … -
Using DjangoRestAPIKey while testing
I'm struggling with test my views with HasAPIKey and IsAuthenticated permission classes/ I've tried to create it in setUp function and in test function but with no effect.After passing it in header I'm still getting 403 error. The only change in settings.py is that line API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY" In test Class I'm inheriting from APITestCase views.py @api_view(['POST']) @permission_classes([HasAPIKey&IsAuthenticated]) def message_create(request): serializer = MessagesSerializer(data=request.data) if serializer.is_valid(): message_text = serializer.data.get('text') new_message = Message.objects.create(user=request.user, text=message_text) return Response(MessagesSerializer(new_message).data, status=status.HTTP_200_OK) tests.py def setUp(self): self.user1 = User.objects.create_user(username='Bob133', password='Pas$w0rd') self.user2 = User.objects.create_user(username='Katy_eleven', password='HardPassword23') self.message1 = Message.objects.create(user=self.user1, text="Example text message number 1") self.message2 = Message.objects.create(user=self.user1, text="Example text message number 2") self.message3 = Message.objects.create(user=self.user1, text="Example text message number 3") self.message4 = Message.objects.create(user=self.user2, text="Example text message number 4") def test_create_message_authorized(self): url = reverse('message_create') self.client.login(username='Bob133', password='Pas$w0rd') self.api_key = APIKey.objects.create_key(name='test_key') data = {"text": "completly new message"} response = self.client.post(url, data, content_type='application/json', **{'X-Api-Key':self.api_key[1]}) self.assertEqual(response.status_code, status.HTTP_200_OK) -
How to get request Object value in Django
I want get member object value 1.models.py enter image description here 2.views.py enter image description here 3.Log enter image description here