Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: insert list using ModelViewSet
The online documentation is not very clear. The default POST method of ModelViewSet is supposed to allow you to insert a list of your models, but in reality it only allows single model insertion. For code example please refer to the one stated in the https://www.django-rest-framework.org/api-guide/viewsets/ class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() -
how to create a xar file for python script or django/flask application?
Is anyone tried creating XAR file for python scripts or django or flask application in CentOS? How stable is it for production usage? Most importantly, how to include python interpreter too in the xar self-executable? https://www.pydoc.io/pypi/xar-18.7.12/autoapi/commands/bdist_xar/index.html https://engineering.fb.com/data-infrastructure/xars-a-more-efficient-open-source-system-for-self-contained-executables/ -
elasticsearch: NotFoundError
Installed elasticsearch. I try to find the records, but when I try to iterate, I get the error elasticsearch.exceptions.NotFoundError: NotFoundError (404, 'index_not_found_exception', 'no such index', cars, index_or_alias) Although such a record is in the database. What could be the reason. I launch the project on port 8001. def search(request): json_data = json.loads(request.body) title = json_data['title'] if 'title' in json_data else '' note_text = json_data['note_text'] if 'note_text' in json_data else '' publication_type = json_data['publication_type'] if 'publication_type' in json_data else '' mesh_terms = json_data['mesh_terms'] if 'mesh_terms' in json_data else '' conditions = json_data['conditions'] if 'conditions' in json_data else '' comments = json_data['comments'] if 'comments' in json_data else '' more = json_data['more'] posts = ArticleDocument.search() if title and title != '': posts = posts.query("match", title=title.lower()) if note_text and note_text != '' : posts = posts.query("match", note_text=note_text.lower()) if comments and comments != '': posts = posts.query("match", comments=comments) if publication_type and publication_type != '': posts = posts.query("match", publication_type=publication_type.lower()) if mesh_terms and mesh_terms != '': posts = posts.query("match", mesh_terms=mesh_terms) if conditions and conditions !='': posts = posts.query("match", conditions=conditions) posts = posts.extra(from_=0, size=more) resdata = [] for hit in posts: resdata.append({"title":hit.title, "id":hit.index}) return JsonResponse({'code':1, 'data':resdata, 'msg':"Success"}) -
Push Notification React Native Expo with Django RestFramework
I am a newbie with notification using React Native Expo, and all Tutorials that I have searched so far is integrated with Firebase, But I am working on Django Rest Framework, I could not find any example, except on the Expo Documentation . I know all the mechanism, but I am struggling on the usage of Python Library : https://github.com/expo/expo-server-sdk-python If anyone has an example on how to use it, I'd be much appreciated. -
How to display some message if the user account is not active?
Here I am trying to display some messages if the username and password is correct but if the is_active field is false but it is not displaying the message with this code.It is displaying me the else part even if the username and password are correct of that inactive user.How can I do it ? views.py form = LoginForm() if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = form.cleaned_data['remember_me'] user = authenticate(request, username=username, password=password) if user and not user.is_active: messages.info(request,'Sorry your account is deactivated now.') return redirect('/login/') elif user and user.is_active: login(request, user) if not remember_me: request.session.set_expiry(0) else: request.session.set_expiry(settings.SESSION_COOKIE_AGE) else: messages.error(request, 'Invalid login credentials. Try Again.') return redirect('/login/') -
ID field is always returning empty
I have a very simple model of user with name email and password and I am assuming the default id field. I am using tastypie and djongo. Now when I write a resource I always get empty id field even though its there in mongo as well. 1- I set ENFORCE_SHEMA to False in settings.py. If I don't do that I always get error yield self._align_results(doc) File "/usr/local/lib/python3.6/dist-packages/djongo/sql2mongo/query.py", line 289, in _align_results raise MigrationError(selected.column) djongo.sql2mongo.MigrationError: id and now When I query I get such data {"email":"abc@abc.com", "name":"abc", "id":""} Tried setting id field manually and tried other ways but no benefit -
Regular expression to match phrases with plus sign
Was wondering what is the best way to match "clear 18+ from your history" from "clear 18+ from your history? blah blah blah" is? Using Python. I've tried this, keyword = "clear 18+ from your history" prepped_string = "clear 18+ from your history? blah blah blah" is_flagged = False if re.search(r'\b' + keyword + r'\b', prepped_string): is_flagged = True The above code only works with no special character. If there is a special character like the plus sign, it won't work. Thanks in advance. -
Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name
I am getting the above error when I try to access the landing page. What am I missing? Traceback NoReverseMatch at / Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name. Here is the base.html code <button> `<a href="{% url 'trucks:fleet' %}"> Fleet Admin </a> </button> and below is the app urls.py file from django.urls import path from .admin import fleet_admin_site app_name = 'trucks' urlpatterns = [ path('fleet/', fleet_admin_site.urls, name="fleet"), ] and the main urls.py file from django.contrib import admin from django.urls import path, include, reverse from django.views.generic import TemplateView urlpatterns = [ path('admin/', include('workers.urls')), path('admin/', include('trucks.urls')), path('', TemplateView.as_view(template_name='base.html')), ] -
How to combine two different Models in serializers module (Django)?
I want to create a Registration API, wherein, I aim to combine the User Model and Profile Model in order to create a new user by adding the username, email, password (User Model fields) and gender, salary, company, and address (Profile Model fields). I attempted to use the source from this link. However, I am not able to POST any data in. This is my code so far: views.py: class RegisterAPIView(APIView): def post(self, request, format=None): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response("Thank you for registering", status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from rest_framework import serializers from users.models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['gender', 'company', 'salary', 'address'] class RegisterBSerializer(serializers.ModelSerializer): #User Model serializer profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'password'] def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password', None) user = User.objects.create(**validated_data) if password is not None: user.set_password(password) user.save() Profile.objects.create(user = user, **profile_data) return user Can anyone hint me on where I am going off-track?. -
Django - Page not found (404) URLconf not updating
Following this tutorial https://docs.djangoproject.com/en/2.2/intro/tutorial01/ I get a 404 when trying to load /polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. mysite.urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls.urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] polls.views from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Directory structure Django |mysite |__pycache__.py |__init__.py |settings.py |urls.py |wsgi.py |polls |migrations |__init__.py |init.py |admin.py |apps.py |models.py |tests.py |urls.py |views.py |db.sqlite3 |manage.py I've tried rebooting my computer as well as the server -
Multiple django 'with' statements inside 'if' statement
I have a Django multiple 'with' statements inside 'if/elif' statement. The blocks of code inside if/elif are the same except for one variable 'slide1_line2'. I am wondering if there is a way to re-write code to avoid repetition. {% if country == 'England' or country == 'Wales'%} {% with graphic='map.png' %} {% with classes='color-1' %} {% with slide1_line1='Your constituency is '|add:name %} {% with slide1_line2='Heading1' %} {% with slide1_line3='text' %} {% with icon='keyboard_arrow_down' %} {% include 'slide_map.html' %} {% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %} {% elif country == 'Scotland' or country == 'Northern Ireland' %} {% with graphic='map.png' %} {% with classes='color-1' %} {% with slide1_line1='Your constituency is '|add:name %} {% with slide1_line2='Heading2' %} {% with slide1_line3='text' %} {% with icon='keyboard_arrow_down' %} {% include 'slide_map.html' %} {% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %}{% endwith %} {% endif %} -
How do I create a Django project using Jupyter?
I have some python code that needs to interact with my HTML page. For that, I have to use Django Framework. As I am very new to this I don't how to do it. I have installed the Django on my system using the following command: pip install django After running this command, I got the below output: Collecting django Downloading https://files.pythonhosted.org/packages/b2/79/df0ffea7bf1e02c073c2633702c90f4384645c40a1dd09a308e02ef0c817/Django-2.2.6-py3-none-any.whl (7.5MB) Requirement already satisfied: pytz in c:\users\hisingh\appdata\local\continuum\anaconda3\lib\site-packages (from django) (2019.1) Collecting sqlparse (from django) Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Installing collected packages: sqlparse, django Successfully installed django-2.2.6 sqlparse-0.3.0 Note: you may need to restart the kernel to use updated packages. Now I want to create my first django project. I am trying to do it through Jupyter notebook by running the below command: django-admin FirstProject OUTPUT: File "", line 1 django-admin FirstProject ^ SyntaxError: invalid syntax Can someone please guide me to do that? Any help will be appreciated. -
django API how to get parameter include special Characters
hello now i make django api for searching mysql DB but i will send parameter like this %20%20%20chinkyu5211 it cognize chinkyu5211 except special characters chinkyu5211 so if someone know that way to cognize %20%20%20chinkyu5211 all sentences plz teach me.. class SearchView(APIView): def get(self, request): data_list=[] #es = Elasticsearch() # 검색어 search_word = request.query_params.get('search') print(search_word) this is my views code and if i printed search_word i got the result chinkyu5211 as i said before i hope that the problem will be solved.. thanks you -
How do I filter data with two parameter from two different Django models
I want to create a JSON object which will Search the particular Projects from the model "EmpProject" by a specific emp_id Search whose project status is "Pending" from the model "Project" with the help of (1.) Search result I am using JSON Parser (no models or generic view) Models Below are my models I have not use many to many field instead I created a Intermediate Table if the solution is also possible by using manytomanyfield than also suggest class Employee(models.Model): employeeid = models.IntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_no = models.CharField(max_length=10) date_of_birth = models.DateField() email = models.EmailField(unique=True) password = models.CharField(max_length=50) designation = models.CharField(max_length=50) dept_id = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ('id',) def __str__(self): return self.emp_name class Project(models.Model): projectname = models.CharField(max_length=50, unique=True,) project_status = models.CharField(max_length=50) description = models.TextField() start_date = models.DateField(auto_now_add=True) due_date = models.DateField() class Meta: ordering = ('id',) def __str__(self): return self.projectname class EmpProject(models.Model): emp_id = models.ForeignKey(Employee,on_delete=models.SET_NULL, null=True, blank=True) project_id = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, blank=True) class Meta: unique_together = [['emp_id','project_id']] ordering = ('project_id',) def __str__(self): return self.emp_id Serializer class EmployeeSerializer(serializers.ModelSerializer): dept_id = serializers.SlugRelatedField(queryset=Department.objects.all(), slug_field='dept_name') class Meta: model = Employee fields = [ 'id', 'employeeid', 'first_name', 'last_name', 'phone_no', 'date_of_birth', 'email', 'password', 'designation', 'dept_id', ] class ProjectSerializer(serializers.ModelSerializer): … -
Unable to run celery task that depends on Django code
I seemingly have a bit of a catch 22 scenario when trying to run a celery task that depends on django code. Celery code from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery import shared_task from celery import task from letters.send_write_letter_reminders import send_write_letter_reminders # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings') app = Celery('app_name') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.timezone = 'Europe/London' # Load task modules from all registered Django app configs. app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task(bind=True, name='send_letter_reminders') def send_letter_reminders(slug=None): send_write_letter_reminders(slug=slug) The problem I've run into is that with this line from letters.send_write_letter_reminders import send_write_letter_reminders With it I get: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. And the app server won't run, but without it I get: NameError: name 'send_write_letter_reminders' is not defined Obviously I'm missing something fundamental about how to run Celery and Django together, but I can't see it. Can anyone enlighten me as to what I've done wrong? -
Django's POST method remove "+" symbol from html input form
I'm new to Django, was wondering how can I make it not remove + or passed in html input form. For ex. one of the input form has an input value of $\frac{1}{2} + \frac{2}{3}$, apparently it is converted to $\\frac{1}{2} \\frac{2}{3}$. I don't want Django's post method to remove + from it. The input html code looks like this: <td><input id="element1" type="text" maxlength="100" lang="latex" required></td> -
IPFS not storing encrypted file completely
I am using django-ipfs-storage module for my project and wants to upload a file to InterPlanetaryFileSystemStorage() model field. However if I simply upload a pdf file, it gets successfully uploaded but when I upload after encrypting the file, only first 4096 bytes are stored and rest are not there. When I tried adding the same encrypted file using ipfs add command on the terminal, the file is successfully uploaded. Here is the code for uploading an encrypted file: file_ = open(os.path.join(settings.ENCRYPTION_ROOT,str(paper)+'.encrypted'),'rb') s_file = File(file_) store = Request.objects.get(tusername=request.user.username) store.paper.save(str(paper)+'.encrypted',s_file,save=True) I have searched everywhere but still didn't get any help in this regard. -
Cant save forms to models django
i cant save my forms to a models into my database the code work smoothly no errors but if i check in django admin its not save to my database model can you help me here my code : forms.py class InstagramUsernameForm(forms.ModelForm): class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.values_list("username", flat=True)) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan", flat=True)) models.py from django.db import models # Create your models here. class Instagram(models.Model): nama_depan = models.CharField(max_length=100,blank=True,null=True) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return self.username class InstagramUsername(models.Model): nama_orang = models.CharField(max_length=20) username = models.CharField(max_length=20) nama_depan = models.CharField(max_length=100,default='') def __str__(self): return self.nama_orang views.py def create2(request): akun_form = InstagramUsernameForm(request.POST or None) if request.method == 'POST': if akun_form.is_valid(): akun_form.save() return redirect('sosmed:awe') else: print(akun_form.errors) context = { "akun_form":akun_form, } return render(request,"sosmed/awe.html",context) awe.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>awe</title> </head> <body> <form method="post"> {% csrf_token %} <h1>awe</h1> <table> {{ akun_form.as_table }} </table> <button type="submit">Create</button> </form> </body> </html> cant save forms to django models -
While creating dynamic url I am getting a Reverse for 'dashboard_group' with arguments error
urls.py urlpatterns = [ path('processes/', views.processes, name="dashboard"), path('processes/<uuid:u_id>/', views.groups, name="dashboard_group") ] views.py def processes(request): return render(request, 'processes/index.html') def groups(request, u_id): return render(request, 'create_instance/index.html') The above code gives me following error - Reverse for 'dashboard_group' with arguments '('a21713b0ec29416c8fb27d4f339eabb8',)' not found. 1 pattern(s) tried: ['processes\/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/$'] -
django rest framework get request in serializer create method
I'm a student studying django rest framework I tried to upload multiple file with form-data this is model class Post(models.Model): text = models.CharField(max_length=5000) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.FileField(blank=True) And views class AddPost(APIView): serializer_class = PostSerializer def post(self, request, format=None): serializer = PostSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return JsonResponse({'status':status.HTTP_200_OK, 'message':"sucess", 'data':""}) serializers class FileSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' class PostSerializer(serializers.ModelSerializer): images = FileSerializer(source='image_set', many=True, read_only=True) class Meta: model = Post fields = ('id', 'text', 'owner', 'created_at', 'images') def create(self, validated_data): images_data = self.context.get('request').request.FILES images_data = self.context.get('request').request.FILES post = Post.objects.create(text=validated_data.get('text'),owner=validated_data.get('owner')) for image_data in images_data.values(): Image.objects.create(post=post, image=image_data) return post when i send request like this in postman enter image description here error occurs and this is error message images_data = self.context.get('request').request.FILES AttributeError: 'NoneType' object has no attribute 'request' i already saw this link https://codeday.me/en/qa/20190306/12057.html thanks for your help -
does not work sympy-gamma on digital ocean server
I am download github code for sympy-gamma form here:- https://github.com/sympy/sympy and put on my digital ocean server. It is run the code but the step by step solution does not display. is any external tool is required for display step by step solution on server? can any one please help me! -
How do I cancel the option url after the link?
debug=true local static enter image description here debug=false static server enter image description here how do i cancel ?_=2.1this string? -
Celery beat processed messages not removed from ready state
I have Celery beat defined as: @periodic_task(run_every=(crontab(minute='*/15')), name='threshold_monitor', ignore_result=True, queue='default', options={'queue': 'default'}) def threshold_monitor(): #Threshold check login Celery is run through supervisord as: celery -A ProjectName beat --loglevel=info The task is well executed every 15 minutes but it is not removed from the celery queue as expected. The number keeps growing in RabbitMq. Is this the expected behavior? If not, how do I fix it. Other celery settings: CELERY_RESULT_BACKEND = 'rpc' CELERY_ACKS_LATE = True CELERY_IGNORE_RESULT = True CELERY_TASK_IGNORE_RESULT = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_TASK_DEFAULT_QUEUE = 'default' CELERY_TASK_ALWAYS_EAGER = False CELERYD_TASK_TIME_LIMIT = 60 RabbitMQ queue screenshots: Note the default queue items are executed and released, but celery keeps growing. -
terjadi expected an indented block
from django.db import models from django.contrib.auth import User Create your models here. class UserProfileInfo(model.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def str(self): return self.user.username user = models.OneToOneField(User,on_delete=models.CASCADE) ^ IndentationError: expected an indented block -
How to implement JWT authentication in web app after a registered user logs in?
I am new to Django and I want to implement JWT authentication in order to view an API data for the currently logged-in user, only. Can someone please give me a hint on how to structure the implementation of JWT in Django (version 2.1)?