Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to initialize a Django ModelChoiceField from a view?
I have the following model relationship where a task is associated to an objective and an objective is associated to a User. I created a Django form that displays all the objectives that are associated to a User. class DropDownMenuSelectedObjectivesForm(forms.Form): def __init__(self, *args, **kwargs): user_id = kwargs.pop('id') super(DropDownMenuSelectedObjectivesForm, self).__init__(*args, **kwargs) self.fields['objective'] = forms.ModelChoiceField(queryset = Objective.objects.values_list('objective',flat=True) .filter(accounts=User.objects.get(id=user_id), status='In Progress'), empty_label=None) When I open my views.py I am able to see all the objectives from the User but I would like that the Django form dropdown menu could be initialized with the current objective that is associated with a task. So far, I have tried the following to initialize the dropdown menu but I've got no success. # views.py def update_task(request, id): '''Update a task''' task = Task.objects.get(pk=id) # get the task id from the db associated_task_objective = task.objective.values('objective')[0] form = TaskModelForm(request.POST or None, instance=task) # Attempt 1 to initialize the ModelChoiceField objective = DropDownMenuSelectedObjectiveForm(id = request.user.id, initial = { 'objective': associated_task_objective}) if request.method == "GET": template_name = 'task/formTask.html' return render(request, template_name, {'form': form, 'objective':objective}) # forms.py class DropDownMenuSelectedGoalsForm(forms.Form): def __init__(self, *args, **kwargs): user_id = kwargs.pop('id') super(DropDownMenuSelectedGoalsForm, self).__init__(*args, **kwargs) # Attempt 2 to initialize the ModelChoiceField self.fields['objective'] = forms.ModelChoiceField(queryset = Objective.objects.values_list('objective',flat=True) .filter(accounts=User.objects.get(id=user_id), … -
Creating a guest User
I want to create a guest user that can only see the content on my website, but cannot post/upload anything. Also the guest does not need to log in. Can anyone point me in the right direction? Any reading material or suggestions would help. Thanks -
How can I get .values() dictionary of a raw query in Django?
I have a query like this: ArchivedStory.objects.raw('SELECT m1.id, m1.archivedEvent_id, m1.media, m1.date FROM app_archivedstory m1 LEFT JOIN app_archivedstory m2 ON (m1.archivedEvent_id = m2.archivedEvent_id AND m1.id > m2.id) WHERE m2.id IS NULL order by date desc') How can I get a list of dictionaries from this query without iteration? Postpending .values() the query yeilds error: 'RawQuerySet' object has no attribute 'values' -
Queryset foreign key models
I have two models below which one of the models inherits a foreign key from the model class Services(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete = models.SET_NULL) service = models.ForeignKey(Service, null=True, on_delete = models.SET_NULL) I want to get the value of the total value of orders per service (per instance) So for example if the id = 1 of service has made orders of £10, £33, etc. I would like to get the total value of that of that service based on how many orders it has been made. So far I have made an queryset below Order.objects.all().values_list('service__price') Which provides me the list of prices, but I would like the total per instance of service. How would one achieve this? -
encode url to base64
I would like to somehow encode the link to the post in base64 slug:slug. Preferably without interfering with the database, and on top of SlugField, if possible. class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(null=False, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'slug': self.slug }) urlpatterns = [ path('post/<slug:slug>', post, name='post-detail'), ] def post(request, slug): post = get_object_or_404(Post, slug=slug) context = { 'post': post } return render(request, 'post.html', context) I tried this, but it didn't help 'slug': base64.b64encode(self.slug) -
Trouble deploying django app to azure web app
I have never deployed a django project to a web app. I usually just build them for fun using localhost. However, I now have one I am trying to deploy to an Azure Web App but keep hitting a brick wall. The deployments within Azure are all successful, but when I visit the app domain I still only see the basic page "Hey, Python developers!" I have read through some existing documentation and made sure to include a web.config file as well as using a wsgi.py file. Additionally, I have updated my settings.py file to include the appropriate ALLOWED_HOSTS. Below is my django folder structure: |.venv |naviwebsite |accounts |naviwebsite |settings.py |wsgi.py |manage.py |requirements.txt |web.config Additionally, below is my web.config file: <configuration> <appSettings> <add key="WSGI_HANDLER" value="naviwebsite.wsgi.application"/> <add key="PYTHONPATH" value="D:\home\site\wwwroot"/> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.webServer> <handlers> <add name="PythonHandler" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python377x64\python.exe|D:\home\python377x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> The views and forms that make up my django app are all located within the accounts folder. Has … -
drf-yasg - manual_parameter not having same format as automated ones
I am using the following manual parameter for a "def put" as I need to send it as an additional query parameter. I am using GenericAPIView for the view class. However when I go to the swagger, it does not have the same formatting as the automated fields it detects: Can somneone point me in the right direction of what I may be missing here? Thanks -
TypeError: SET_NULL() missing 4 required positional arguments: 'collector', 'field', 'sub_objs', and 'using'
How do i solve the above error which shows up not during the makemigrations but during migrate in Django. class Comment(models.Model): #comment_id=models.IntegerField(primary_key=True) name=models.CharField(max_length=100, default="No Comment Added") comment_created=models.DateTimeField(auto_now_add=True) task=models.ForeignKey(task_check, on_delete=models.SET_NULL, null=True ) task_records=models.ForeignKey(task_check_Records, on_delete=models.CASCADE, null=True, default=models.SET_NULL) def __str__(self): return self.name -
Django docker: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
I am new to docker and postgres and was following book 'Django for professionals' from William S. Vincent to learn this. I was trying to connect to postgresql with docker containers. What I did: 1> Written Docker file: # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ 2> Written docker-compose.yml file: version: "3.7" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 3> Changed settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db',docker-compose up -d --build 'PORT': 5432 } } 4> installed psycopg2 docker-compose exec web pipenv install psycopg2-binary==2.8.3 5> Run docker-compose to rebuild the image: docker-compose up -d --build Which throws an error when i check the docker-compose logs as: Attaching to postgresql_web_1, postgresql_db_1 web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | Exception in thread django-main-thread: web_1 | … -
Django Shopping Cart
I'm trying to understand the code below that adds products inside a shopping cart. The code has been extracted from the Django by Example 3 book: def add(self, product, quantity=1, override_quantity=False): # Add a product to the cart or update its quantity product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): # Iterate over the items in the cart and get the products from the database product_ids = self.cart.keys() # Get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item The consumer's products are listed in a session variable. The 'add' function allow the user to insert more products in a dict python. Keys are the "product's ID" and values are "quantity" and "price". Doubts: 1. If the products are listed inside the dict session, why do I need to query again the products from the database as the iter function does? Wouldn't it be easier just to query inside the session variable? 2. The cart … -
add prefix to id in template if flag is set in django
My database was something like this : | id | customer_account | -few more fields - | is_renewed | | 25 | asd111 | - some values - | 0 | | 26 | asd222 | - some values - | 1 | | 27 | asd333 | - some values - | 1 | | 28 | asd444 | - some values - | 0 | in my models, I have : class Policy(models.Model): customer_account = models.ForeignKey(CustomerAccount, on_delete=models.CASCADE) --few more fields-- is_renewed = models.BooleanField(default = False) def use_updated_id(self): if self.is_renewed: new_id = str("R") + str(self.id) else: new_id = self.id return new_id in my template, I have : {% for policy in policy_list % } <p> Policy Number : {{policy.id}} </p> {% endfor %} which gives me output as Policy Number : 25 Policy Number : 26 Policy Number : 27 Policy Number : 28 I understand that I can define a method in model and use that instead of id as below to meet my requirement {% for policy in policy_list % } <p> Policy Number : {{policy.use_updated_id}} </p> {% endfor %} Policy Number : 25 Policy Number : R26 Policy Number : R27 Policy Number : 28 My … -
How to do Password and Confirm password validation in Django Forms
It's a signup form. When I input different passwords it doesn't show any error. I referred many sites, please help me from django import forms from .models import * class signup_form(forms.Form): firstname = forms.CharField() lastname = forms.CharField() email = forms.EmailField() GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Qual_choices = ( ('UG', 'UG'), ('PG', 'PG') ) gender = forms.ChoiceField( widget=forms.RadioSelect,choices=GENDER_CHOICES) qualification = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=Qual_choices) Password = forms.CharField(widget=forms.PasswordInput()) ConfirmPassword = forms.CharField(widget=forms.PasswordInput()) def clean(self): cleaned_data = super(signup_form, self).clean() password = cleaned_data.get('Password') confirm_password = cleaned_data.get('ConfirmPassword') if password and confirm_password: if password != confirm_password: raise forms.ValidationError('Password mismatch') return confirm_password -
Setting initial field value in generic form through URL parameter
I'm struggling to set an initial value in a form instance based on the URL parameter in Django 3.0. I have a Claim model: # models.py class Claim(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(default=timezone.now) member = models.ForeignKey(User, on_delete=models.CASCADE) I have a NewClaimForm based on ModelForm: # forms.py class NewClaimForm(forms.ModelForm): class Meta: model = Claim fields = ['product', 'text'] I have a NewClaimView based on CreateView: # views.py class NewClaimView(LoginRequiredMixin, CreateView): model = Claim form_class = NewClaimForm template_name = 'portal/new_claim.html' def form_valid(self, form): form.instance.member = self.request.user return super(NewClaimView, self).form_valid(form) And using the following template fragment on the index page... # index.html <div class="card-deck"> {% for product in products %} <div class="card text-center"> <div class="card-header"> <h5 class="card-title text-primary">{{ product }}</h5> </div> <div class="card-body"> <ol class="card-text text-left"> <li>Fill in the {{ product }} form</li> <li>Attach your medical records</li> <li>Get your claim reviewed within 48 hours</li> </ol> <a href="{% url 'portal:new_claim_product' product_id=product.id %}" class="btn btn-primary">Online Form</a> </div> </div> {% endfor %} </div> ...I pass the product_id parameter to the URL: # urls.py app_name = 'portal' urlpatterns = [ path('new_claim/<int:product_id>/', NewClaimView.as_view(), name='new_claim_product'), ] And lastly, this is what my new_claim template looks like: # new_claim.html {% extends "portal/base.html" %} {% load … -
How to set the current date to an input type = date form in Django
I have been trying to make the date field in a form to show the current date when it renders. Please find below the code. HTML File <form class="form-horizontal" role="form" method = 'POST'> {% csrf_token%} <h2>New Manufacturer Details</h2> <div class="form-group row"> <label for="createddate" class="col-sm-3 control-label">Created Date</label> <div class="col-sm-9"> <input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ createddate }}'> </div> </div> <div class="form-group row"> <label for="manufname" class="col-sm-3 control-label">Name</label> <div class="col-sm-9"> <input type="text" id="manufname" name = "manufname" placeholder="Manufacturer Name" class="form-control" autofocus required="true" value = '{{ manufname }}'> </div> </div> <div class="form-group row"> <label for="manufaddress" class="col-sm-3 control-label">Address</label> <div class="col-sm-9"> <textarea class="form-control" id="manufaddress" name = "manufaddress" placeholder="Manufacturer Address" rows="3" required="true" value = '{{ manufaddress }}'></textarea> </div> </div> <div class="form-group row"> <label for="manufcontact" class="col-sm-3 control-label">Contact Name</label> <div class="col-sm-9"> <input type="text" id="manufcontact" name = "manufcontact" placeholder="Manufacturer POC" class="form-control" autofocus required="true" value = '{{ manufcontact }}'> </div> </div> <div class="form-group row"> <label for="manufcontactnum" class="col-sm-3 control-label">Contact Number</label> <div class="col-sm-9"> <input type="text" id="manufcontactnum" name = "manufcontactnum" placeholder="Manufacturer Contact Number" class="form-control" autofocus required="true" value = '{{ manufcontactnum }}'> </div> </div> <div class="form-group row"> <label for="manufemailid" class="col-sm-3 control-label">Email Id</label> <div class="col-sm-9"> <input type="email" id="manufemailid" name = "manufemailid" placeholder="Manufacturer Email Id" class="form-control" autofocus required="true" value = '{{ manufemailid … -
Trying to use django-bootstrap-modal-forms as confirm modal, the post method is being called twice
I am trying to use the BSModalReadView as confirmation modal. So, I created the following class: class PopulateOntologyView(LoginRequiredMixin, BSModalReadView): model = Project template_name = 'modalPopUp/populateOntology.html' success_message = 'Success: Project was Read.' success_url = reverse_lazy('ontoSecReqRule:SecConProjects') def get_object(self): print("processing") user = self.request.user project = Project.objects.filter(user=user) x = project.filter(projectName=self.kwargs['project']) return x.first() def post(self, request, *args, **kwargs): print("mypost") createUCModel(str(self.request.user), self.kwargs['project']) return HttpResponseRedirect(reverse_lazy('ontoSecReqRule:SecConProjects')) I created a post method, so that when the user click the populate button the createUCModel(str(self.request.user), self.kwargs['project']) is then run. Template for the main page. <main class="mainContent"> {% include "modalPopUp/_modal.html" %} <div class="card" id="maincontent"> <div class="card-header"> <h3 class="panel-title text-center">Semi-Modeled Use Cases</h3> <span class="float-left total_count">{% if show_pageitems %} {% show_pageitems %}{% else %} Modeled Use Case: {{myUseCase|length}}{% endif %}</span> <button type="button" class="populate-project btn btn-dark float-right" name="button"> {% icon 'cogs' %} Populate Ontology </button> </div> </div> </main> {% endblock %} {% block extrascripts %} <script type="text/javascript"> $(function () { $(".populate-project").modalForm({formURL: "{% url 'useCaseExtract:PopulateOntology' view.kwargs.project %}"}); }); </script> {% endblock extrascripts %} Template for the modal: <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Populate Ontology</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Do you want to populate the ontology? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" … -
How to retrieve data to dataframe faster in Django from large database
I have 800k data in db, and I want to retrieve data to dataframe and do some manipulations with data. But it is taking really long time to retrieve the data. Here is my code: def test(request): data = pd.DataFrame(list(ReportData.objects.all().values())) some manipulations here context = {'mylist': data.to_html(classes='table table-striped').replace('border="1"','border="0"')} return render(request, 'credits/test.html', context) I was wondering if there was a way I could retrieve faster from db? Any help would be appretiated. -
Django Channels unable to receive events during sleep?
I am using AsyncWebSocketConsumer and I want to put consumer to sleep for 10 seconds while handling one specific event. So, on receiving that event I am calling await asyncio.sleep(10). But problem with this is that it is blocking events to this consumer instance for next 10 seconds. My question is that if I am using AsyncConsumer, shouldn't it continue sending future events even though I am on async sleep? I have been going through the code of daphne server and found out following: def onMessage(self, payload, isBinary): # If we're muted, do nothing. if self.muted: logger.debug("Muting incoming frame on %s", self.client_addr) return logger.debug("WebSocket incoming frame on %s", self.client_addr) self.last_ping = time.time() if isBinary: self.application_queue.put_nowait( {"type": "websocket.receive", "bytes": payload} ) else: self.application_queue.put_nowait( {"type": "websocket.receive", "text": payload.decode("utf8")} ) which means on receiving new event from frontend, it creates a new task and add it to async queue for consumer to consume. So, why sleep on one async task blocking other task? Am I missing something here? -
DRF Nested Objects serialization and creation
I'm trying to create objects just by getting a json that have the objects nested in it,for example, I have a model with only one field that is name and im getting this json {"name":"category1", "children":[{ "name":"category1.1", "children":[]}, {"name":"category1.2", "children":[{"name":"category1.2.1", "children":[]}] } ] } What i'm trying to achieve is to read this,and create category objects that reference its parent or its children, I've tried multiple solutions inspired from these answers but I can't seem to get close to getting the job done(Django rest framework nested self-referential objects -- How to create multiple objects (related) with one request in DRF?) I've tried having the model with only name and a foreign key that reference the category itself,and I added recursive field to my serializer like this: class RecursiveField(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data class CategorySerializer(serializers.ModelSerializer): subcategories = RecursiveField(many=True,allow_null=True) class Meta: model = Category fields = ['name','subcategories'] def create(self, validated_data): category = None if len(validated_data['subcategories'])==0: category = Category.objects.create(name=validated_data['name']) else: for i in range(len(validated_data['subcategories'])): child = validated_data['subcategories'] child_list = list(child.items()) subcat = child_list[1] if len(subcat)==0: subcategory = Category.objects.create(name=child.get('name')) category = Category.objects.create(name=validated_data['name'],children=subcategory) return category The best I got with this solution is being able to create the parent object,but … -
Django access to product total price through order model
I want to get each product's total price in all orders which I mean how much each product sold in all orders. What Query should I write in views.py to display this matter in html? this is my models.py: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Shipping', 'Shipping'), ('Delivered', 'Delivered'), ) # order will remain after customer deleted customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=200, null=True) def __str__(self): return self.product.name and this is my views.py: def home(request): products = Product.objects.all() orders = Order.objects.all() total_order_prices = Order.objects.aggregate(Sum('price')) orders.products = Product.objects.all().aggregate(Sum('price')) context = {'orders':orders, 'products':products,'total_order_prices': total_order_prices } return render(request, 'account/home.html', context) -
HOW TO WORK ON SQLITE DATABASE IN DJANGO?
I am new to programming i am trying to add product through my admin panel but i am getting this error: no such table found [I am using python version 3.8.2 Django version==3.0.7 and i am getting this error: No such table found][1] thanks for help [1]: https://i.stack.imgur.com/ayhGa.png -
What is good for a developer using rest in django or not using any thing making own api?
I am already learned many things about django but i want to make api and use it on reactjs but reat_framwork is good for using that ...So ,i wanted to know that if i use this am i become a professional or without using this or making own api makes me prossional -
Django import export how to read import this file
I want to read the course coloumn but when i exclude the group field it shows all the fields are being skipped. How can i import this file? -
how to choose what key to Update?
I want to choose a field to Update from my sqlite3 db using postman by utilizing request.data. However, I receive this error "OperationalError at / near "?": syntax error". I tried this code def put(self,request,*args,**kwargs): connection = sqlite3.connect('/Users/lambda_school_loaner_182/Documents/job-search-be/jobsearchbe/db.sqlite3') cursor = connection.cursor() req = request.data for key in req: if key == id: pass else: print(key) cursor.execute("UPDATE users SET ? = ? WHERE id = ?;",(key,req[key],req['id']) ) connection.commit() cursor.execute("SELECT * FROM users WHERE id=?", (request.data['id'],)) results = cursor.fetchall() data = [] # if request.data['id'] for row in results: object1 = {} col_name_list = [tuple[0] for tuple in cursor.description] for x in range(0,len(col_name_list) ): object1[col_name_list[x]] = row[x] data.append(object1) cursor.close() # serializer =PostSerializer(data = request.data ) # if serializer.is_valid(): # serializer.save() return Response(data) -
I it possible to get distinct value from __str__(self)
IS it possible to return distinct value form self() method. I need it for django models def __str__(self): return self.name -
Why should I not store my django Secret Key in settings.py
I'm not that expert in that server-side stuff, but I am wondering why I can't just leave the secret key in the setting.py file. I mean when somebody could see the settings.py I would have been already hacked, right? So couldn't I just leave the secret key where it is right now? Thx for your help and stay healthy!