Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: problem with format when using ajax query (string/Json)
I try to send data with ajax but format is string and I need JSon (or formated data) Data to be send are displayed in an htlm table. I loop in all my row to collect all data to be send using ajax. But I have error when I try to make a JSON object when using JSON.Parse(new_parameters). If use new_parameters in my ajax query, I get False in my ajax view... If I "stringify" new_parameters to use it in my ajax query, I get data in my ajax view but in string format... That's mean the way I construct new_parameters is not the good way... var parameters = {}; var current_parameters = []; var new_parameters = []; // Collect data from html data when user click on "Modify settings" button $(document).on('click', '#modifier', function(event) { event.preventDefault(); $('#table_parametrage tr').each(function() { var parameter = {}; $(this).find('td div').each (function() { parameter[$(this).attr("col_name")] = $(this).eq(0).html(); }); new_parameters.push(parameter); }); new_parameters.shift(); // requête ajax > start // parameters = JSON.parse(new_parameters, null, 2); console.log(new_parameters); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does … -
How to create multilink django model?
if you help I will be very grateful to you! In general, I decided to consolidate the knowledge of django by creating my own project and chose that I was implementing a multi-link service such as 'taplink' and so on, there were a lot of them. Just started and was immediately confused. Essence of the question: I need to display in the template all the links that the user selected and decided to add. Everything would be fine, but each link has its own unique css classes and unique href attributes. First I decided to create a model: class Links(models.Model): # messengers whatsapp = models.CharField(max_length=50, blank=True) telegram = models.CharField(max_length=50, blank=True) viber = models.CharField(max_length=50, blank=True) fbmessenger = models.CharField(max_length=50, blank=True) skype = models.CharField(max_length=50, blank=True) but realized that this is wrong. Then created other models, for example: class InstagramModel(models.Model): #title = models.CharField(max_length=100) help_text = "Введите ваш логин (без @)" login = models.CharField(max_length=100) choose = models.BooleanField(default=False) style = models.TextField(default='fab fa-instagram instagram') url = models.URLField(default='https://www.instagram.com/') class WhatsappModel(models.Model): #title = models.CharField(max_length=100) help_text = "Введите ваш номер телефона начиная с цифры 7 или 8 (без +7)" login = models.CharField(max_length=100) choose = models.BooleanField(default=False) style = models.TextField(default='fab fa-whatsapp whatsapp') url = models.URLField(default='https://wa.me/') here is view file def card_links (request): … -
python built in server not loading css file
Why does not it work in Django? There is error in the browser like that. its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. In file html there is : <link rel="stylesheet" href="{% static 'nowy.css' %}"> In settings.py it looks like: STATIC_URL = '/static/' Dirs are: app > static > nowy.css I can't find where is the mistake. -
Django , C# User Authentication,PostgreSQL
I am new in Django Web Development and i am in a process of learning. So i have some questions. I have build a simple register / login system in Django that is connected to a PostgreSQL local database.And all work fine registration/login function, now i want to develop a log in c# desktop application where i will use the PostgreSQL Database that django is using for saving the registered users. So since the password are encrypted i cant just do "Select user from user_auth where password='test' and email='test@test.com'". So is there any library for c# that i can use to encrypted the password and send the request, or i need to take another approach .... to learn Django REST and do all this with HTTP requests. -
Transport Endpoint is not connected - apache hosted django app
I just deployed my first Django application on my apache web server and I ran into follwing problem: I configured my django app that you can login with your ad credentials. If I run the server via development web server (python manage.py runserver) it works just fine. But if my apache is hosting the app, it says Caught LDAPError while authenticating adaccount: SERVER_DOWN({'desc': "Can't contact LDAP server", 'errno': 107, 'info': 'Transport endpoint is not connected'},) I know it must the something with the apache. I tried 3 settings KeepAlive On, MaxKeepAliveRequests and KeepAliveTimout but no success. Any Idea? Here is my Settings.py import os import ldap os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django #django.setup() from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = 'ldap://dnsOfLDAP:3268' AUTH_LDAP_BIND_DN = "serviceaccount" AUTH_LDAP_BIND_PASSWORD = "some***" AUTH_LDAP_USER_SEARCH = LDAPSearch( "searchScope", ldap.SCOPE_SUBTREE, "sAMAccountName=%(user)s" ) AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "UserPrincipalName", } from django_auth_ldap.config import ActiveDirectoryGroupType AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "searchScope", ldap.SCOPE_SUBTREE, "(objectCategory=Group)" ) AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType(name_attr="cn") AUTH_LDAP_USER_FLAGS_BY_GROUP = { #"is_active": "activeGroup", "is_staff": "staffGroup", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 1 # 1 hour cache #ohne apache auth backend AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', ] #mit apache auth backend # AUTHENTICATION_BACKENDS = [ # 'django.contrib.auth.backends.RemoteUserBackend', # … -
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?