Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send PUT Request from Tabulator to Django REST Endpoint (currently getting 403 Error)
I am using Tabulator with Django to edit a model. I am getting a 403 error when I send a PUT call to an API endpoint which works fine via Postman. My question is: how can I correctly make a call from Tabulator to do this? I am pretty new at this stuff (both Django and especially JavaScript) so apologies if I've missed something basic. The html file is a Django template. The table is populated via an Ajax call to a REST endpoint (provided using Django REST Framework). This GET request works fine and the table populates. I have another endpoint for updates which does not require authentication. This works fine using Postman or using the Python request call below to test, however I cannot get it to work from Tabulator using the table.setData command. import requests apiURL = 'http://localhost:8000/mymodel/api/cust_listapi/2/' payload = {"name":"JAMES EARL JONES"} response = requests.put(apiURL,data=payload) My tabulator code is below. The variable ajaxConfigPut is set to override the default form method used by Tabulator, and changed it to json, and also used a fetch parameter to force omit any credentials. This is then used in the table.setData call later on (table.setData(updateurl, updateData, ajaxConfigPut);). <div id="example-table"></div> <script … -
How can I connect to the database after starting a Django project?
I thought of using a Django project as client for a database. The database shall be run in a local network. The Django project is run on local dev machines. Usually one would inject the database connection meta-data (NAME, ENGINE, USER, PASSWORD of DATABASES dict in settings.py) via env vars during Django project startup. Is there a workaround to prevent Django from trying to connect to the database during startup and allow to define the database connection meta-data somehow different during Django project runtime? -
Serving a Specific Section of Django Paths using Nginx
I'm using Gunicorn and Nginx as a proxy to serve Django. However, I wanna limit the paths that are processed through Django to a specific subdirectory. My Django paths are: /: Landing Page /rest/...: REST API Endpoints /admin/...: Admin Panel /dashboard/...: Dashboard /uplodas/...: Media Files (Uploaded by Users) I want to replace the Landing Page and the Dashboard pages with static files generated by Nuxt.js. I've already seen a few solutions where the entire Django system is served from a sub-directory, but I'm trying to see if I can serve /admin, /rest, and /uploads subdirectories in the root, and have Nginx fall back to Nuxt.js static files for the rest of the paths. -
Generating PDF invoice using Template file in Python
I am developing an Invoice application in Django web framework. In one of my previous application developed in PHP, I created an invoice template file in Microsoft word and populated the fields using PHPOffice library. It worked really well since I didn't have to worry about the formatting in pdf. All the formatting was done beforehand in the template file itself. $report_data = new \PhpOffice\PhpWord\TemplateProcessor($template_File); $report_data->setValue('INVOICENUMBER', $invoice_id); $report_data->setValue('INVOICEDATE', date('M j,Y', $invoice_date)); I was wondering if a similar solution exists in Python? Any useful pointers along the same lines would be really helpful. -
Why DJANGO roll back my transaction even I hide the IntegrityError?
I am using Django 2.11. My Database is Mysql 5.6.23 Here are the code I want to ask: with transaction.atomic(): MyModel.objects.create(name='some_name') some_other_func() The some_other_func use a try catch statement to catch IntegrityError and ignore it But I notice that when IntegrityError happend, the whole transaction being rolled back. My questions are: How does the transaction sense the Error since I deliberately ignored it ? Why django rolle back the transaction since I deliberate the error -
Error: invalid syntax in INSERT INTO statement (using postgresql and django)
I'm trying to make my database to make a jeopardy style game. I've made my app's model and migrated it in django, and am now trying to populate the database using a python program. However, I'm getting an error in the INSERT INTO statement, with the carat pointing to the 'O' in into. What's also strange is that if I copy and paste the insert into statement and first statement of data and paste them while I'm in the database shell, the insert works no problem. Could someone please tell me what could be the problem here? Note: I know the python file cuts off to the right, but I promise that the end of the lines of data ends with the proper parenthesis, comma, etc. [Successful insertion in database shell][1] [Error message][2] [My python file][3] -
Django Ajax 'GET' return only strings
I am trying to get some data from my database using ajax, and iterate it. for some reason, I get a long string, and not object that I can iterate. views.py def postHog(request): if request.method == 'GET': pk = request.GET['megama'] megama = Speciality.objects.get(id=pk) hog = Submain.objects.filter(speciality=megama) hogback = [] for i in hog: if (i.image): hogback.append({"name": i.name, "desc": i.desc, "image": i.image.url}) else: hogback.append({"name": i.name, "desc": i.desc, "image": "None"}) response_data=json.dumps(hogback,ensure_ascii=False) return JsonResponse({'hogback': response_data}, status=200,content_type="application/json") urls.py path(r'megamas/', views.postHog, name="post_hog"), myjs.js $(".btnsmain").click(function () { $.ajax({ type: 'GET', url: "/megamas", data:{ megama:$("#id_main").val() }, success:function (data) { $.each(data.hogback, function (index,element) { alert(index,element.name); }); }, error: function (data) { alert("not good"); } }) }); if i use alert(hogback[0]) i get the "[" its like i am getting back strings and not the list and dict objects. thank you! -
Django Van JS: css template refresh
I am using the django framework trying to use Van JS ClassList to toggle a CSS class to my html tag, system settings of mine (windows 64 bit, Hp PC, Apache Xampp, Pycharm Community Edition) I notice a problem, which as I go through the process: 1 modify css file in pycharm. 2 kill the server. 3 reload the page. I find that the css file in static folder has not be modified in my browser inspect element. but on my PC, it is modified. can anyone suggest a reason or a better way of achieve this. I will be so glad if you offer some help. -
Setup Django-SHOP on Divio
Tell me, is it possible to install django-shop on Divio servers? How can I do that? I can’t imagine how this can be done, because the structure of files in divio is different from the structure of ordinary django projects -
Show PDF preview dynamically in jQuery
I am building a Django web application. I am referring to InvoiceNinja application for invoice creation which shows the preview of the invoice as an embed object. As I change any field while creating the invoice, the pdf preview updates automatically. I am not sure how this done(referred to the attached document). I don't think, they are creating a PDF document(refer to the screenshot). Any idea as to how to do it? Any useful pointers would be really helpful. -
Why I am facing CORS issue for some django rest framework API?
I am working on a project where I am using React as frontend and Django as a backend language. Lately, I am facing this weird issue where I am having CORS policy issues for some endpoints of Django rest framework APIs but for some API it's working absolutely fine. Can someone please help me out why exactly I am facing this CORS issue for some APIs? ``` ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ... 'corsheaders', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ('http://localhost:3000',) MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] ``` -
How to form different urls based on value of for loop in django template?
{% for bus in buses %} <form action = "{{bus.id}}"> <label>{{bus.id}}</label> <label>{{bus.departure_time}}</label> <button type = "submit">book now</button> {% endfor %} this is my template format, i am printing a number of buses using for loop when a user clicks on book now i want the urls to be the busID on which bus user clicks. but it's forming the url based on last value (bus.id) of for loop. is there any fix for this? -
How to reference a foreign key in html django
I am trying to reference a foreign key named data_source in ProtocolUserCredentials in my html template. When I run this it just comes up with a blank header for each cred object in creds, and not the username and password. Running if cred.protocoldatasource__data_source doesn't work. If I run a non-foreign key in the conditional similar to if cred.data_source_username, and then the password in the if <h4> username: {{ cred.data_source_password }} </h4>, it'll display with no error. <div class="container" style="border:1px solid #cecece;"> {% for cred in creds %} <div class="jumbotron jumbotron-fluid"> <div class="container"> {% if cred.protocoldatasource__data_source = 'Demonstration Protocol, External Identifiers, demo_exrecs' %} <h4> username: {{ cred.data_source_username }} </h4> <h4> password: {{ cred.data_source_password }} </h4> {% endif %} </div> </div> {% endfor %} </div> {% endblock %} def post(self, request): post_data = request.POST self.user = post_data['user'] self.protocol_user = post_data['protocol_user'] self.protocol = post_data['protocol'] self.data_source = post_data['data_source'] self.data_source_username = post_data['data_source_username'] self.data_source_password = post_data['data_source_password'] context = {} if 'submit_nautilus_creds' in post_data: form = self.processCredsForm(request) creds = ProtocolUserCredentials.objects.all() context = {'form': form, 'creds': creds} return render(request, 'confirm_nautilus_creds.html', context) class ProtocolUserCredentials(Base): protocol = models.ForeignKey(Protocol, verbose_name='Protocol') data_source = models.ForeignKey( ProtocolDataSource, verbose_name='Protocol Data Source') user = models.ForeignKey(User, verbose_name='User') protocol_user = models.ForeignKey( ProtocolUser, verbose_name='Protocol User') data_source_username = models.CharField( max_length=50, … -
Django-tinymce {#advanced_dlg.link_title}
In my Django blog, I get the following empty pop-up when I click on the link button in the TinyMCE editor. Has anyone else encountered this problem? Thank you! -
Why is Django on Google App Engine is very slow?
I have Django server deployed on Google App Engine, I am doing simple GET request which is taking around 2 seconds, while the same request takes around 300ms when run locally. Both servers are using the same mysql database on Google Cloud SQL. I am testing this on my home wifi (100mbps), so don't think it's a network issue, anyway the payload is pretty small (2.5kb). Anyone seen this slowness when deployed to Google App Engine? Is there any configuration change I could make to Google App Engine, that would make it faster? Any suggestions are welcome. Thanks! -
Show related data inside another modals class-based view
I am working on a project that manages different servers and the whitelist associated with each server. I would like to show the associated whitelist for the server in the server's DetailView page. Right now, I have this sort of working by simply calling the Django HTML escapes for the whitelist objects in my template. This works okay but I would like to enable the end user to create/update/delete these whitelists from the respective server detail pages. Here are the two models: #from models.py class Server(models.Model): server_url = models.CharField(max_length=100, unique=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) sw_vendor = models.CharField(max_length=20, choices=SW_VENDORS_CHOICES) sw_version = models.CharField(max_length = 10) pb_method = models.CharField(max_length = 20, choices = PB_METHOD_CHOICES) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) history = HistoricalRecords() def __str__(self): return self.server_url def get_absolute_url(self): return reverse('proxyadmin-server-detail', kwargs={'pk': self.pk}) #and class Whitelist(models.Model): reference = models.CharField(max_length=20, unique=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) server = models.OneToOneField(Server, on_delete=models.CASCADE) applications = models.ManyToManyField('Application') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.reference I tried creating CBVs for Whitelist and referencing it in the template but ran into a Reverse URL error filtering because I could not figure out how to filter the whitelist by any of the Server field. Any help would be greatly appreciated! Let me … -
python populate.py wont populate my database
After writing the following code and expecting the output to be an updated database with random names, websites, etc., I get no error message and no updated database import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'First_project.settings') import django django.setup() import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.object.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = webpage.objects.get_or_create(topic=top, url=fake_ur, name=fake_name)[0] acc_rec = AccessRecord.object.get_or_create(name=webpg,date=fake_date)[0] if __name__ == ' __main__': print("populate") populate(20) print("populating complete!") please what do I do? -
RuntimeError: Model class users.models.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
This is my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'pages', 'register', 'crispy_forms' ] And my forms.py file: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] And finally my models.py file: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I'm trying to create a User Profile Update page and i'm facing an error with respect to importing the user profile model. Not sure why i'm facing this issue and looked digged a lot into making changes in the 'Installed Apps' and 'models'. How do I resolve this error. Any help would be deeply appreciated. Thanks. -
How to update empty/null value via django put method?
I am using Django API put method for updating records from a form. It updates all except empty value. for example: if I change name "anik" to "apanik" it works! But when I am trying to make empty that name field like name "anik" to " " , api dont take thake empty value. So what i did I wrot a script like: if (!name){ $("#name").val(' '); } It updates to empty in the database. But in the same method when I am trying to update a dropdown with no choice API did not take that. Like if (!industry_expertise){ $("#industry_expertise").val(' '); } Like here #industry_expertise is an ID of dropdown menu.So what I am trying to do if have no choice to dropdown it should change default to in the database too. How to do it -
How to perform session in django?
I have created an application with login and logout. But after clicking back it goes to the user name and pass form page.. it doesn't destroy the session.. how is it possible to destroy session in django?? -
ajax in django success function is not working
I am new in ajax as well as Django. I try to put ajax in my code to check that in the signup page if some user is already having one email then that email can't use for new users and disable the button else if the email does not exist then the user can be created. ajaxCode $(document).on('blur', 'input[name="email"]', function(){ $.ajax({ type:'POST', url:'/stock/checkemail/', data:{ email:$("#email").val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ $('input[type="submit"]').attr('disabled', 'true') }, failure:function(){ $('input[type="submit"]').removeAttr('disabled'); } }) }); url.py path('checkemail/',Emailser.as_view()), views.py class Emailser(View): def post(self, request): em = request.POST['email'] print(em) try: user = User.objects.get(email=em) return HttpResponse('true') except: return HttpResponse('false') In views.py print(em) is also printing mail that type in field but don't know why is not working. template {% extends 'base.html' %} {% block content %} {% load static %} <div> <h2>Sign Up</h2> {% if error %} {{error}} <br/> {% endif %} <form method="post" id="signup" > {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" >Signup</button> </form> </div> <script src="{% static 'assets/signup.js' %}" ></script> {% endblock %} -
ModuleNotFoundError: No module named 'app.myapp' In Django
File "C:\Users\user\app-rest\app\app\urls.py", line 4, in <module> from app.myapp.views import UserViewSet ModuleNotFoundError: No module named 'app.myapp' Not sure what the issue is but when I comment out the import and the related views on my URL page, it works. Could it be from the folder being app\app\url being the same name twice? if it is how can I change that without screwing up the rest of my code? settings are set up right because it usually works. Thank everyone in advance. -
How can I deploy project on EC2 with nginx?
I'm trying to deploy a project on aws ec2 but the project is not instead I see the index of nginx django.conf server { listen 80; server_name 54.186.237.246; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/REST-API/app.sock; } } gunicorn.conf [program:gunicorn] directory=/home/ubuntu/REST-API command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/REST-API/app.sock itzamna.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn -
Read and add data to a database in real time for a video processing app with Django
I want to create a Django website that will make computer vision tasks on a video and show the results on a webpage in real time (frame by frame). Each frame is grabbed from the video and sent to a function in the back-end that will do computer vision tasks then store the output (some numbers) in a database. Once that happens a section of the front end will get updated automatically without refreshing the page since the user will be seeing the video and the data from the database in real time. So I already have the video showing on the webpage, and the computer vision function grabbing and processing each frame in the back (without storing anything in the database just yet). Can someone specify which front end frameworks that will make this possible / which technologies to use in order to store and grab data from the database in real time? Or any things in general that I might be missing? -
Django: How to validate uniqueness of user uploaded files using hashes
I am trying to find an elegant solution to check whether an user uploaded file already exists. A user uploads a file using a Submission Form, just including the file field. This form should compute the hash for the file, add it to the Submission instance, and compute validation checks there. If the uniqueness constraint on the hash value is violated, this should raise a validation error, so that the form can print an adequate error message. The relevant files: # models.py class Submission(models.Model): uploaded = models.DateTimeField(auto_now_add=True, unique=True) exercise = models.ForeignKey(Exercise, on_delete=models.PROTECT) file_sha1 = models.CharField(max_length=40, editable=False, unique=True) file = models.FileField( upload_to=<... file saving ...>, validators=[ <... validators ...> ], ) # forms.py class SubmissionForm(forms.models.ModelForm): class Meta: model = Submission fields = ("file",) widget = {"file": forms.FileField()} error_messages = { "file": { <...error message codes + messages...> "duplicate": DUPLICATE_ERROR, } } def save(self, exercise): self.instance.exercise = exercise return super().save() In addition, I have a _generate_sha1(file) method hashing a file. I saw couple of solutions to this problem using validation in views.py but I believe that is not the right place for it. I looked into clean() and clean_file() but I did not manage to get it working. Thanks for your help.