Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django upload file to openstack-swift without saving locally
we want to have progress bar for uploading files in openstack-horizon. we are using drop zone for chunky uploading.like picture below. when files are uploading, the TemporaryFileUploadHandler save it locally in /tmp and then is accessible for uploading. but I want to save it directly to Openstack swift instead of locally. How can I change this handler or write new handler to do this task? -
Media files uploaded by the user are not getting displayed
Using django for rendering user uploaded data from a "/blogs/createblog" form web page to "/blogs" webpage, but the image file uploaded by the user is not getting displayed in his/her blogpost ("/blogs") page. My settings.py, base level/urls.py, app/models.py, app/views.py and the html templates are something like this: settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') baseproject/urls.py from django.contrib import admin from django.urls import path,include from . import views from django.conf import settings from django.conf.urls.static import static from django.urls import re_path from django.views.static import serve urlpatterns = [ path('admin/', admin.site.urls), path('',include('home.urls')), path('blogs/',include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app/models.py from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): blog_id=models.AutoField(primary_key=True) author=models.CharField(max_length=200) title=models.CharField(max_length=300) pub_date=models.DateField() category=models.CharField(max_length=200,default="Promotional Blogs") heading1=models.CharField(max_length=300,blank=True) content1=models.TextField(blank=True) heading2=models.CharField(max_length=300) content2=models.TextField() about=models.TextField() likes=models.ManyToManyField(User, related_name="blogpost_like") image=models.ImageField(upload_to="blog/images") def number_of_likes(self): return self.likes.count() def __str__(self): return self.title + " by " + self.author app/views.py def createblog(request): if request.method=="POST": author=request.POST.get("author") title=request.POST.get("title") today=date.today() category=request.POST.get("category") heading=request.POST.get("heading") body=request.POST.get("body") about=request.POST.get("about") pic=request.POST.get("pic") new_post=BlogPost(author=author,title=title,pub_date=today,category=category,heading2=heading,content2=body,about=about,image=pic) new_post.save() messages.success(request,"Your blog is published successfully.") return redirect("/blogs") return render(request,"blog/editor.html") app/editor.html {% extends 'blog/basic.html' %} {% block title %}Editor - BlogLikho{% endblock %} {% block body %} <div class="container my-4"> <h1 class="mb-4" style="text-align:center;">Blog Editor</h1> <form method="POST" action="/blogs/createblog">{% csrf_token %} <div class="row"> … -
How to get all User Input from a for loop in Django
Iam trying to display all the created departments in a form of HTML inputs and take user input (value1, vlaue2) and update department table with respect to "DepartmentID". the problem is it is taking only the first value from the loop how to get all the inputs from the for loop. template Department_template <input type="submit" value="Submit" > {% for department in departments %} <div class="row"> <div class="col-sm-3"> <label>value1</label> <input name="value1" class="form-control" /> </div> </div> <br /> <div class="row"> <div class="col-sm-3"> <label>value2</label> <input name="value2" class="form-control" /> </div> </div> {% endfor %} Views.py def department(request): departments = Department.objects.all() value1 = request.POST.getlist('BUID') value2 = request.POST.getlist('GBUID') for department in departments: print(value1) print(value2) context = {'departments': departments} return render(request, 'employee/department.html', context) ------------------------------------------------------------------ Output: ['1'] ['2'] ['1'] ['2'] ------------------------------------------------------------------ ------------------------------------------------------------------ What I want: ['1'] ['2'] and update DepartmentID that equals to 123 with value1 = 1 value2 = 2 ['3'] ['4'] update DepartmentID that equals to 43534 with value1 = 3 value2 = 4 ------------------------------------------------------------------ -
Django Creating forms for 2 Models. Similar to how it looks in the admin page
Description models.py class Quiz models.py class Question and class Answer admin.py for question and answer admin page for Quiz admin page for question and answers (can add or remove options in a boolean field) -
Django - One to Many relationship
I have user and user role models. There are 3 user roles as teacher, student, admin. One user should have only one role but if I make one-to-one relationship only one user can be attached to one role. I want there can be many students, many teacher, many admins but one user must only have one role. I couldn't figure out how to design this relationship. I have 2 models as User and User_Role. class role(models.Model): role_name = models.CharField(max_length=64) class user(models.Model): name = models.CharField(max_length=64) -
Django models filter/get query
When I run the following line in my django code: Site.objects.filter(id='19282') I get the following: <Site: Chicago> Can someone please help me so that when I use "Site.objects.filter(id=received_post_data.get('19282')" I get just the value "Chicago" as a string ? -
"select * into new_table from old_table" does not create primary key
Im using sql query to create tables dynamically, so i made StockSample and i want to clone its structure but by this it does not make default id as a primary key and auto increment it Heres my code, cursor = connection.cursor() query= "select * into stock_"+str(stock_id)+" from stocksample where 1=2;" cursor.execute(query) What Above SQL Query Creates: StockSample: Model: class StockSample(models.Model): user_id = models.ForeignKey(AppUser,on_delete=models.CASCADE) product_name = models.CharField(max_length=100) product_id = models.ForeignKey(Product,on_delete=models.CASCADE) barcode = models.CharField(max_length=100, null=True, blank=True) mrp = models.IntegerField() selling_price = models.IntegerField() expiry_date = models.DateField(null=True, blank=True) Tried This But still it does not make id as primary key: query = "Select *, id = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) Into stock_"+str(stock_id)+" From stocksample Where 1 = 2" query2 = "alter table stock_"+str(stock_id)+" add primary key id" GIVES ERROR -
i need help am getting an error, Page not found (404) Request Method: GET
i don't know why am getting an error to get my urls right when i add chat/ to my project but getting it working when i change my urls to '' when i have the main application in my urls.py already with ''. urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('chat/', include('chat.urls')),] app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='index'), path('<str:room>/', views.room, name='room'), path('checkview', views.checkview, name='checkview'), path('send', views.send, name='send'), path('getMessages/<str:room>/', views.getMessages, name='getMessages'), ] index.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { margin: 0 auto; max-width: 800px; padding: 0 20px; } .container { border: 2px solid #dedede; background-color: #f1f1f1; border-radius: 5px; padding: 10px; margin: 10px 0; } .darker { border-color: #ccc; background-color: #ddd; } .container::after { content: ""; clear: both; display: table; } .container img { float: left; max-width: 60px; width: 100%; margin-right: 20px; border-radius: 50%; } .container img.right { float: right; margin-left: 20px; margin-right:0; } .time-right { float: right; color: #aaa; } .time-left { float: left; color: #999; } </style> </head> <body> <div align="center"> … -
How to print data passed through the POST request in customized change_form.html
I want to print the data received in the post request on cart_change_form.html, but I have not been able to solve it for a few days. It was confirmed that the data came in normally up to the changeform_view of admin.py, but only empty values, the data before the POST request, are displayed in cart_change_form.html. Please tell me how can i pass the data after POST request to cart_change.form.html. #admin.py def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = {'title': 'Cart Add'} extra_context['show_save_and_add_another'] = False if request.method == 'POST': data = json.loads(request.body) extra_context['data'] = data print(extra_context['data']) # I successfully got data here return super(CartAdmin, self).changeform_view(request, object_id, form_url, extra_context=extra_context) #cart_change_form.html {% extends 'admin/change_form.html' %} {% url 'admin:app_list' app_label=opts.app_label %} {% load i18n admin_urls static admin_modify jazzmin %} {% get_jazzmin_settings request as jazzmin_settings %} {% block cart_extrajs %} <script type="text/javascript"> if("{{ data }}"){ # empty value is returned alert("hi"); } </script> {% endblock %} -
ForeigKey and ManytoMany Key in a single model in django
This is more of a logical question than coding I am creating an app where a company admin can sign up (company can be of three types OR combination of three options i.e. pool, consignor and consignee). This admin now can create Employee accounts and give them further roles according to the job. Now this employee model will be related to a company but according to the region will have access to only a limited consignor or consignee I have created the models for the above statement like this: class CompanyTypes(models.Model): company_choices = (('Pool Operator', 'Pool Operator'), ('Consignor', 'Consignor'), ('Consignee', 'Consignee')) company_type = models.CharField(max_length=500, default='Pool Operator', choices=company_choices) class Company(models.Model): type = models.ManyToManyField(CompanyTypes) name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=50, default=0) phone = models.CharField(max_length=50, default=0) gstin = models.CharField(max_length=50, default=0) address = models.CharField(max_length=500, default=0) class User(AbstractUser): is_admin = models.BooleanField(default=False) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) @property def full_name(self): return self.first_name + " " + self.last_name class GroupModels(models.Model): module_choices = (('HR', 'HR'), ('Tech', 'Tech'), ('Marketing', 'Marketing')) module = models.CharField(max_length=500, choices=module_choices) class Group(models.Model): name = models.CharField(max_length=500, default=0) modules = models.ManyToManyField(GroupModels) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=500, default=0) role = models.CharField(max_length=100, default='View') #View/CRUD … -
Can we customized behaviour of SESSION_EXPIRE_AT_BROWSER_CLOSE in django?
I want to customize SESSION_EXPIRE_AT_BROWSER_CLOSE behavior how to do it? Basically, I'm maintaining user a flag when the user login and logs out but when SESSION_EXPIRE_AT_BROWSER_CLOSE is used logout URL is not called so that I'm not able to maintain the flag variable value? So can I customize SESSION_EXPIRE_AT_BROWSER_CLOSE so that I can maintain my flag variable? -
Cant run django server, ModuleNotFoundError: No module named 'pwd.settings'; 'pwd' is not a package
When i type "python3 manage.py runserver" this error occured: ModuleNotFoundError: No module named 'pwd.settings'; 'pwd' is not a package When i running server on my local machine its working. When i running server on digitalocean it isnt working. my pip freeze: asgiref==3.4.1 attrs==19.3.0 Automat==0.8.0 blinker==1.4 certifi==2019.11.28 chardet==3.0.4 Click==7.0 cloud-init==21.3 colorama==0.4.3 command-not-found==0.3 configobj==5.0.6 constantly==15.1.0 cryptography==2.8 dbus-python==1.2.16 distro==1.4.0 distro-info===0.23ubuntu1 Django==3.2.9 entrypoints==0.3 httplib2==0.14.0 hyperlink==19.0.0 idna==2.8 importlib-metadata==1.5.0 incremental==16.10.1 Jinja2==2.10.1 jsonpatch==1.22 jsonpointer==2.0 jsonschema==3.2.0 keyring==18.0.1 language-selector==0.1 launchpadlib==1.10.13 lazr.restfulclient==0.14.2 lazr.uri==1.0.3 MarkupSafe==1.1.0 more-itertools==4.2.0 netifaces==0.10.4 oauthlib==3.1.0 pexpect==4.6.0 Pillow==8.4.0 pyasn1==0.4.2 pyasn1-modules==0.2.1 PyGObject==3.36.0 PyHamcrest==1.9.0 PyJWT==1.7.1 pymacaroons==0.13.0 PyNaCl==1.3.0 pyOpenSSL==19.0.0 pyrsistent==0.15.5 pyserial==3.4 python-apt==2.0.0+ubuntu0.20.4.6 python-debian===0.1.36ubuntu1 pytz==2021.3 PyYAML==5.3.1 requests==2.22.0 requests-unixsocket==0.2.0 SecretStorage==2.3.1 service-identity==18.1.0 simplejson==3.16.0 six==1.14.0 sos==4.1 sqlparse==0.4.2 ssh-import-id==5.10 systemd-python==234 Twisted==18.9.0 ubuntu-advantage-tools==27.2 ufw==0.36 unattended-upgrades==0.1 urllib3==1.25.8 wadllib==1.3.3 zipp==1.0.0 zope.interface==4.7.1 my manage.py file #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pwd.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() i dont know what to do with that -
PyMongo or MongoEngine for Django
For one of my projects I preferred using Django+Mongo. Which one is similar with mongooses(Node.js) -
object is not callable error in Django `DetailView`
I am getting an object is not callable error but I do not know why. My model is as follows... class PetDetailView(LoginRequiredMixin, generic.DetailView): model = Pet @property def get_queryset(self): pet_owner = PetOwner.objects.get(user=self.request.user) pet = pet_owner.pet_set.get(pk=self.kwargs["pk"]) queryset = pet return queryset I did something very similar to return a list of pets given the current user in a different class with a ListView and when returning pets everything works fine. This is a DetailView though and I am only returning just one thing. I want to only return the pet of the user that is currently logged in and not any pet based on the primary key. Because of this I am overriding the get_queryset method to ensure I do not have access to any other items that do not pertain to the current logged in user. I printed to the console what pet is and I get Leo instead of <Pet:Leo>. I think this might be the problem but if it is I'm not sure why it's happening when in my python shell it works as I expect it. -
Cannot find fetchall while calling oracle stored procedures from Django
I am new to Oracle databases. I need to call a Oracle Stored Procedure from my Django project. That procedure returns a cursor. Below is the procedure create or replace procedure test_proc (val in NVARCHAR2, c1 out SYS_REFCURSOR) is begin open c1 for select * from rfc_types_matcher; end; This is how I am making call to procedure from my Django application import cx_Oracle dsn_tns = cx_Oracle.makedsn('host', '10710', service_name='sname') conn = cx_Oracle.connect(user=r'user', password='pass', dsn=dsn_tns) cursor = conn.cursor() out_val = cursor.var(cx_Oracle.CURSOR) params.append(out_val) data1 = cursor.callproc(sp_name, params) data = out_val.getvalue() But if I do cursor.fetchall() it says its not a query. But if I run cursor.execute("raw query") I can get cursor.fetchall() How to get resultset of a stored procedure? -
How do I access the linked table in django
My blog has multiple recipes in each blog post. And the recipes are used more than once across all blog posts. I am trying to create a page where I can display all the recipes in a grid. Once the visitor clicks on a recipe I want it linked to the first blog post in the database that includes that specific recipe. Cause I have html pages for every blog post but not for every recipe. I cannot wrap my head around how this will be structured and accomplished. Should I redesign the models or is there a way to do this with django templates? Any help will be appreciated! models.py class Posts(models.Model): title = models.CharField(max_length=155) summary = models.TextField(blank=True, null=True) slug = models.SlugField(unique=True, max_length=155) recipes = models.ManyToManyField('Recipes', through='PostRecipes') class PostRecipes(models.Model): post = models.ForeignKey('Posts', models.DO_NOTHING) recipe = models.ForeignKey('Recipes', models.DO_NOTHING) class Recipes(models.Model): title = models.CharField(max_length=155) summary = models.TextField(blank=True, null=True) content = models.TextField(blank=True, null=True) views.py def allrecipes(request): recipes = Recipes.objects.all() context = { 'recipes': recipes, } return render(request, "All-recipes.html", context) All-recipes.html {% for item in recipes %} <a href="{{ STATIC_URL }}/{{ item.slug }}">{{ item.title }}</a> {% endfor %} -
Django: Data not showing in HTML when trying to read a CSV file
This is my view code to read an uploaded csv file thanks to models.FileField. When I try to show the variable in my HTML template unfortunly nothing appears. What am I doing wrong? VIEWS def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): data = request.FILES['docfile'] data = pd.read_csv(data, header=0, sep=',', encoding="UTF-8") form.save() return redirect('upload_file') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.filter(user=request.user.userinformation).all() context = { 'documents': documents, 'form': form, 'message': message } return render(request, 'list.html', context) def data_1(request): data = upload_file(request) header = list(data.columns) first_row = data.iloc[0] context = { 'header': header, 'first_row': second_row } return render(request, 'list.html', context) URLS urlpatterns = [ path('file/data', views.data_1), path('file/upload', views.upload_file, name='upload_file'), ] HTML {{ header }} {{ second_row }} {% for row in second_row %} {{ second_row }} {% endfor %} -
How to count date fields in queryset with same foreign key in Django
I'm using Django, is there a way to calculate between different fields in a queryset that have the same foreign key? That is, I want to subtract enroll_date from injection_date. injection_date enroll_date student_id (Foreignkey) 2021-10-31 22 2021-11-03 22 This is the code I've written so far, what do I need to fix? [views.py] injection_enroll = Student.objects\ .annotate(injection_enroll=F('injection_date') - F('enroll_date'))\ .values('injection_enroll') -
Django Comparing Current Time With Model TimeField
I have a class in models.py: class SomeClass(models.Model): ...other fields... mytime = models.TimeField() I want to manipulate current time with mytime, like substraction and comparison. I have tried to get the current time with datetime.datetime.now().time(), and was able to do comparison like SomeClass.objects.get(some_filters).mytime < datetime.datetime.now().time(), but I couldn't do subtraction. Is there a convenient way, either in Django or Python, to unify their time formats before doing manipulation? -
How to fix "Please correct duplicates" below in django admin page?
How to fix this duplication error? my code show this error after adding the same teacher said it has duplicates, how can I fix this? This is my models.py code. Maybe it has something to do with OneToOneField, I tried changing but the error still exists. from django.db import models from django.contrib.auth.models import AbstractUser from django_extensions.db.fields import AutoSlugField from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class User(AbstractUser): is_admin = models.BooleanField('Is admin', default=False) is_teacher = models.BooleanField('Is teacher', default=False) is_student = models.BooleanField('Is student', default=False) This error happened after using AbstractUser class Student(models.Model): name = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) id_number = models.IntegerField() def __str__(self): return str(self.name) class Teacher(models.Model): name = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return str(self.name) class SchoolSubject(models.Model): subject_name = models.CharField(max_length=250) def __str__(self): return self.subject_name class Subject(models.Model): SEMESTER_CHOICES = ( ('1st', '1st Sem'), ('2nd', '2nd Sem') ) REMARKS = ( ('1', 'Passed'), ('2', 'Failed'), ('3', 'No Grade'), ('4', 'Incomplete') ) instructor = models.OneToOneField( Teacher, on_delete=models.CASCADE, unique=True) name = models.ForeignKey( Student, on_delete=models.CASCADE) year_taken = models.CharField(max_length=225) semester = models.CharField( max_length=10, choices=SEMESTER_CHOICES, default='1st') # subject_name = models.ForeignKey(TeacherSubject, on_delete=models.CASCADE) subject_name = models.OneToOneField( SchoolSubject, on_delete=models.CASCADE, unique=True) grade = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, validators=[ MinValueValidator(0.00), MaxValueValidator(5.00)]) remarks = models.CharField(max_length=10, choices=REMARKS, default='3') slug = AutoSlugField(populate_from=['subject_name'], … -
How to handle one type errors once for multiply celery tasks?
I have django app which run big amount of celery tasks. Sometimes this tasks raise erors with the same type then I got too many log messages about the same error. Is there some approach to catch the certain type error and log this only one time for all tasks? -
Turning on a webapp's functionality using a button in another webapp
I have two different web apps (designed using Django) which are deployed on different servers and running independently. I am searching for the following pointers: Imagine there is a functionality X in webapp1 and a button1 in webapp2. When button1 is pressed (webapp2), the X1 functionality(webapp1) must be activated. -
How to use django rest api to do inference?
I was trying to build a website with Django rest API as the backend. when given a string Its gives the score from 1 to 10 for negativity. The frontend part of the website was built using next.js. Previously I have made the same app without Django rest API by doing all inference in the views.py file. Now I am using Rest API I am confused about where should I need to include the machine learning inference code. I have seen tutorials on the internet showing that inference code is attached in the models.py file. Previously when I included inference code in views.py the page used to get reload whenever I do the inference. I want to avoid it. What is the best practice to include inference code while using Django rest API. -
¿How to add multiple forms inherited from another form with Django?
I have a question, what happens is that when I click the plus sign (+), the fields are repeated to put more data. I did some research and saw that I can use a formset, I only have a problem placing the code for the views. Since I'm inheriting from Parte/forms.py to Presupuestos/forms.py and I don't know if in Parte/views.py or Presupuestos/views.py to do the modification for the formset or how to adjust it to what I already have in my views Parte/model.py class Parte(models.Model): codigo=models.IntegerField() quantity=models.IntegerField() unit_price=models.IntegerField() total_price=models.IntegerField() tax_free=models.BooleanField() descripcion=models.TextField(max_length=255,blank=True, null=True) descuento=models.IntegerField(default=0) total=models.IntegerField() def __str__(self): return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_price} {self.tax_free}{self.descuento}{self.total}' Parte/forms.py from django import forms from django.forms import formset_factory from .models import Parte class ParteForm(forms.ModelForm): class Meta: model=Parte fields=['codigo','descripcion','quantity','unit_price','total_price','tax_free'] ParteFormset = formset_factory(ParteForm, extra=0) Presupuestos/forms.py class PresupuestosParteForm(forms.ModelForm): class Meta: model = Parte fields = '__all__' widgets = { 'codigo': forms.TextInput( attrs={ 'class': 'form-control' } ), 'quantity': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'unit_price': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'multiplicar()', } ), 'total_price': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'tax_free': forms.CheckboxInput( attrs={ 'class': 'form-check-input', 'onclick': 'taxes_free(multiplicar())', } ), 'descripcion': forms.TextInput( attrs={ 'class': 'form-control' } ), 'descuento': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'totales()', } ), 'total': forms.NumberInput( attrs={ 'class': 'form-control', … -
discount amount after posting a sale - Django
I am making an app that consists of a sales system. I want that when registering a sale, the quantity sold is discounted to the product. I leave the sales and product models, also the createview: class Product(LlegadaModel): """Product model.""" nombre = models.CharField(max_length=100) precio = models.FloatField() cantidad = models.FloatField() ... class Venta(LlegadaModel): """Venta model.""" fecha = models.DateTimeField(default=timezone.now, help_text='Ejemplo: 09/11/2021 17:20:00') cliente = models.ForeignKey(Cliente, on_delete=models.SET_NULL, null=True) producto = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) cantidad = models.FloatField() forma_pago = models.CharField(help_text='Contado - QR - Tarjeta', max_length=8) create view class CreateVentasView(CreateView): """Create sales.""" template_name = 'ventas/create.html' form_class = VentasForm success_url = reverse_lazy('ventas:list') context_object_name = 'venta'