Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, how to display thousand's point with IntegerField
I utilize in my views.py the following code: Materiale.objects.values_list('conto__nome', 'data__year','data__month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')), output_field=IntegerField())).values_list('conto__nome', 'data__year', 'data__month', 'totale')) Or rather the ExpressionWrapperwith output_fiedl = IntegerField(). But in my templates I view, ad example, the value 1000, instead 1.000. How can obtain this result? -
Conditional Statement not working in Django template
I am trying to offer a download option if the file exits but it always shows Not Avaialable even if the file exists. I have made a dictionary in views.py which saves True for that index if the file exists. I have also generated logs and the path generated at os.path.join is correct and dictionary has True for those values. I think the problem is me using 2 dot operator while accessing the dictionary in template. Template {% for upload in upload_list %} <tr> <td>{{ upload.upload_report_date|date:"M-Y" }}</td> <td>{{ upload.upload_at|date:"d-M-Y" }}</td> <td>{{ upload.upload_at|date:"h:i A" }}</td> <td>{{ upload.upload_by }}</td> <td>{% if upload.upload_errors %} Errors {% else %} Successful {% endif %}</td> {%if file_list.upload.upload_report_date %} <td><a href="{%static 'media/reports/finance'%}/sap-daily-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> <td><a href="{%static 'media/reports/finance'%}/sap-monthly-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> <td><a href="{%static 'media/reports/finance'%}/quantum-monthly-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> <td><a href="{%static 'media/reports/finance'%}/daily-ignored-vendors-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> {% else %} <td>Not Available</td> <td>Not Available</td> <td>Not Available</td> <td>Not Available</td> {% endif %} </tr> {% endfor %} Views.py upload_list = SAPActivityUpload.objects.all().order_by('-upload_at') file_list={} for upload in upload_list: try: if os.path.exists(os.path.join(settings.MEDIA_ROOT,'reports/finance/sap-daily-%s.csv' % (upload.upload_report_date).strftime("%Y-%m"))): file_list[upload.upload_report_date]=True except: pass -
when django user creates new user send mail
I am able to send the mail when Django-Admin user creates new user but this(send mail) function also trigger when i am register the user from front-end side. I want this should not call when front-end user register. Help me for this. -
Set Content-Type with Django, gunicorn and nginx
I've deployed a Django app with gunicorn and nginx as they normally recommend. After deploying, the static js and css did not load into the browser. On firefox console I get an error saying: The resource from “http://my.url/static/global/css/template.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) -
How to get full path of selected file on change of <input type=‘file’> using django
compress.html <form action="/compress" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="pdf">Select pdf :</label> <input type="file" name="pdf1" id ="pdf1" accept="pdf/*" /> <br> <button type="submit" class="btn btn-dark mt-2" value="click"> submit </button> <script type="text/javascript"> function getFilePath(){ $('input[type=file]').change(function () { var filePath=$('#fileUpload').val(); }); } </script> views.py def mergepdf(request): from pylovepdf.ilovepdf import ILovePdf ilovepdf = ILovePdf('my_secrete_key', verify_ssl=True) task = ilovepdf.new_task('compress') task.request.FILES['full_path']# here i want full path of selected file task.set_output_folder('/Downloads/download_pdffile') task.execute() task.download() task.delete_current_task() The filePath var contains the only name of selected file, not the full path. I searched it on the net, but it seems that for security reasons browsers (FF, chrome) just give the name of the file. Is there any other way to get the full path of the selected file? -
Do I have to recreate tables as models for an existing database?
I'm just starting with Python and Django and have an existing database. I'd like to create views to edit the fields in this database, do I have to create models to match these tables or is there a way to start editing after connecting the database and a view? -
Django UserCreationForm raise Validation Error when email already exist
Hi there I am new to Django. I have got a UserRegisterForm inherited from UserCreationForm. Everything works fine class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] Now I want the to show a sign 'email already exist' near by the email input box if the email's already in the database. I have tried: class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] def clean_email(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError("Username is not unique") return username def clean_username(self): email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email is not unique") return email It didn't work. I will be so glad if anyone can help. -
Django Rest Framework fields source validation naming issues
How to ensure DRF serializer attribute or validated_data parameter for validate and create method does not change to model attribute name when field name are declare in different name using source argument class TestSerializer(serializers.HyperlinkedModelSerializer): new_name = HyperlinkedRelatedField( source='old_name', view_name='viewset-detail', queryset=SomeModel.objects.all(), ) # override validate method def validate(self, attrs): attrs['old_name'] # this is valid attrs['new_name'] # invalid # override create method # problem same for create here def create(self, validated_data): attrs['old_name'] # this is valid attrs['new_name'] # invalid Just want to know is this part of DRF design(any reason) or I did this wrongly, is kind of confuse other team members when this happened -
Pagination stopped working on Django application
I am new to Django and I just picked up a book "Django 2 by example". I followed all the code in the tutorial bu something broke the pagination along the line and I just can't figure what it is. I get an output of "Page of ." instead of "Page 1 of 1. at the base of my blog. Find some of my code below:. P.S: Kindly ignore the indentation in the code. Thank you. Views.py from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from django.core.mail import send_mail from django.db.models import Count from taggit.models import Tag from .models import Post, Comment from .forms import EmailPostForm, CommentForm def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None` if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts, 'tag' : tag}) list.html {% extends "blog/base.html" %} {% block title … -
Continuously parse CSV files which are updated by another process in PHP
I'm working on project in which csv file is updated continuously with python program. I'm creating a dynamic webpage in PHP which shows updated csv values in HTML table. I got logic for reading csv file in PHP but don't know how to read the updated values continuously and display them in HTML table in which updated values overwrites the previous values -
Django and pure Python
I want to create a web app with Django and integration of Selenium and Python-Docker API. Where inside the Django project is the correct place to put the Selenium scripts so users will be able the run it by a puse of a button? I've seen some thred saying inside a 'view', but is is a lot of logic that I've sprated into multipale .py files. -
Django Admin - filter inline options by 3rd Model?
Use-case: There are 3 Models: User Division Office The relations are: An Office is always connected to one Division. A User can be a member of various Divisions, and work for various offices. I want to create an inline for my User admin page, under the Office field. However I would like to populate the inline options with Offices that belong only to Divisions that the user is part of. Code: class User(models.Model): username = models.CharField(max_length=100) class Division(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User) class Office(models.Model): name = models.CharField(max_length=100) division = models.ForeignKey(Division, on_delete=models.CASCADE, null=True, blank=True) class OfficeAdminForm(forms.ModelForm): # I assume I should change it here, but I don't know how to filter accordingly. office = forms.ModelChoiceField(queryset=Office.objects.all(), empty_label="(Nothing)") class OfficeInline(admin.TabularInline): model = Office form = OfficeAdminForm class UserAdmin(admin.ModelAdmin): inlines = [OfficeInline] admin.site.register(Item, ItemAdmin) admin.site.register(Category) -
Django - Excel Calculate the total of method value
I created a data model that user upload excel file and calculate the row and column class Data(models.Model): """ Model of Data""" user = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to="documents/%Y/%m/%d") uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) def amount(self): wb = xlrd.open_workbook(self.document.name) worksheet = wb.sheet_by_index(0) row_count = worksheet.nrows print(row_count) column_count = worksheet.ncols print(column_count) total_col_row = row_count * column_count # print payments payments = total_col_row * 9 return payments how to get the total amount if user enter for example a 3 files? -
Filtering django model using date
I need to filter some data from models using the date. I see some posts that speaks about ranges but I just want to see for example the rows of my table from the 22/04/2020, in other words, just one day. Reading the documentation, I understood that I have to do the following, import datetime prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp=datetime.date(2020, 4, 22)) prueba = loads(serializers.serialize('json', prueba)) for p in prueba: print(p) But appears the following warning: RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-04-22 00:00:00) while time zone support is active. And the list appears empty. I think the problem is that is just filtering using 2020-04-22 00:00:00 and not all the day. How can I fix this? Between two dates is working but just one day I don't know how to do it. import datetime start_date = datetime.date(2020, 4, 22) end_date = datetime.date(2020, 4, 23) prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp__range= (start_date,end_date)) PD: I have info rows in this day. Thank you very much. -
Class view default view location defaults to wrong folder
I have the following class in my views.py file: class PostDetailView(DetailView): model = Product Which correctly displays view, stored at products/product_detail.html However, i also have the following class in views file: class OfferDetailView(DetailView): model = Offer I have created offer directory with offer_detail view. However, Django still tries to get products/offer_details.html Of course i can manually set template name, but I want Django to search in offers folder. Why does it search in products? -
I AM THINKING THERE IS SOMETHING WRONG IN MY VIEW RELATED TO FOREIGN KEY. PLEASE HELP ME OUT
This is my model class addteacher(models.Model): Teacher_Name=models.CharField(max_length=50) Teacher_Subjects=models.ForeignKey("subjects",related_name="+", on_delete=models.CASCADE) //here foreign key use Teacher_Subjects_Code=models.CharField(max_length=50) Teacher_Username=models.CharField(max_length=50) Teacher_Password=models.CharField(max_length=50) class subjects(models.Model): Subject_Name=models.CharField(max_length=50) ** form related to model** class addstudent_form(forms.ModelForm): Student_Registration_no=forms.CharField(widget=forms.TextInput()) Student_Name=forms.CharField(widget=forms.TextInput()) Student_roll_no=forms.CharField(widget=forms.TextInput()) Student_mobile_no=forms.CharField(widget=forms.TextInput()) class Meta(): model = addstudent fields = ['Student_Registration_no','Student_Name','Student_roll_no','Student_mobile_no'] class addsubject_form(forms.ModelForm): Subject_Name=forms.CharField(widget=forms.TextInput(),required=True) class Meta(): model=subjects fields = ['Subject_Name'] ----------------------below is view-------------- def addteacher1(request): if request.method == 'POST': Teacher_Name = request.POST['Teacher_Name'] Teacher_Subjects = request.POST['Teacher_Subjects'] Teacher_Subjects_Code = request.POST['Teacher_Subjects_Code'] Teacher_Username = request.POST['Teacher_Username'] Teacher_Password = request.POST['Teacher_Password'] Teacher_Password2 = request.POST['Teacher_Password2'] if Teacher_Password == Teacher_Password2 : if login_teacher.objects.filter(user_name_teacher = Teacher_Username).exists(): messages.info(request, 'username exists') return render(request, 'createteacher.html') else: add_teacher = addteacher.objects.create(Teacher_Name=Teacher_Name, Teacher_Subjects=Teacher_Subjects, Teacher_Subjects_Code=Teacher_Subjects_Code, Teacher_Username=Teacher_Username, Teacher_Password=Teacher_Password) add_teacher.save() return render(request, 'createteacher.html') else: return render(request, 'principlehome.html') below is the error I am receiving while is am giving input using HTML ValueError at /principle/addteacher Cannot assign "'c'": "addteacher.Teacher_Subjects" must be a "subjects" instance. Request Method: POST Request URL: http://127.0.0.1:8000/principle/addteacher Django Version: 3.0.2 Exception Type: ValueError Exception Value: Cannot assign "'c'": "addteacher.Teacher_Subjects" must be a "subjects" instance. I am 19-year student I tried hard to this but I can't. please help me out if you can I though I am using foreign key wrong. 1 There is "c " stored in the database in the subject table 2 I am thinking if I … -
insert to mysql database by reading text file in python
I have a text file with delimiter "|" ,below is the file structure. Each row should be considered as each row in database table and each filed is separated by "|" symbol. 1585035601212|asd.OTHER|3|ww1|7.14.2| 15850356012323|asd.OTHER|3|ww1|7.14.2| 158503560113132|asd.OTHER|3|ww1|7.14.2| am using below code, import mysql.connector, csv, sys with open('externaldatabase.txt') as textfile: csvreader = csv.reader(textfile, delimiter='\t') csvdata = [] for row in csvreader: csvdata.append(row) conn = mysql.connector.connect( host="localhost", user="root", passwd="root", database="mydjangoapp", port=3307, ) c=conn.cursor() for row in csvdata: # Insert a row of data c.execute("INSERT INTO externaldatabase (release_date, version, download_url, name, description) VALUES ('%s', '%s', '%s', '%s', '%s')" % (row)) conn.commit() c.close() but I got following error c.execute("INSERT INTO externaldatabase (release_date, version, download_url, name, description) VALUES ('%s', '%s', '%s', '%s', '%s')" % (row)) TypeError: not enough arguments for format string also it will be helpful if i can read files in a particular destination with out mentioning the file name and remove the file after inserting to DB(Type of file to be read is FILE) -
How do i build my react front end and django backend application for a 32 bit system?
I am working on an application for a 32 bit PC. i have almost completed the front end and backend. now i want to build executable for my application (if that's even possible in case of react and django). I want to run the application on a 32 bit PC. I myself have a 64 bit machine. Please guide me how do i do that. For django application i can create a virtual environment? but would that require me to install python on the system i want to install the app. and in case of react how can i build it from my PC to work on 32 bit PC. Thanks in advance. -
how to combine quires in django
i am creating a website where user will download videos , now i want to query the artist and it's videos, i already have one to many field but i have no idea how to do in views.py this is my models from django.db import models from embed_video.fields import EmbedVideoField # Create your models here. class Video(models.Model): video_author = models.CharField(default='Bongo Media', max_length=20) video_title = models.CharField(max_length=100) video_file = models.FileField(blank=True) video_image = models.ImageField(default='image.png') video_embed_link = EmbedVideoField(blank=True) video_descriptions = models.TextField(max_length=100, blank=True) video_pubdate = models.DateTimeField(auto_now=True) is_recommended = models.BooleanField(default=False) def __str__(self): return self.video_title class Artist(models.Model): artist_picture = models.ImageField(upload_to='media') artist_name = models.CharField(max_length=100) artist_songs = models.ForeignKey(Video, on_delete=models.CASCADE) def __str__(self): return self.artist_name and this is my views.py from django.shortcuts import render, get_object_or_404 from .models import Video, Artist # Create your views here. def home(request): artist = Artist.objects.all() videos = Video.objects.all().order_by('-video_pubdate') context = { 'videos': videos, 'artist': artist } return render(request, 'index.html', context) def detail(request, pk): video_detail = get_object_or_404(Video, pk=pk) context = { 'video_detail': video_detail } return render(request, 'detail.html', context) -
Adding django auth token to ajax call for external api
I have a django app (called Client) that makes an API call to another django app api (Master) and I'm logging in the users using OpenID Connect (via django-keycloak). My question is how to securely add the users access token to the header of an ajax call on the Client site to the Master site. The obvious solution is to have in my template something like:: "beforeSend": function (xhr) { xhr.setRequestHeader('Authorization', "Bearer {{ user.token }}"); }, But exposing the token seems like a bad idea. I could also create an api in the Client system that called the API in the Master system and added the token behind the scenes, but this is going to double the time for each round trip and also seems a bad idea. What is the best solution to this problem? -
How to unit test a file upload in Django?
I want to test a view that accepts .zip file as request. So far, I tried this: def test_upload_zip(self): with open('zip_file.zip', 'rb') as file: response = self.client.post(reverse(self.url), {'zip_file': file}, format='multipart') The data I am getting at the view when I do print(request.data) is: <QueryDict: {'zip_file': [<InMemoryUploadedFile: zip_file.zip (application/zip)>]}> But, for my actual request I want data in multipart like this: <QueryDict: {'zip_file': ['data:application/zip;base64,UEsDBBQAAAAIAK1xmF................AAAA=']}> In real request, I am not sending any content-type from my frontend. When I tried to put content_type='multipart/form-data in my test like this: def test_upload_zip(self): with open('zip_file.zip', 'rb') as file: response = self.client.post( reverse(self.url), {'zip_file': file}, content_type='multipart/form-data' ) I got this error: django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None What am I doing wrong, and how can I get the desired data in my request.data? -
How do i load css file into html in Django
I'm trying to create a Django app and i have made all the static settings like Settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'CricketTeamManagement/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' URLS.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Management.urls')) ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) I have also created a static folder in Main project folder and ran python manage.py collectstatic it created a new static folder outside and it has admin folder in it and sub folders like js,css,font,images and collectstatic collects the images and stores in this folder. I see static files are clearly working. All the models.py imagefields are uploaded to media folders and even that works. The Problem comes here My css files are not taking its styles and not altering my html elements. If I have the below code in html file the styling works and if i separate it to a css folder and create a css file by removing style tag it is not working. <style> body { background-color: powderblue; } h1 { color: blue; } p { color: red; } </style> when i saw the css file Not Found … -
Obtaining user's timezone
I'm making a website and need to know the user's timezone. I know I could simply ask them for it, but think some users may not know their timezone and feel there must be a more user-friendly kinda way to get it (rather that having users Google their timezone or something if they dont know it). Maybe there is a way to grab their timezone without having to specifically ask them? Or maybe there is a Django widget which displays a list of citys which the user can select theirs from and that will give me their timezone? Or maybe there's simply no user-friendlier way than simply asking them for it. Thank you. -
Django Choice Field rename first option
Django 3 Enum like field generates an addition option like <option value="" selected="">---------</option> How to Rename this like <option value="" selected="">Select an option</option> class Student(models.Model): class YearInSchool(models.IntegerChoices): FRESHMAN = 1, 'Freshman' SOPHOMORE = 2, 'Sophomore' year_in_school = models.IntegerField( choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) -
while filtering datatable server side Cannot resolve keyword 'priority' into field. Choices are: eventname, id, key, timestamp
I'm using django-rest-framework-datatables to filtering/pagination/sorting datatable when using rest-framework, it's working correctly with all fields except one, it's show error "Cannot resolve keyword 'priority' into field. Choices are: eventname, id, key" i think that the problem is: this field not appear in database table model class CachedEvent(models.Model): key = models.CharField(max_length=255) timestamp = models.DateTimeField() eventname = models.CharField(max_length=255) @property def priority(self): eventtype, created = EventType.objects.get_or_create( eventname=self.eventname ) return eventtype.priority viewSet: class EventViewSet(viewsets.ReadOnlyModelViewSet): queryset = CachedEvent.objects.all() serializer_class = CachedEventSerializer serializer: class CachedEventSerializer(serializers.ModelSerializer): id = serializers.CharField(source='original_id') class Meta: model = CachedEvent fields = ['key', 'timestamp', 'id', 'eventname', 'priority'] can help me please