Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
passing an object( field value ) into view and save it on a model
I have a field called 'rep' in my form, I want the view ,query the user that is equal to 'rep' and pass it to my view and save it into the recipient in the model : I tried the following line : form.instance.recipient = Message.objects.get(recipient=self.request.rep) but I get 'WSGIRequest' object has no attribute 'rep' View : view.py class compose(CreateView): model = Message form_class=ComposeForm template_name='django_messages/compose.html' def form_valid(self,form): # form.instance.recipient = Message.objects.get(recipient=self.request.rep) form.instance.sender =self.request.user return super(compose,self).form_valid(form) form.py class ComposeForm(forms.ModelForm): """ A simple default form for private messages. """ class Meta: model = Message # fields ='__all__' fields=['rep','subject','body',] #recipient = CommaSeparatedUserField(label=_(u"Recipient")) # subject = forms.CharField(label=_(u"Subject"), max_length=140) # subject='hello' body = forms.CharField(label=_(u"Body"), widget=forms.Textarea(attrs={'rows': '12', 'cols':'55'})) rep=forms.CharField() model.py class Message(models.Model): """ A private message from user to user """ subject = models.CharField(_("Subject"), max_length=140) body = models.TextField(_("Body")) sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_messages', verbose_name=_("Sender"), on_delete=models.PROTECT) recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=True, blank=True, verbose_name=_("Recipient"), on_delete=models.SET_NULL) parent_msg = models.ForeignKey('self', related_name='next_messages', null=True, blank=True, verbose_name=_("Parent message"), on_delete=models.SET_NULL) sent_at = models.DateTimeField(_("sent at"), null=True, blank=True) read_at = models.DateTimeField(_("read at"), null=True, blank=True) replied_at = models.DateTimeField(_("replied at"), null=True, blank=True) sender_deleted_at = models.DateTimeField(_("Sender deleted at"), null=True, blank=True) recipient_deleted_at = models.DateTimeField(_("Recipient deleted at"), null=True, blank=True) -
Bootstrap modal will not open - button is located in an underscorejs template
Here is the code from the underscore template. Note: the button data-target is correct. <ul class="unstyled list-unstyled"> <% _.each(events, function(event) { %> <li> <span class="pull-left event <%= event['class'] %>"></span>&nbsp; <button class="unschedule" data-toggle='modal' data-target='#remove-lesson-form' data-backdrop='static' data-selected-teacher="<%= event['teacher_name'] %>" data-lesson-id="<%= event['id'] %>" data-lesson-start="<%= event['start'] %>" data-lesson-end="<%= event['end'] %>"><i data-feather="x"></i></button>&nbsp;&nbsp;<a href="<%= event.url ? event.url : 'javascript:void(0)' %>" data-event-id="<%= event.id %>" data-event-class="<%= event['class'] %>" class="event-item"> <%= event.title %></a>&nbsp;&nbsp;<span>: <%= event['start_elf'] %> to <%= event['end_elf'] %></span> </li> <% }) %> </ul> This is the modal html from my django template, everything is fine here as well, as taken from bootstrap modal: <div class="modal" id="remove-lesson-form" tabindex="-1" role="dialog"> <div class="modal-dialog modal-sm" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Confirm Removal of Lesson</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div> <p id="rlessonDateTime"></p> <p id="rlessonTeacher"></p> </div> <button id="removeLessonButton">Unschedule</button> </div> <div class="modal-footer"> <button id="rmodalCloseButton" type="button" class="btn btn-secondary" data- dismiss="modal">Close</button> </div> </div> </div> </div> And here's the js code that handles the modal, everything seems fine here as well, so how come this modal isn't opening? Nothing is happening when the button is clicked. $('#remove-lesson-form').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); // Button that triggered the modal var selectedTeacher = button.attr("data-selected-teacher"); var lessonId = button.attr("data-lesson-id"); var … -
django-storage with S3: TypeError: a bytes-like object is required, not 'str'
I have a function that exports a CSV to S3: def export_csv(report_id): # MyModel has a JsonField called `json_data` items = MyModel.objects.all() data = [x.json_data for x in items] df = pd.DataFrame(data) file_buffer = io.StringIO() # QUOTE_ALL to avoid separators from throwing off columns df.to_csv( file_buffer, index=False, encoding='utf-8', quotechar='"', quoting=csv.QUOTE_ALL, ) report.report_data_file.save( "data.csv", ContentFile(file_buffer.getvalue()) ) I'm using the following FieldField: class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False class Report(BaseModel): ... report_data_file = models.FileField( storage=PrivateMediaStorage(), upload_to=export_location, null=True, blank=True, ) This is working fine in my local environment, where PrivateMediaStorage is defined as class PrivateMediaStorage(FileSystemStorage): pass In production, where I am using django-storages, I am seeing the following error when running this function: TypeError: a bytes-like object is required, not 'str' -
Calling Django JSON API from Template
Say I have a django app called App1 and a django app called App2. App1 has an endpoint called getJson() which returns a json object. Now, in App2, I have an endpoint which renders an html template. In the html template I have a button and when the button is clicked, I want to call App1's getJson function. Is there a better way to do this than doing a get request in the JS of the template? If so, how? Thanks! -
getting an error message when trying to run django project locally
I'm trying to run a project locally. I cloned the repo and installed django and set up a virtual environment but when I run the command "python manage.py runserver" in my virtual environment I'm getting this message " .env doesn't exist. If you're not configuring your environment seperately create one" I checked and the .env file is in the directory that my virtual environment is in so I'm not sure why it's saying it doesn't exist. -
How to post pictures on django?
I have been trying to make my code able to post images but when I try to create the post, the part that is supposed to let me uploud a picture, the form of the picture doesn't appear. I was wondering if there is any way to make the code work, ther might be something wrong int he create view or the create.html, maybe urls. views.py def create(request): if request.method == 'POST': created_date = timezone.now() header1 = request.POST['header'] content1 = request.POST['content'] user = request.user form = PostForm(instance=user) context2 = {"form": form} created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user) created_obj.save() print('create created') return redirect('home', context2) else: print('create not created') return render(request, 'create.html') models.py class Create(models.Model): added_date = models.DateTimeField() title = models.CharField(max_length=200) content = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, upload_to='images/') user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1) 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' urls.py urlpatterns = [ path('', views.home, name='home'), path('create', views.create, name='create'), ] forms.py class PostForm(ModelForm): class Meta: model = Create fields = ['image'] exclude = ['user'] create.html {% extends 'home.html' %} {% block body %} <div style="margin-top: 200px; margin-left:200px;"> <form action="create" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="header" placeholder="Add here..."> <input type="text" … -
Django 3 ModelChoiceField stays empty
I have this form with two fields. The second field should be populated with the names of existing projects but when rendered is stays empty and no dropdown appears. class UploadRawForm(forms.ModelForm): orig_file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) project = forms.ModelChoiceField(queryset=Project.objects.all(), required=True) class Meta: model = RawFile fields = ['orig_file', 'project'] Template: {% extends 'base.html' %} {% block title %}File upload{% endblock %} {% block content %} <h1> {{ name }} </h1> <form method="POST" id="upload-form" class="upload-form" enctype="multipart/form-data" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Upload</button> </form> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} {% endif %} {% endblock %} -
How can I update a Django user's password from inside Postgres?
I'd like to reset a user password, but only have access to the Postgres database. Dropping in plaintext doesn't work, and the hashing process for Django appears to be too complex to replicate. Any thoughts?