Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create hierarchical urls within django app?
I have multiple app based django project and within some apps url scheme getting complicated due to number of models. Hence I'm looking a way to make a hierarchical url structure within the app. In my project's urls file I do the following. from order import urls as order_urls In the order app I have urls.py and urls directory which contains separate url patterns for each model as follows. In the app's urls.py file I import the model's urls as follows. from urls import rental as rental_urls urlpatterns = [ url(r'^rental-request/', include(rental_urls)), ] This gives me the error: ModuleNotFoundError: No module named 'urls' If I put __init__.py it gives me circular import error. I'm not sure this is the correct way/possible for my requirement. Anyone could explain the correct way to achieve it? -
Error when testing the view with a file upload
I would like to test a file upload from my view with the following function: def test_post(self): with open("path/to/myfile/test_file.txt") as file: post_data = { 'description': "Some important file", 'file': file, } response = self.client.post(self.test_url, post_data) self.assertEqual(response.status_code, 302) document = Document.objects.first() self.assertEqual(document.description, "My File") self.assertEqual(document.filename, 'test_file.txt') When I test the file upload on the actual website, it works. But when I run this test, I get the following error: django.core.exceptions.SuspiciousFileOperation: Storage can not find an available filename for "WHJpMYuGGCMdSKFruieo/Documents/eWEjGvEojETTghSVCijsaCINZVxTvzpXNRBvmpjOrYvKAKCjYu/test_file_KTEMuQa.txt". Please make sure that the corresponding file field allows sufficient "max_length". Here is my form save method: def save(self, commit=True): instance = super(GrantDocumentForm, self).save(commit=False) instance.filename = self.cleaned_data['file'].name if commit: instance.save() return instance Seeing as it works on the actual website, I suspect it has something to do with the way I setup the file in the test; probably something small. -
Get Foreign Key Model's name in DRF serializer
I have 2 models - QuestionSession and Project. Project just stores these sessions, so my models as simple as: class Project(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class QuestionSession(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='sessions', blank=True, null=True, default=None ) And my serializers: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = [ 'id', 'name', 'sessions' ] class QuestionSessionSerializer(serializers.ModelSerializer): class Meta: model = QuestionSession fields = [ 'id', 'questions', 'project' ] The result I am trying to achieve is to retrieve Session with its project's name. But the project field in QuestionSession serializer only returns project's id. Looks like this: {"sessions":[{"id":4,"questions":[12,13],"project":3}]} How can I get project's name with these serializers? -
Django Error 400 with variable in urlopen
I have 500 error in my Django app, and a 400 error code when I turned on the debug mode. I use Python 3.5 This is about this : url = "https://graph.facebook.com/v3.2/lamontagnesolitaire?access_token="+str(token)+"&fields=posts{id}" fb_query = urlopen(url).read().decode('utf-8') The query is working fine, because when I put my 'token' as a plain string, I don't have any error and I can properly read the URL. I already tried this methode, or some variantes : url = "https://graph.facebook.com/v3.2/lamontagnesolitaire?access_token=%s&fields=posts{id}" %token fb_query = urlopen(url).read().decode('utf-8') I still get a 400 error message : Django Traceback : Environment: Request Method: POST Request URL: http://localhost:9000/api/likes Django Version: 1.11.4 Python Version: 3.5.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'start', 'myaccount', 'wall', 'api', 'gunicorn', 'django.contrib.sites', 'django.contrib.sitemaps', 'compressor'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/django-project/seigneurdesanneaux/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/django-project/seigneurdesanneaux/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/django-project/seigneurdesanneaux/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django-project/seigneurdesanneaux/api/views.py" in view_likes_synchronization 48. fb_query = urlopen(url) File "/usr/lib/python3.5/urllib/request.py" in urlopen 163. return opener.open(url, data, timeout) File "/usr/lib/python3.5/urllib/request.py" in open 472. response = meth(req, response) File "/usr/lib/python3.5/urllib/request.py" in http_response 582. 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.5/urllib/request.py" in error 510. … -
Setting year range for Mezzanine inline date editor
I'm having trouble with configuring the Mezzanine in-line editing for datetime fields. I have a field in the page something like this (as in http://mezzanine.jupo.org/docs/inline-editing.html) {% editable page.project.start %} {{ page.project.start|date:'Y M'}} {% endeditable %} However, the widget is showing only 9 future years (as https://docs.djangoproject.com/en/2.1/ref/forms/widgets/#selectdatewidget) specifies, so it's impossible to enter any dates in the past. I'd need to set the years attribute for that widget, however, I don't have any direct access to it, as it's generated automagically by Mezzanine. How can I set the arguments to Django widgets through the Mezzanine in-line editing code? -
unbound method logmein() must be called with Login instance as first argument (got WSGIRequest instance instead)
I got the follwoing error.. TypeError at /authme/logmein/ unbound method logmein() must be called with Login instance as first argument (got WSGIRequest instance instead). in the above error 'Login' is a class based view and logmein() is one of the method of 'Login' class. this is my urls.py from django.conf.urls import url, include from authme import views urlpatterns = [ url(r"^$", views.Login.as_view(), name="Login"), url(r"^logmein/$", views.Login.logmein, name='logmein'), url(r"^logout/$", views.Login.logout, name='logout'), ] and this is my views.py from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.shortcuts import redirect from django.views.generic.base import View class Login(view): def logmein( request ): if request.user.is_authenticated(): return redirect('/') else: username = request.GET.get("inputUsername",False) password = request.GET.get("inputPassword",False) if username and password: user = authenticate( username=username, password=password ) if user is not None: if user.is_active: login( request, user ) return redirect("/") else: return render( request, 'authme/login.html',{"message":"Login Failed! Your Account Is Inactivated!"} ) else: return render( request, 'authme/login.html',{"message":"Login Failed! Please try again!"} ) else: return render( request, "authme/login.html",{"message":"Login Failed! Please try again with correct key-pair."} ) return render( request, "authme/login.html", { "message":"None" } ) thanks in advance.... -
i am getting error The 'make' utility is missing from PATH when i am building Docker file
when i build docker file i am getting error as 'The make' utility is missing from PATH. This is my Docker file FROM python:3.6-alpine WORKDIR /app COPY ./requirements.txt /app RUN apk --no-cache add shadow \ gcc \ musl-dev \ postgresql-dev \ python3-dev \ freetype-dev \ libffi-dev \ tiff \ tiff-dev \ tk-dev \ tcl-dev \ postgresql \ postgresql-dev \ jpeg \ jpeg-dev \ zlib \ zlib-dev \ nodejs \ yarn \ && addgroup -g 1000 -S www-data \ && adduser -u 1000 -S -G www-data www-data \ && pip install --no-cache-dir --upgrade 'pip<19.0' \ && pip install --no-cache-dir -r requirements.txt \ && apk del //\ gcc \ musl-dev \ tiff-dev \ tcl-dev \ jpeg-dev \ zlib-dev \ postgresql-dev \ && rm -rf /var/cache/apk/* RUN chown www-data:www-data . USER www-data COPY --chown=www-data:www-data . /app ./bin/build-and-run.sh db uses an image, skipping rabbitmq uses an image, skipping elasticsearch uses an image, skipping Building backend Step 1/8 : FROM python:3.6-alpine 3.6-alpine: Pulling from library/python Digest: sha256:4ae5142f052c4efd0bede8483f8ca43a73e8fcfce5dbf8f581967c2c9bac597b Status: Image is up to date for python:3.6-alpine ---> 1837080c5e87 Step 2/8 : WORKDIR /app ---> Using cache ---> a38347027d99 Step 3/8 : COPY ./requirements.txt /app ---> Using cache ---> 2aa3cf2383d1 Step 4/8 : RUN apk --no-cache add … -
Django PayPal back-end integration with REST API for Mobile App
Has anyone used PayPal for Django backend, I am developing a project( A REST API), was thinking which module to work with. The API is associated with a mobile App, I am confused which side payment feature should be added, also how to manage after payment data, failed payments, invoices, subscriptions etc. Any help will be appreciated -
The correct practice to implement these relationships in django models
I am designing my database and want to know if the relationships I am implementing are the best practice or not. The aim is that one person can own multiple places and multiple people can even book a single place at different times and one place can have multiple bookings. so I am using this code class User(models.Model): name = models.CharField(max_length=100) ban = models.BooleanField(default=False) class Place(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey(User, on_delete=models.CASCADE, ) class Bookings(models.Model): date = models.CharField(max_length=100) booker = models.ForeignKey(User, on_delete=models.CASCADE) place = models.ForeignKey(Place, on_delete=models.CASCADE) the expected output is a secure way to implement the relationships currently they are working when I tested them in the shell with one or two places and users but I am not sure if this is right. -
Which rule/guideline does this break (adding attributes to orm instance)
I came across this code: class MyModel(model.Model): def __init__(self, *args, **kwargs): self._log_data = dict() super(MyModel, self).__init__(*args, **kwargs) def send_data(self, obj): self._log_data['foo'] = obj.foo ... I just have the feeling that adding ._log_data to an orm instance is wrong. Up to now I just have this feeling that this implementation is not obvious and I am missing the matching term. According to which rule/guideline is this not clean/good code? -
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?