Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make if condition in dropdown
I am trying to make a Django based website, and I want to make a dropdown with if and else conditions working on it, means that if a person selects physics in the dropdown and presses the submit button, it should go to a specific page and if he presses chemistry then it goes to a specific page, please tell me how to do this, I am attaching my code. Main page (home.html): <!DOCTYPE html> <html> <head> <title>Hi there</title> </head> <body> <form action="{% url 'test' %}"> <select name="Subject"> <option value="Mathematics">Mathematics</option> <option value="Physics">Physics</option> <option value="Chemistry">chemistry</option> <option value="accounts">accounts</option> <option value="bsuiness">business</option> </select> <input type="submit" value="Generate Password" class="btn btn-primary"> </form> </body> </html> Views.py: from django.shortcuts import render def home(request): return render(request, 'homepage/home.html') def test(request): if request.GET.get('Physics'): return render(request, 'homepage/home.html') else: return render(request, 'homepage/test2.html') urls.py from django.contrib import admin from django.urls import path from homepage import views as home_views from homepage import views as test_views urlpatterns = [ path('admin/', admin.site.urls), path('', home_views.home, name='home'), path('test/', test_views.test, name='test'), Please help by telling what to code to make the if statement work -
'ManyToManyDescriptor' object has no attribute 'filter'
I am making an application which obtains data and then displays it through graphics, the problem is that I am making a query to know when developers belong to a project, but it throws me an error I disagree that the ManyToManyDescriptor object does not have the filter attribute. My view: class ProjectTemplateView(TemplateView): template_name = 'index.html' def count_developer(self): projects = Project.objects.all() for project in projects: developers = Developer.project_set.filter(project=project).count() print(developers) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['projects'] = Project.objects.all() context['developers'] = self.count_developer() return context This is my project model: class Project(models.Model): STATUS_CHOICES = ( ('approver', 'Aprovado'), ('process', 'En Proceso'), ('inactive', 'Inactivo'), ) name = models.CharField(max_length=50, unique=True, verbose_name='Nombre') developer = models.ManyToManyField(Developer, verbose_name='Desarrollador') visibility = models.BooleanField(default=False, verbose_name='Visibilidad') status = models.CharField( max_length=10, choices=STATUS_CHOICES, verbose_name='Estatus') slug = models.SlugField(max_length=50, unique=True) created_at = models.DateTimeField( auto_now_add=True, verbose_name='Fecha de Creacion') update_at = models.DateTimeField( auto_now=True, verbose_name='Fecha de Actualizacion') And this is my developer model: class Developer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de Creacion') -
contact form send email success but no message in my email box - django
I have created the below django contact form for the contact page of my website. The problem with the form is that when a user fills and clicks the submit button, it show a success message but the email is not sent. i mean i don't receive message in my box Can someone please check and tell me where I went wrong. forms.py : from django import forms from django.forms import ModelForm # contact form class ContactForm(forms.Form): contact_name = forms.CharField(required=True ) contact_email = forms.EmailField(required=True ) title = forms.CharField(required=True) content = forms.CharField(required=True ) views.py : def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') title = request.POST.get('title') template = loader.get_template('website_primary_html_pages/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'title' : title, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "Hey , There are new Message from blog", content, "Creative web" + '', ['contact@techpediaa.com'], headers = { 'Reply To': contact_email } ) email.send() return redirect('Success') return render(request, 'website_primary_html_pages/contact_us.html', {'form':Contact_Form }) #end contact form settings.py : #MY EMAIL SETTING DEFAULT_FROM_EMAIL = 'contact@techpediaa.com' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' when user fills all fields it show message send success but … -
Modal Submit with Ajax Submitting Non-Modal Form - Django
I am working with a django project where I have a form to create a proforma invoice. Within that form there is a button which launches a bootstrap modal to create a bank which may be needed for the proforma invoice. This modal submits via ajax and when I click submit, it is trying to trigger a submission of the proforma form which does not work because I don't have all the data entered. How can I fix my code to stop the modal submission trying to submit the non-modal form? forms.py class CreateBankForm(forms.ModelForm): class Meta: model = BankAccount fields = ['name', 'account', 'routing', 'swift'] class ProformaForm(forms.ModelForm): class Meta: model = Proforma fields = [ 'name', 'exporter', 'shipment', 'date', 'bank' ] proforma.html <form id="proformaform" method="POST"> ... ... {{proformaForm.as_p}} </form> <p> <button type="button" class="btn btn-primary js-create-book"> <span class="glyphicon glyphicon-plus"></span> New book </button> </p> <!-- THE MODAL WE WILL BE USING --> <div class="modal fade" id="modal-book"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> <script> ////////////CREATE A BANK WITH AJAX $(function () { $(".js-create-book").click(function () { $.ajax({ url: '/create_bank/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }); }); $("#modal-book").on("submit", ".js-book-create-form", function () { … -
How to use hex(x ' ' ) inside of a sql statement with python execute?
I am working in Python/Django with a MySQL Db. This sql query works fine in my Workbench SELECT * FROM frontend_appliance_sensor_reading WHERE id = (SELECT max(id) FROM frontend_appliance_sensor_reading WHERE sensor_id = hex(x'28E86479972003D2') AND appliance_id = 185) I am returning the latest record for a sensor. The hex string is the sensor ID that I need to pass in as a variable in python. Here is my python function that would return this object def get_last_sensor_reading(appliance_id, sensor_id): dw_conn = connection dw_cur = dw_conn.cursor() appliance_id_lookup = appliance_id dw_cur.execute(''' SELECT * FROM frontend_appliance_sensor_reading as sr WHERE id = (SELECT max(id) FROM frontend_appliance_sensor_reading WHERE sensor_id = hex(x{sensor_id_lookup}) AND appliance_id = {appliance_id_lookup}) '''.format(appliance_id_lookup=appliance_id_lookup, sensor_id_lookup = str(sensor_id))) values = dw_cur.fetchall() dw_cur.close() dw_conn.close() print values However it seems to concat the x with the variable like this: (1054, "Unknown column 'x9720032F0100DE86' in 'where clause'") I have tried various string combinations to get it to execute correctly with no luck. What am I missing? Does the x actually get interpreted as a str? Or should I be converting it to something else prior? Also, I cannot not use Django's ORM for this as the sensor id is stored in a BinaryField as BLOB data. You cannot filter by … -
Npm run dev command is stuck and wont work
Hello there I recently started watching a tutorial about django rest framework (for the frontend I am using reactjs) but I have a problem with downloading/initializing react. I used the "npm run dev" command in the cmd and it is stuck at: "[webpack-cli] watching files for updates...". Does anyone know what to do?? If so can you pls tell me. -
Django Type Error adding data to model via django admin backend
I have no clue what happened... Yesterday I was in django/admin page testing out the form, making sure I can upload images and it was working perfectly fine. This morning, I get a type error and I cannot for the life of me track down where it's coming from. Here is my models.py from django.db import models class MenuCategory(models.Model): name = models.CharField(max_length=25, unique=True, default='') summary = models.TextField(max_length=120, unique=False, default='') class Meta: verbose_name = 'Menu Category' verbose_name_plural = 'Menu Categories' def __str__(self): return '' + self.name class MenuItem(models.Model): category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) title = models.CharField(max_length=25, unique=True) price = models.FloatField() image = models.ImageField(upload_to='', width_field=200, height_field=200) description = models.TextField(max_length=240, unique=False, default='') class Meta: verbose_name = 'Menu Item' verbose_name_plural = 'Menu Items' def __str__(self): return '' + self.title And my admin.py from django.contrib import admin from menu.models import MenuItem, MenuCategory # Register your models here admin.site.register(MenuItem) admin.site.register(MenuCategory) class MenuInlines(admin.TabularInline): model = MenuItem class CategoryAdmin(admin.ModelAdmin): inlines = [MenuInlines] I really don't understand where the TypeError is =( This seemed to be working fine yesterday and I have no clue what I changed. I did 'makemigrations' and 'migrate' just to be sure... Any clue? Did I leave something out that might be pertinent? -
Can i use Dynamic sidebar menu for multiple users using conditional operator in Django franework?
I have 1 admin and 6 prilages.. admin gives privilages to each user like a, b, c, d, e. If admin gives the prilages of a and c to me, then, i need to see the sidebar with only a and c. But when admin loged in its want to see all sidebar like a, b, c, d, e. -
Update your Django project after deployment in Apache2
So, I deployed my Django Project, my website is currently running but of course I want to keep developing it. Which way does it the most sense? It comes to mind the following methods: -Develop in my work machine, uploading to Github, clone it in my server and copy the files that have been changed. -Develop directly via SSH in VIM. Both don't sound so great. Any other idea? Thank you ! -
{% with %} tag to store 'in' expression value in django template
I'm trying to store a boolean value in a variable within the {% with %} tag of Django. But its not working. is there any other way around to do this ? Can I create a custom filter for it or is there any pre-built filter for this? {% with isEnrolled=course in all_courses %} ..... {% endwith %} -
Append <tr> to HTML table progressively with a JQuery AJAX call (Django framework)
I am new to Javascript, Jquery and Ajax request and I have an issue with the execution of my scripts. Basically I have a very long list to display on my home page (1200+ items). I used to load the page normally but since my list would take a long time to load (and since it's right in the middle of the page) there would be an enormous delay before all my HTML elements would show. For example my footer would be the last item to load and it would appear almost a full second after my navbar. I decided to use AJAX requests to load my HTML first, get my navbar and my footer done and only then fetch my list to show it in the middle of my page. The first problem I encounter is that while my script is being processed, nothing appears. This means that even if my first list item's "tr" is ready, it will only show when the 1200th's "tr" is also ready. I would need the table to be populated progressively. I can see my "tr"s being generated in my console but they are only applied in my HTML after they are all … -
Append an item to a streamfield in wagtail
I have a streamfield which is working, and has data in, the code I wrote to do this looks something like: class NewYearBlock(blocks.StructBlock): year = blocks.IntegerBlock(verbose_name="Year (the year this data is rolling into)") holidayRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over") overtimeRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over") class Meta: icon = 'user' and newyearStream = StreamField([ ('newyear', NewYearBlock()), ], blank=True) What I would like to do is to append an item to this streamfield via some code, I know how to replace the item with the below (which works) employeeModel.newyearStream = newyearStream employeeModel.save() But this replaces what already exists. I was then thinking I could loop over the existing stream, and then create a new object to save, but when I try to do that I receive TypeError: cannot unpack non-iterable StreamChild object so I looked at the type, and see it is <class 'wagtail.core.blocks.stream_block.StreamValue'> Can anyone help point me in the right direction to either loop through the stream and get my results out, or a better way to append to my streamField. Thanks for your time helping, Dan -
How to print Django queryset in Tabular form in python3 manage.py shell
Is there a way or package to print Django queryset in Tabular form in python3 manage.py shell The queryset prints like this: But I want it to be printed like this -
Django auto_now count results in a certain date
I want filter of all request done is done in a certain date class Log(models.Model): request = models.CharField(max_length=255) created_at = models.DateField(default=now, blank=True) def __str__(self): return self.request But I don't how to do it correctly compare both the created_at and the date today quantity_of_requests = Log.objects.filter(created_at=now()).count() -
How to serve a rendered JPEG image with Django Rest Framework?
On a call to my Django API, I'm trying to generate an image with matplotlib and then serve this image back to the client using Django Rest Framework. I'm aware of Serve images with django-rest-framework and Return image using Django REST framework Render, but they can't quite get me there. I think I'm supposed to create a sort of CustomRenderer, then pass the result to the view. I'm unclear about how such a view.py should look. What would be really ideal would be to be able to generate the image in memory, and then serve this without having to save it as a physical file on my server. So I have the image renderer, render.py in my app's directory: # app/render.py from rest_framework import renderers from matplotlib import pyplot as plt class JPEGRenderer(renderers.BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): # data coming in would be a numpy array # Matplotlib can create the image from the numpy data array. # It would be cool to generate and return this as a Bytes IO object # to avoid persisting the file on my server as pass this to the view, … -
override save() and query_set() django admin
I'm searching for a way to customize the Django Admin to support permissions and data based on the user group. For example, I've just created the Developers1, Developers2 groups.. now I've also created the Transaction model, with AdminModel to specify how to list data. what im trying to do is i want each group to only access its own Transaction model, and each group can only add, delete, update and view their own Transactions (eg developers1 group cant access developers2 Transactions and vice versa) in the admin.py i've override the save() method as below.but im not sure how to make the filter to save data for each group @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference','familymember__name'] inlines = [FamilyGroupInline,FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user.groups.filter() print(obj.user) super().save_model(request, obj, form, change) and after i make a queryset() as below def get_queryset(self, request): qs = super().get_queryset(request) print(qs.values('group__name')) if request.user.is_superuser: return qs return qs.filter(group__in=request.user.groups.all()) -
IndentationError: unindent does not match any outer indentation level in json.loads(request.body)
Im stuck at this error code, IndentationError: unindent does not match any outer indentation level and its located in my data = json.loads(request.body) . Can someone help me to find the error. I already search lot of google page about this error but its seems different with my problem, thx. from django.shortcuts import render from django.http import JsonResponse from django.http import HttpRequest import datetime import json def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create( customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create( order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = transaction_id else: print('User is not logged in') return JsonResponse('Payment complete!', safe=False) -
Minify All Static Files Without Changing Their Names Django-Pipeline
I'm using Django Pipeline as a drop in minifier for my static files. What I would like to happen is that when I run collectstatic that the django-pipeline would minify the file and output it with the same filename in the output folder. e.g. static_input/myfile.js #50kb -> collectstatic -> static_output/myfile.js #25kb Looking through the docs, it only seems possible to output multiple files to one file e.g. PIPELINE = { 'PIPELINE_ENABLED': True, 'JAVASCRIPT': { 'stats': { 'source_filenames': ( 'js/jquery.js', 'js/d3.js', 'js/collections/*.js', 'js/application.js', ), 'output_filename': 'js/stats.js', } } } Is there a way to make django-pipeline simply minify my static files without trying to merge and rename them? -
Django CSRF_COOKIE_DOMAIN on Heroku
So we deployed Django app to Heroku and everything was working well. Until I looked at cookies. I have csrftoken cookies for both app-staging.herokuapp.com and .app-staging.herokuapp.com. But when I set CSRF_COOKIE_DOMAIN = 'app-staging.herokuapp.com' I automatically get the wrong thing .app-staging.herokuapp.com. I tried everything I could but nothing helped. I tried current Firefox (83.0) and Chromium. The biggest problem is invalid check for CSRF token. Since domains don't match it's invalid. csrftoken=E9sdyx5U61IaFP3YNJHk3ZKtnllkEnyZ6i9eimHYD31sn4qXRXv7FBDOpPfpWhyt; Domain=app-staging.herokuapp.com; expires=Fri, 19 Nov 2021 15:33:52 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure Please don't suggest that I set CSRF_COOKIE_DOMAIN = None. In case one Django instance would run on more domains I would need to solve the same problem. Which we will have to do soon. -
Do we have Manage.py Task in VS code
I used to work with Pycharm But now i use VS Code for coding Django, so Does anyone know Do we have Manage.py Task in VS code or Do I have a way to make this Task? i use it Many times like when i call runserver or migrate i Take Screenshot from it in pycharm it is located below -> pycharm Manage.py Task I just need a button that opens Terminal (CMD) + 'Python Manage.py ...' when I click on it And do not need to Write 'Python Manage.py' several time. -
Django formview form_valid, form has no attribute `instance`
I'm trying to create a form view using the FormView class. It works fine displaying the post form but when posting the data form_valid function is called and here I get an error: AttributeError: 'GameForm' object has no attribute 'instance' As I can understand the form object passed in the form_valid method doesn't contain an instance but examples show that it is possible.. What am i missing? views.py from django.shortcuts import render, redirect from django.views.generic import (ListView, DetailView) from django.views.generic.edit import FormView from .models import Game from .forms import GameForm # ... Other views class GameCreateView(FormView): template_name = 'games/game_form.html' form_class = GameForm success_url = '/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.instance.author = self.request.user return super().form_valid(form) Website log AttributeError at /game/new/ 'GameForm' object has no attribute 'instance' Request Method: POST Request URL: http://127.0.0.1:8000/game/new/ Django Version: 3.1.3 Exception Type: AttributeError Exception Value: 'GameForm' object has no attribute 'instance' Django version = 3.1.3 Thanks in advance! -
How run makemigrations <app> --empty with Django and Docker?
I have a Django app with Docker and Docker-compose. So I can build, up or down my container but how can I run manage.py or django-admin command like makemigrationn <app> --empty ? In a "classical" Django project architecture, no problem But using Docker, I have an error django.core.exceptions.ImproperlyConfigured: Requested setting STATIC_URL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I try django-admin makemigrations myapp --empty --settings=core.settings.dev but have another error no module core found -
Can I create a script, "Virtual Environment" and run it in crontab?
They help me, they know I need to run a script to start the services, I use Django with Python and ubuntu server. I have been seeing many examples in crontab, which I will use, every time I restart the server, I run the Script, which contains the command to run the virtual environment and in addition to the command "python3 manage.py runserver_plus", apart was to see restart the server all nights, I was also successful with crontab, but I can't execute what the script contains. They can help me, I am not very expert, but I managed to do something. Is it the path of the script? Tried running the command directly, got no results. -
How to not show pre selected form data in django form
i have form that give list of subject name with multiple choice but when student select one of those choice then i want next time next time they again come to choice they will not see pre selected data. how can have that in django form? what would be the approach to have that solution? much appreciate for your help. thank you so much. models.py class Registration_Course(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) course = models.ManyToManyField(Student_Course_Name, blank=True) def __str__(self): return str(self.user) views.py class Course_Registration(generic.CreateView): model = Registration_Course template_name = 'test/reg.html' form_class = RegForm def form_valid(self, form): form.instance.user = self.request.user form.save() return HttpResponse("saved form") forms.py class RegForm(forms.ModelForm): answer = forms.ModelChoiceField( queryset=Answer.objects.none(), widget=forms.RadioSelect(), required=True, empty_label=None) class Meta: model = Registration_Course fields = ['course', 'student'] widgets = { 'course': forms.CheckboxSelectMultiple } -
Unique=True message need to show in the vuejs template
I am developing the VueJs app using Django rest framework, In the question model, For the content field I added the unique = true because I want the content to be different. In the api it is validating the field. class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.CharField(max_length=240, unique=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") Now I want that error message in the vuejs template after the field . What I need to change in the script of the vuejs. <template> <v-container> <h1 class="mb-3">Ask a Question</h1> <v-form @submit.prevent="onSubmit" ref="form" v-model="valid" lazy-validation> <v-textarea v-model="question_body" placeholder="What do you want to ask?" rows="3" :counter= "240" :rules= "textarearules" auto-grow outlined row-height="25" shaped ></v-textarea> <v-btn type="submit" :disabled="!valid" color="primary white--text text-center" class="mr-4 mb-3" @click="validate" rounded>Publish</v-btn> </v-form> <div v-for="question in questions" :key="question.pk"> <h1>{{ question.content }}</h1> </div> <p v-if="error" class="muted mt-2">{{ error }}</p> </v-container> </template> <script> import { apiService } from "@/common/api.service.js"; export default { name: "QuestionEditor", props: { slug: { type: String, required: false } }, data() { return { questions: [], question_body: null, error: null, valid: true, textarearules: [ v => !!v || 'Answer is required', v => (v && v.length <= 240) || 'Answer must be less than 240 …