Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery worker stops working after sending a task
A basic test on a Django/celery environment produce a restarting of the worker every time a new task is sent. celery==4.1.1 Django==1.10.3 redis==3.0.1 -
Creating migrations for a reusable Django app
I am writing a reusable Django app and having problems creating migrations. I have looked at this question, and I'm still confused. I have the following sort of directory structure: django-mycleverapp/ django-mycleverapp/django_mycleverapp/ django-mycleverapp/django_mycleverapp/__init__.py django-mycleverapp/django_mycleverapp/apps.py django-mycleverapp/django_mycleverapp/models.py django-mycleverapp/django_mycleverapp/urls.py django-mycleverapp/django_mycleverapp/views.py django-mycleverapp/example/ django-mycleverapp/example/manage.py django-mycleverapp/example/example/ django-mycleverapp/example/example/__init__.py django-mycleverapp/example/example/settings.py django-mycleverapp/example/example/urls.py django-mycleverapp/setup.py As you can see, the directory "django_mycleverapp" contains my reusable app and the directory "example" contains a test project. I include the models of "django_mycleverapp" in the INSTALLED_APPS section of the settings for "example". However, running python ~/example/manage.py makemigrations django_mycleverapp doesn't build any migrations. Any suggestions? How am I meant to have a test project that will build migrations in "/django-mycleverapp/django_mycleverapp/migrations"? -
csrf_token is forbidden in second form submmition
i am new in django and i create a resend email page in my web all is work porfectly but if i give wrong email in input box it gives error email is invalid! then secodly i have put correct email in input b0x then it shows error csrf token is forbidden this is my resendemail.html <div class="main"> <section class="signup"> <div class="container"> <div class="signup-content"> <form method="POST" id="signup-form" class="login-form" > <h2 class="form-title">Resend Email</h2> <div class="form-group"> <input required minlength="4" maxlength="50" value="{{email}}" type="email" class="form-input" name="email" id="email" placeholder="Enter Your Registerd Email"/> {% csrf_token %} <div style="margin: 10px 0px; color: #D8000C; line-height: 40px; text-align: center; background-color: #FFD2D2;">{{ error }} </div> <img src="{% static 'img/loader.gif' %}" id="gif" style="display: none; margin: 0 auto; width: 80px; "> <div class="form-group" id="submit"> <input type="submit" name="submit" id="submit" class="form-submit" value="Resend"/> </div> </form> <p class="loginhere"> <a href="{% url 'login' %}" class="loginhere-link">Log In </a> &nbsp; Or &nbsp; <a href="{% url 'resend_email' %}" class="loginhere-link">Forgot Password </a> </p> </div> </div> </section> </div> <!-- JS --> <script src={% static "js/jquery.min.js" %}></script> <script src={% static "js/script.main.js" %}></script> <script src={% static "js/main.js" %}></script> <script> $('#signup-form').submit(function() { $('#gif').css('display', 'flex'); $('#submit').css('display', 'none'); }); </script> <script> $(window).load(function() { $('.preloader').fadeOut('slow'); }); </script> this is my view function def resend_email(request): if request.method == 'POST': … -
Middleware EXEMPT URLS for Access Control List
I am trying to redirect users who don't have permission to see that page. In my database i have saved url names . Example - company_list path('company/list', CompanyListView.as_view(), name='company_list'), Now i am using EXEMPT_URLS where url names are saved and user is exempted for those urls. EXEMPT_URLS = [ 'login', 'logout', 'superadmin_dashboard', 'admin_dashboard', ] class PermissionRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') current_url = resolve(request.path_info).url_name print(request.path_info) if request.user.is_authenticated and current_url not in EXEMPT_URLS : if request.user.userprofile.user_role_id == 1: return redirect('superadmin_dashboard') else: return redirect('admin_dashboard') Now the problem come here. Like i am adding a company and its logo. and when i m going to company_list it is showing me the list but not images. "GET /media/user_profiles/logo_L7T5FKg.png HTTP/1.1" 302 I founded the problem, when i commented def process_view() it is showing me images in my template. But when i uncomment it it does not showing images. Basically my middleware is blocking that "GET /media/user_profiles/logo_L7T5FKg.png HTTP/1.1" 302. How can i that image url name and put in EXEMPT_URLS -
Django mail failed to send mail to icloud mail id
I used the below code from django.core.mail import EmailMessage email = EmailMessage('Hello', 'World', to=['user@gmail.com']) email.send() the message is sent when I used any other mail except icloud, the code says the message has been sent but I didn't receive any message. Is this Django issue or some policies of icloud is blocking it? -
Django_1.11 from framework
I am working on e-learning website with django.I have to make validations on my module that without paying . Student can't access the courses but can access the demo video means to be module 1 of the course..plzz help#python_django1.11 -
Storing multiple values into a single field in mysql database that preserve order in Django
I've been trying to build a Tutorial system that we usually see on websites. Like the ones we click next -> next -> previous etc to read. All Posts are stored in a table(model) called Post. Basically like a pool of post objects. Post.objects.all() will return all the posts. Now there's another Table(model) called Tutorial That will store the following, class Tutorial(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tutorial_heading = models.CharField(max_length=100) tutorial_summary = models.CharField(max_length=300) series = models.CharField(max_length=40) # <---- Here [10,11,12] ... Here entries in this series field are post_ids stored as a string representation of a list. example: series will have [10,11,12] where 10, 11 and 12 are post_id that correspond to their respective entries in the Post table. So my table entry for Tutorial model looks like this. id heading summary series "5" "Series 3 Tutorial" "lorem on ullt consequat." "[12, 13, 14]" So I just read the series field and get all the Posts with the ids in this list then display them using pagination in Django. Now, I've read from several stackoverflow posts that having multiple entries in a single field is a bad idea. And having this relationship to span over multiple tables as a mapping is … -
Django - how to create a file and save it to a field in ModelSerializer
I have a model with a FileField 'file_test' I would like to manually create a file and assign in to 'file_test' in the serializer Below are my code, would like some help. Thanks class Test(models.Model): file_test = models.FileField(storage=OverwriteStorage(), upload_to=_get_landmark_upload_path, max_length=100, blank=True) class TestSerializer(serializers.ModelSerializer): test = serializers.CharField(write_only=True, required=True) class Meta: model = Test fields = ('test') def save(self, *args, **kwargs): self.file_test.save('test.txt', ContentFile(self.validated_data['test'])) return super().save(*args, **kwargs) -
The view students.views.addgrregister didn't return an HttpResponse object. It returned None instead
ValueError at /students/addgrregister/ i am trying to add students in gr_register but its giving an error due to this error the code is not working models.py class gr_register(models.Model): Gender_Choices = ( ('M', 'Male'), ('FM', 'Female'), ) Status_Choices = ( ('P', 'Present'), ('FM', 'Left'), ) gr_no = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) date_birth = models.DateField(null=True) classes_A = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_A", default=1, verbose_name="Class of Admission") sections_A = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_A", default=1, verbose_name="Section of Admission") gender = models.CharField(max_length=10, choices=Gender_Choices) classes_C = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_C", verbose_name="Current Class") sections_C = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_C", verbose_name="Current Section") address = models.CharField(max_length=100, null=True, verbose_name="Home Address") area_code = models.ForeignKey(Area, on_delete=models.CASCADE, verbose_name="Area") status = models.CharField(max_length=10, choices=Status_Choices, default='P') class Meta: ordering = ('gr_no',) def __str__(self): return self.first_name views.py from django.shortcuts import get_object_or_404, render, redirect def addgrregister(request): if request.method == 'POST': form = gr_registerForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = gr_registerForm() return render(request, 'students/addgrregister.html', {'form': form}) forms.py from django import forms from django.forms import ModelChoiceField, ModelForm from .models import * class gr_registerForm(ModelForm): classes_A = forms.ModelChoiceField(queryset=Classes.objects.all()) sections_A = forms.ModelChoiceField(queryset=Sections.objects.all()) classes_C = forms.ModelChoiceField(queryset=Classes.objects.all()) sections_C = forms.ModelChoiceField(queryset=Sections.objects.all()) area_code = forms.ModelChoiceField(queryset=Area.objects.all()) class Meta: model = gr_register fields = '__all__' def init(self, *args, **kwargs): forms.ModelForm.init(self, *args, **kwargs) -
pipenv EC2 set up guide?
It is very confusing to set up from a GitHub to a free EC2.t2, all the tutorials I found use virtualenv but I want to use pipenv, it can be a problem because some of the configurations from nginx link directly to the virtual environment files Can anyone provide a set up/kick-starting guide for EC2 with Django that: makes use of environmental variables for secret key uses nginx and gunicorn Outputs a hello world -
How to Integrate Paytm Gateway with python3 in Wallet of Website?
I am making a website using Django with wallet feature and want to integrate Paytm gateway with python but have no idea how to do I also had download paytmkit. -
Django 1.11 How to execute a code only once that save a data to DB using Django model
I am geting started with Django Rest Framework, my app is based on Django 1.11 version. I have a model name Test. Now I need to populate this model once only when the app starts up, which will recieve a data from a REST API call. I read about app.ready() however I coudn't figure out how to wire up these steps. So basically when the app starts up : Check if there is some data present in the table A, preferably by calling objects.count(). If yes do nothing. If not, call the third party API and save the model. This can also be done on Admin? -
What are the pros and cons of scheduling celery beat periodic tasks at 0.1 seconds?
My application requires to run periodic tasks(task to check a flag) every second. But sometimes it appears the task is not executed in the expected period of 1 second. So I have changed it to execute at period 0.1 seconds. i.e, the task checks the flag 10 times every second. CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'app.tasks.periodic_runner', 'schedule': 0.1, 'args': [], 'relative': True }, 'task-number-two': { 'task': 'app.tasks.periodic_assigner', 'schedule': 0.1, 'args': [], 'relative': True } } What are the pros and cons? This task hits the database each time it is executed. I have five such tasks. Does it destroy my server in any way in the long run? -
How to create text editor for blog in python?
I want to create a blog in Python-Django where the user can post their content. Obviously, they need some text editor on the frontend. We can create simple textfield with the help of Django but I don't know how can I create a fully featured text editor? ** Example:- https://html-online.com/editor/ ** How can I create this kind of text editor for my Django blog website? -
How to connect the library for http requests?
I'm trying to connect the library to work with queries. At first I tried to connect this My steps: pip install requests in views.py: import requests .... def my_view(request) ... req = requests.get('https://api.github.com/events') And I get an error Internal Server Error Also I tried to use urllib.request in views.py: `import urllib.request .... def my_view(request) ... req = urllib.request.Request('https://api.github.com/events')` And I get an error Internal Server Error again What am I doing wrong? -
How to Upload any kind of file in django 2
I'm New in Django 2. I was trying to upload a file in Django here is my code View.py def addBook(request): checkName = AddBook.objects.filter(title=request.POST.get('title')) if not checkName: bookAdd = AddBook( title=request.POST.get('title'), slug=slugify(request.POST.get('title')), description=request.POST.get('description'), cover_image=request.FILES.get('title'), file=request.FILES.get('title'), category=request.POST.get('category'), created_by=request.user.id, ) bookAdd.save() messages.add_message(request, messages.INFO, 'Book Saved Successfully') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.add_message(request, messages.INFO, 'Book Title Already Exists') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) I can save everything but I need to save the file path and save the file locally. I read their documentation but cannot help me out. Please help me to solve this problem -
Django: how to add "set & save" method to models.Model?
How to write set method so I can call it like this: object.set(field1 = 0, field2 = 1) Here is my class: class model(models.Model): class Meta: proxy = True def set(self, **kwargs): # Insert your genius code here. self.save() -
Error installing mysqlclient using pycharm
I get an error when I try to connect MySql database using pycharm or even cmd I downloaded visual studio 2017 but the problem is still there and I tried with cmd all the possible wheels but it says 'this wheel is not supported in this platform' This is the error I get when I try to install mysqlclient using pycharm -
Unsure as to how to format url in fstring
I've got the following code: return f"<td class='eventyes'><a href='{% url 'accounts:daydetail' %}?{{ day }}'><span class='date'>{day}</span><ul><div class='singleevent'>{d}</div></ul></a></td>" I'm getting the following error: File "<fstring>", line 1 (% url 'accounts:daydetail' %) ^ SyntaxError: invalid syntax What syntax should I use to correctly format the name of the view within the anchor tag? Thanks! -
Authentication credentials were not provided. (error) in angular 6 while integrating rest api (django)..?
"Authentication credentials were not provided." i m getting this error in angular 6 while API integration from django. i m new to this so i don't know much about authentication but as per DRF tutorial i believe i have done everything write please review this code below.? *REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'google_auth.authentication.GoogleAuthAuthentication', 'rest_framework.authentication.BasicAuthentication', # enables simple command line authentication 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) }* ngOnInit() { } onSubmit(f){ console.log(f.value); const header = new HttpHeaders({'Content-Type': 'application/json'}); this.http.post('http://12.12.12.12/rest-auth/login/', f.value,{headers:header}).subscribe(( data ) => { console.log(data) this.a =data; console.log(this.a.key); localStorage.setItem('userToken',this.a.key); this.router.navigate(['../profile']); alert("You are login") } ,error => {console.log(error); this.non_field_errors=error.error.non_field_errors; this.password_error=error.error.password; }) } } -
How will I know when to increase the size of my RDS instance. Using Postgres with django
How will I know when to increase the size of my RDS instance (vertical scaling). Using Postgres with django. Suppose I choose t2 micro to start how will I know when to increase its size. I am using a django Application using PostgreSQL and Amazon t2micro instance -
How do you implement content-disposition as an attachment for django_weasyprint package?
Using the django_weasyprint (class-based view implementation) package to generate a pdf. I'm able to generate a pdf in the browser but have trouble setting up a open/save-as dialog box pop-up feature. I know I have to set content-disposition equal to attachment (I think) but I'm struggling doing so. from django.conf import settings from django.views.generic import DetailView from django_weasyprint import WeasyTemplateResponseMixin class ArticleView(DetailView): # vanilla Django DetailView model = Article template_name = 'article_detail.html' class ArticlePrintView(WeasyTemplateResponseMixin, ArticleView): # output of DetailView rendered as PDF pdf_stylesheets = [ settings.STATIC_ROOT + 'css/app.css', ] I've tried to used this snippet (found on stackoverflow) as well but I'm slightly confused about the first argument, '/path/to/test.pdf', of the write_pdf method. Does that mean I need an actual pdf included in the application as opposed to it being generated from the article_detail.html. from weasyprint import HTML class PdfView(DetailView): model = TheModel template_name = 'pdf.html' def get(self, request, *args, **kwargs): template_response = super().get(self, request, *args, **kwargs) HTML(string=template_response.rendered_content).write_pdf( '/path/to/test.pdf', stylesheets=['/path/to/pdf.css'] ) return template_response I'd like to have the open/save-as dialog box to pop-up automatically. Any ideas on the easiest solution? -
Http request to Django hosted on LAN timed out
I want to host my Django rest-api on my local server so visitors to my hosted website can make calls to it. It works perfectly on localhost:8000. What I did was: I changed ALLOWED_HOSTS in my settings.py file to all ['*'] python3 manage.py runserver 0:8000 But now when I try to make a call to or visit http://171.66.208.134:8000/ I get: (quizkly_env) DN0a22641a:web shiningsunnyday$ http --json POST http://171.66.208.134:8000/quizkly/ content="Barack Obama was the 44th president of the United States." http: error: Request timed out (30s). (quizkly_env) DN0a22641a:web shiningsunnyday$ I also tried python3 manage.py runserver 171.66.208.134:8080 but got: System check identified no issues (0 silenced). January 25, 2019 - 03:28:56 Django version 2.1.5, using settings 'quizkly.settings' Starting development server at http://171.66.208.134:8080/ Quit the server with CONTROL-C. Error: That IP address can't be assigned to. What's going wrong? -
for free Django VC deployment on AWS, which is best? just EC2.t2 or Beanstalk
I want to make sure that my instance shuts down whenever the free tier is surpassed, so a literally free site. For starters, all I could see are alerts, but nothing such as the instance shutting down unless you make some kind of hack that the alert starts a process that shuts down the EC2 which is a bit of a mess. The deployments on EC2 I have seen are SSH, not VC. Beanstalk also starts EC2 instances as process is needed which can also spike costs a lot and I am only wanting a free hosted test. Since Beanstalk is linked to whichever EC2 I suppose you can still link it to a free EC2.t2? Please avoid recommending other hosting services as AWS is a must for this task. -
Attribute error: 'str' object has no attribute 'read' python-django
So the scenario here is, I have a endpoint that will take a zipfile, unzip it and save it to media dir for now. Here's the whole code for that def get_filenames(path_for_zip): with ZipFile(path_for_zip, 'r') as zip: return zip.namelist() class Upload(View): def post(self, request): context = {} upload_file = request.FILES['document'] unzip_file = get_filenames(upload_file) for files in unzip_file: print(files) fs = FileSystemStorage() fs.save('read.jpg', files) return render (request, 'toDo_app.html', context) I am using FileSystemStorage as you can see. ZipFile is unzipping properly and i can see it in print(files) but the issue is at FileSystemStorage I guess, Its not getting saved and I get the attribute error 'str' object has no attribute 'read'. Please point me out what did I do wrong and how should it be solved. Thank you.