Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to host in AWS. This line not working for me "sudo ln /etc/nginx/sites-available/django.conf /etc/nginx/sites-enabled/"
If i run sudo ln /etc/nginx/sites-available/django.conf /etc/nginx/sites-enabled/ It shows ln: failed to create hard link '/etc/nginx/sites-enabled/django.conf': File exists If i run sudo nginx -t It shows nginx: [emerg] open() "/etc/nginx/sites-enabled/example.conf" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 Not understanding the problem. Please help. -
Django login keeps returning invalid login user details
I'm new to Django and trying to create a simple user registration and login page. The login page keeps returning invalid user login details according to the code but the details are correct. -
IngerityError when Posting textarea content in django
I'm working on a simple project that requires a candidate to enter a description of his/herself. Since this requires lots of text, I use models.TextField() in models.py file and <textarea> tag in html. In models.py class Candidate(Person, models.Model): #Other fields description = models.TextField() def __str__(self): return self.name In Html <!---some stuff up--> <label for="candidate_description">Describe yourself</label> <textarea id="candidate_description" placeholder="Description..."></textarea> <!---some stuff below--> views.py file def regCandidate(request): if request.method == 'POST': candidate = Candidate( description=request.POST.get('candidate_description'), ) candidate.save() return render(request, 'Election/registerCandidate.html', {}) When I run the server and try to submit I get a IntegerityError. I have did some done some research and found out the error is occurs when django receives a null value when it is required. I'm a beginner at django and I'm using custom forms. Can anyone help explain why django is receiving a None and how to fix it. -
Ignoring validator errors django
For my code, I would like to introduce a set of custom warning messages based on some logical arguments on the data being posted. However, when using the django warning messages, the posted data through API gets saved into the database. I was wondering if it is possible to create a custom validator in the serializers that will respond with a post error message and be able to incorporate a parameter that will allow the user to bypass the error if they choose to do so? Almost all the research I have done points towards bad practice in bypassing validator errors and also requires going into the code to ignore it. Since these are custom errors that will not pose any data inconsistencies for the database, I would like to know more. -
I have created a Bio application in django.. how could i stop user to create duplicate Bio or remove create Bio button
Here is my model class Bio(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default="",null=True) name = models.CharField(max_length=200,null=True,blank=True) text = models.TextField(max_length=280) facebook = models.URLField(name='facebook',default=None,null=True) linkdin = models.URLField(name='linkdin',default=None,null=True) picture = models.ImageField(upload_to="bios/images", default="") def __str__(self): return self.name here is my views class BioCreateView(LoginRequiredMixin, View): template_name = 'bios/bio_form.html' form_class = BioForm success_url = reverse_lazy('bios:all') def get(self, request, pk=None) : form = BioForm() ctx = { 'form': form } return render(request, self.template_name, ctx) def post(self, request, pk=None) : form = BioForm(request.POST, request.FILES or None) if not form.is_valid() : ctx = {'form' : form} return render(request, self.template_name, ctx) here is my nav bar pic This the pic of Nav bar How can I stop the user to create duplicate Bio or remove that create bio button I already assigned an owner to that bio -
AttributeError: 'MetaDict' object has no attribute 'private_fields'
I am building a website in django. I am using Mongodb as a database. But I am getting an error "AttributeError: 'MetaDict' object has no attribute 'private_fields'" Whenever I run the server. Here is my code: model.py from django.db import models from mongoengine import * # # Create your models here. class User_Registration(Document): company_name=StringField(required=True,max_length=200) username=StringField(required=True,unique=True,max_length=15) password=StringField(required=True,unique=True,max_length=15) email=EmailField(required=True) forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('username','password','company_name','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } admin.py from django.contrib import admin from .models import User_Registration # Register your models here. admin.register(User_Registration) -
AWS not showing images on Django website deployed on heroku
I am trying to show my media files on a Django website hosted on Heroku via Amazon AWS S3. Currently, my settings for the AWS is: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} DEFAULT_FILE_STORAGE = 'register.storage_backends.MediaStorage' And in my storage_backends.py I have: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False When I open my website and inspect the images I can even the url seems to be correct: https://mybucket.s3.amazonaws.com/media/defaults/user/default_u_i.png?AWSAccessKeyId=... However, I still cannot see the image and it shows me the default thumbnail. What am I doing wrong here? I have uploaded the files to my bucket and I have checked multiple times and they are in the correct directory. Thanks for all the help in advance! -
Save recorded audio file in django from javascript ajax
I am trying to record audio file using javascript and save in django backend. Here is ajax function function uploadAudio( blob ) { var reader = new FileReader(); reader.onload = function(event){ var fd = {}; fd["data"] = event.target.result; $.ajax({ type: 'POST', url: 'testing/', data: fd, dataType: 'text' }).done(function(data) { console.log(data); document.getElementById("response").innerHTML=data; alert(data); }); }; Here is the function in views.py file @csrf_exempt def test(request): if request.is_ajax(): print("Yes, AJAX!") print(request.DATA ) else: print("Not Ajax") return render(request,'testing.html',{'print':'message'}) How can i save the data as audio file -
For angular-django webapp. How to setup cloudfront with s3 and beanstalk
I have an angular app for the frontend and Django for my backend. I am using beanstalk to deploy my Django app. What is the best way to make use of s3, CloudFront, route53, and beanstalk? angular hosting on s3 with Django being used for APIs angular in Django angular hosting on s3 with CloudFront while Django being used for APIs. Here 3rd method is much faster than the other two, I used the s3 bucket for hosting and directed cloudfront to s3 and then made a domain alias in route53 to CloudFront. it is working fine, but how to direct APIs to Django which is in the beanstalk? -
DeleteView not working with Ajax and Bootbox in Django
I'm using Bootbox along with Ajax to delete a listing in my app which is calling a DeleteView but after I confirm the deletion, nothing changes. View.py class FileDelete(DeleteView): model = Uploaded success_url = reverse_lazy('index') template_name = 'FileManagement/delete_file.html' Script <script> $(".delete-file").click(function () { var button = $(this); var id = button.attr("data-id"); console.log(id); bootbox.confirm("Are you sure you want to delete this file?", function (result) { if (result) { $.ajax({ method: "GET", url: "delete/" + id, success: function(){ } }); } }); }); </script> Urls.py url(r'^delete/(?P<pk>\d+)/$', views.FileDelete.as_view(), name="delete_file") I haven't finished the success part but it's still not deleting from the database. -
django operational error:attempt to writw a read only database
Request Method: POST Request URL: http://127.0.0.1:8000/basic_app/register/ Django Version: 3.0.8 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.8 Python Path: ['E:\DjangoProject1\learning_users', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Sun, 13 Sep 2020 16:04:41 +0000 -
I have a problem with python manage.py runserver
I am new with Django.. I flowed the steps in the main website I had installed pip, django and python . I had done everything but when I use the manage.py runserver I have an error and it wouldn't workenter image description here -
How to override Django many to many field add() and remove() methods
I am trying to set up a Facebook-like activity notification system using Django-Activity-Stream. The library provides a special action signal for creating the actions. According to the documentation, to trigger this action, You can do it through custom forms or by overriding predefined model methods, such as Model.save(). The logic is to simply import the action signal and send it with your actor, verb, target, and any other important arguments. For example, action.send(request.user, verb='reached level 10') However, I have an intermediate through model from which the action signal has to be sent. Since Model.save() method is not called when M2M add() or remove() methods are instead used, I want to know if there is any way to override those add() and remove() methods. I have thought about using M2M changed signals but soon realized that I wouldn't be able to easily access request.user in M2M changed signals. (I need to always know who request.user is to generate any useful activity notifications). I am concerned that accessing a user instance in a signal (by creating a separate middleware to store request.user in a thread, for example) may be costly and unsafe. If it is a reliable option, please tell me. -
Nested for in Django template with dynamic key
I have two query set results group = [{'id': 1, 'group1'}, {'id': 1, 'group2'}] sub_groups = [{1: [{'id': 1, 'sub_group1'}, {'id': 2, 'sub_group2'}], {2: [{'id': 3, 'sub_group3'}, {'id': 4, 'sub_group4'}] I need to show group and its sub group in template. So, I am looping through the groups and then I need to loop through sub_groups. I can't able to access the sub_groups by group id. Getting Could not parse the remainder: '[group.id]' from sub_groups[group.id]' <ul class="list-group"> {% for group in groups %} <li class="list-group-item">{{group.name}}</li> <ul> {% for sub_group in sub_groups[group.id] %} <li class="list-group-item">{{sub_group.name}}</li> {% endfor %} </ul> {% endfor %} -
django - urlpatterns giving 404 error for defined URLs
I have an application running on django. But I am getting error code 404 for some urls even though these are defined. from .views import check_secret_key # a function in views.py from .swagger_schema import SwaggerSchemaView # a class inheriting APIView from .kom.kom_writer import kom_status # a function urlpatterns = [ url(r'^docs/api-docs/', SwaggerSchemaView.as_view()), url(r'^nag/secret-key/', check_secret_key), url(r'^nag/kom-status/', kom_status), ] API curl http://localhost:9999/internal/docs/api-docs/ works fine but curl http://localhost:9999/internal/nag/kom-status/ and nag/secret-key fir 404 errror. Not FoundThe requested resource was not found on this server. I am not sure what is it that I am missing. Note: App was recently updated from DJango 1.8 to 1.11 and djangorestframework 3.2.5 to 3.5.3. Before that it was working fine. -
How do I pass a variable from Django's render method's context param to a javascript script on the frontend?
For context here, I am experienced with JavaScript but new to Django. Goal: Log the contents of a Django context variable in the browser's console using JavaScript. Specifically I'd like to log the contents of context in the Django render method I write below. In script.js I have console.log("hey", foo) which I expect to output the contents of a variable I pass into the Django render method. It gives me an error: Uncaught ReferenceError: foo is not defined I found two StackOverflow threads that seem to answer my question re: how to do this correctly. Neither worked. In (1) How can I pass my context variables to a javascript file in Django?, the answer from user Brian Neal claims I can deliver the Django variable into a javascript script at the top of the html file Django uses to render the page. Here is how I tried his answer: Django's render method says... def page(request): bar = "a" doohickey = "b" context = {'foo': bar,'baz': doohickey} return render(request, 'myPage.html',context=context) Then in myPage.html I say: {% load static %} {% block js %} <script>var foo = {{ foo|safe }}; console.log("aliens");</script> <script src="{% static 'js/script.js' %}" type="text/javascript" defer></script> {% endblock %} And … -
Djang-allauth signup issue on Heroku
before I get any deeper I’d just like to ask if any of you have experienced this issue. When in local environment logging and signing up redirection work fine. After deploying to Heroku, logging is fine but after signing up, redirection is not working and I’m getting Server Error 500. Unfortunately, Heroku logs don’t give me any closer description why it is so. It is just suspicious that locally is everything fine. Is there any known issue I should be aware of? I haven’t found anything online and already spent days digging. Many thanks for any help. -
Pythonanywhere django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments
i work in pythonanywhere and i have run a signup script - local it works without problems in pythonanywhere i get this error 2020-09-13 15:37:43,507: Internal Server Error: /signup1/ Traceback (most recent call last): File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/username/werkvertragrepo/werkvertrag/views.py", line 612, in signup1 text_body = render_to_string('acc_active_email.txt', merge_data) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 170, in render return self._render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/template/defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': 'NTA', 'token': 'aa5a2v-c248dcaea908540be1e8e3d5feff970f1'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A- Za-z]{1,20})/'] serverlogs 2020-09-13 15:37:43 {'user': <User: user@usermail.de>, 'domain': 'www.mywebsite.de', 'uid': 'NTA', 'token': 'aa5a2v-c248dcaea908540be1e8e3d5feff970f1'} 2020-09-13 15:37:43 Internal Server Error: /signup1/#012Traceback (most recent call l ast):#012 File "/home/username/.virtualenvs/myenv/lib/python3.6/site- packages/django/core/handlers/exception.py", … -
Can not able to serve media files on cpanel django
I build a website with Django and now hosting it. I used Whitenoise to serve images but only static ones shows up when debug is False. How can I serve media files uploaded by users too? Since it is my first development with Django detailed help would be much appreciated kind folk of the Stack. -
DJANGO WEB SOCKET WITHOUT CHANNELS
I will start django project for my bussiness (food), i focus on android app, but i want set my server with django. I want my android app use websocket for realtime food queue. EX: Android app -> server(django) -> merchant app(android) If i saw on tutorial always use django channels, but it not work on my project. I think, use django as webserver and make own websocket using python in same address (ip/port). So in this project, websocket only used for send data/notif to android app. In my mind, i use django for webserver and make tcp socket (not websocket) for send data to merchants. Thanksss... -
Cannot read property 'title' of null error when using Vue with Django Rest Framework When LimitOffsetPagination
As a test to use Vue to do a GET on a Django Rest Framework api url, it appears to work fine and I will get a listing of the tutorial title and rendering of the tutorial id in my links as expected: My html file: <li v-for="tutorial in tutorials"> <a href="/tutorial/[[ tutorial.id ]]/"> [[ tutorial.title | title ]] </a> at [[ tutorial.created ]] by [[ tutorial.author ]] </li> <script type="text/javascript"> let app = new Vue({ el: "#app", delimiters: ["[[", "]]"], data: { tutorials: {} }, mounted() { axios.get('/api/tutorials/').then(response => { this.tutorials = response.data }) } }); </script> As far as the rest api goes for Django, the serializer used in Django is: class TutorialSerializer(serializers.HyperlinkedModelSerializer): author = serializers.StringRelatedField() class Meta: model = Tutorial fields = [ "title", "description", "summary", "author", "graphic", "created", "modified", "is_approved", "is_published", "publish_date", ] But when I introduce a limit like so in settings.py: REST_FRAMEWORK = { ... 'DEFAULT_PAGINATION_CLASS': \ 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100, } I now get this in the console: TypeError: Cannot read property 'title' of null at eval (eval at Ya (vue:6), <anonymous>:3:331) at wn.vt [as _l] (vue:6) at wn.eval (eval at Ya (vue:6), <anonymous>:3:177) at wn.e._render (vue:6) at wn.r (vue:6) at fn.get (vue:6) at … -
How to count ManytoManyField within form in Django?
I have a form class called AttendanceForm. Inside that form I have a field called student which is a ManytoManyField with Student model. Also I set the widget of student field to CheckboxSelectMultiple. Now how can I count or know how many students or checkboxes in the form? I have tried {{ form.student.count }} within the template but it's not working. here is my models class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Attendance(models.Model): student = models.ManyToManyField(Student) my forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student',] widgets = {'student': forms.CheckboxSelectMultiple()} this is how i render form in template <form method="POST"> {% csrf_token %} <div class="row"> {% for form in form.student %} <div class="col-md-4"> <div class="row"> <h6 class="ml-2 mt-3" id="info-text"> {{ form.tag }} {{ form.choice_label }} </h6> </div> </div> {% endfor %} </div> <button type="submit">Check</button> </form> this is my view ( Im using form within the detailview) class Class_detailView(LoginRequiredMixin, FormMixin, DetailView): login_url = '/' model = Class form_class = AttendanceForm template_name = "attendance/content/teacher/class_detail.html" def get_success_url(self): return reverse('class_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) def form_valid(self, form): form.save() return super().form_valid(form) -
How to make relations between Mongodb Collection in Django
I am building an online job posting and searching website in django and using mongodb as a database. I am new to both of them. I am stuck at a point where I have to connect two mongodb documents with each others. The User_Registration model is for the sign_up and sign in of the user. Username is unique I am using this as a foreign key in the other model which is for the job that user has posted. When user sign in to the website he/she view the job that has been posted by him/her. Following is the models which I have made. Am I doing it the right way or not I am a bit confused with this, Kindly help me out. class User_Registration(models.Model): company_name=models.CharField(max_length=250,blank=False) username=models.CharField(max_length=10,primary_key=True,unique=True,blank=False) password=models.CharField(max_length=10,unique=True,blank=False) email=models.EmailField(max_length=250,blank=False) class New_Job(models.Model): username=models.ForeignKey(User_Registration,on_delete=models.CASCADE,null=True) company_name=models.CharField(blank=False, max_length=15) job_title=models.CharField(blank=False,max_length=15) job_description=models.TextField(blank=False,max_length=300) job_requirements=models.TextField(blank=False,max_length=500) company_logo=models.ImageField(blank=True,upload_to="images/") -
Bootbox with DeleteView can't find url in Django
I'm using Bootbox to delete a listing in my app but the url is not working. Here's the script: <script> $(".delete-file").click(function () { var button = $(this); let id = button.attr("data-id"); bootbox.confirm("Are you sure you want to delete this file?", function (result) { if (result) { $.ajax({ method: "GET", url: "{% url 'delete_file' pk=id %}", success: function(){ #success } }); } }); }); </script> Urls.py url(r'^delete/(?P<pk>\d+)/$', views.FileDelete.as_view(), name="delete_file"), Html: <a data-id="{{ file.pk }}"/ class="delete-file">Delete</a> I've added the dash / because Stack was rendering this as a button. The error I'm getting is: Reverse for 'delete_file' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['delete/(?P\d+)/$'] -
Django css problems wiht svg map
I have the following html with an svg: html code and the following css: body{ background-color: rgb(162, 190, 199); } .mapdiv{ width:28%; margin: auto; } .mapdiv path { fill: #e8e9d6; stroke: #000000; stroke-width:0.8px; transition: fill 0.3s; } .mapdiv :hover { fill:rgb(177, 38, 38); } Wich looks like this: However when use the same code in django and load static like this: {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>SVG Map</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> The css work fine except for the :hover .mapdiv :hover { fill:rgb(177, 38, 38); } Why?