Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use dynamic tabs in django?
I am trying to implement dynamic tabs in my project that gives multiple tabs based on the values stored in the database. In my case, I have two values stored in database so it's displaying just two, If I will increase more, it will show accordingly. Category.objects.filter(category='MEDICINES') Out[14]: <QuerySet [<Category: FRUITS>, <Category: GRAINS>]> Here is my models.py file, from django.db import models from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Publish")) class Category(models.Model): category_names = ( ('DISEASES','DISEASES'), ('MEDICINES','MEDICINES'), ('ENCYCLOPEDIA','ENCYCLOPEDIA'), ) category = models.CharField(max_length=100, choices=category_names) sub_category = models.CharField(max_length=100, unique=True) def __str__(self): return self.sub_category class Medicine(models.Model): title = models.CharField(max_length=200, unique=True) display_name = models.CharField(max_length=17, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='medicine_posts') category = models.ForeignKey(Category, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("medicine_detail", kwargs={"slug": str(self.slug)}) Here it my views.py file, from django.views import generic from .models import Medicine, Category from django.shortcuts import render, get_object_or_404 class MedicineList(generic.ListView): queryset = {'medicine' : Medicine.objects.filter(status=1).order_by("-created_on"), 'category' : Category.objects.all() } #queryset = Medicine.objects.filter(status=1).order_by("-created_on") print(queryset) template_name = "medicine.html" context_object_name = 'element' #paginate_by = 10 Here is my medicine.html file, <div class="container"> <div class="row"> … -
posting date in dd-mm-YYYY format in django rest framework
I have set my Date_INPUT_FORMATS = "%d-%m-%Y" in settings.py file. Below is my settings File - REST_FRAMEWORK = { 'DATE_INPUT_FORMATS': "%d-%m-%Y", 'DATE_FORMAT': "%d-%m-%Y", 'DATETIME_FORMAT': "%d-%m-%Y %H:%M:%S", } I have a model with joining date As below : class Employee(models.Model): joiningDate = models.DateField() name = models.CharField(max_length=50) My Serializer : class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['joiningDate', 'name'] Viewset : class EmployeeViewSet(ModelViewSet): queryset = models.Employee.objects.all() serializer_class = serializers.EmployeeSerializer This is the json I am trying to post: { "joiningDate":"31-03-2020", "name":"EMpname", I think I have set it up correctly but while posting I am getting the following Error: "joiningDate": [ "Date has wrong format. Use one of these formats instead: %, d, -, %, m, -, %, Y." ] Can anyone guide me in the right direction? What did I miss? Thanks a lot in advance for your responses -
No module named settings error django elastic beanstalk
I'm trying to deploy a django app to elastic beanstalk. Beanstalk can't find the settings file when loading wsgi.py. I've seen this in a few other SO questions, but none of those solved my issue. I get the following error: ModuleNotFoundError: No module named 'kairos_app.prod_settings' Target WSGI script '/opt/python/current/app/kairos_app/kairos_app/wsgi.py' cannot be loaded as Python module. These are the contents of the 02_python.config file under .ebextensions: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python3 kairos_app/manage.py migrate --noinput" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python3 kairos_app/manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "kairos_app.prod_settings" "PYTHONPATH": "/opt/python/current/app/kairos_app:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: kairos_app/kairos_app/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" And this is what the directory structure looks like: It seems to pick up the WSGIPath okay, so I'm not sure why it can't pick up the django settings module path. -
populate GeoDjango PointField
I am going through the trouble to populate GeoDjango PointField. this is my model: class Shop(models.Model): name = models.CharField( max_length=50, ) location = models.PointField( null=True, blank=True ) I am not getting how to populate this PointField. I tried with like this: lat = 'nnnnnnnnnn' long = 'xxxxxxxxx' Shop.objects.create( name='example name', location=Point(lat, long) ) but it is not populating properly, I am not getting what is the right way to pupulate this pointField. Can anyone help me in this case? -
Django - The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead
I am building an customer management app and have built few decorator's. but when i run the app give this error The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead. decorators.py from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') elif request.user.is_authenticated == None: return redirect('login') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect('user-page') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function and my views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from .models import * from .forms import OrderForm, CreateUserForm, CustomerForm from .filters import OrderFilter from .decorators import unauthenticated_user, allowed_users, admin_only # Create your views here. @unauthenticated_user def registerPage(request): form … -
Elasticsearch DSL query with specific Output
I have a few objects in the database: object 1, object 2, object 3, .., object n Now I am doing filter like this MyDocument.search().filter("match", is_active=True).sort('id').execute() Output: searchDocumentobject 1, searchDocumentobject 2,searchDocumentobject 3, .... Now I need to searchDocumentobject 2 in last from the list. Need the output like this: searchDocumentobject 1,searchDocumentobject 3, .... , searchDocumentobject 2 Thank you -
Using python and django to test for reference value
I am someone who is both a doctor and researcher. I want to improve the work process of our department nurses by creating python code (which partly I already made in python) to help most beginning nurses. The issue i can get my head around is trying to link my python code (input) to a webform like in django and for it to return the conditions i have set. Ideally I want to end up for a webpage with a form asking multiple questions (multiple choice), which will return and action for the nurses to perform. I am sorry if this is a very basis and easy question. -
Access table field dymanically in django using for loop
def xyz(): site_data=site.objects.all() site_fields = site._meta.get_fields() site_fields_name = [f.name for f in site_fields][1:] return render(request, "Demoapp/InputGssA1.html", {'headers': table_structure,'site_data':site_data,'site_fieldname':site_fields_name}) this is i am render from function inside view.py and want to show in table format in InputGssA1.html, here table code is like {% for i in site_data %} <tr> {% for x in site_fieldname %} <td>{{i.x}}</td> {% endfor %} </tr> {% endfor %} but problem is I can't access object.fieldname using i.x in my code , i.fieldname statically work but this way it not working, How I access object's fieldname this way inside template tag?? -
Permission Error: [WinError 32] The process cannot access the file because it is being used by another process Django
I am dealing with pdf on my web page using PyMuPdf library(other pdf reading libraries are not working properly for me) ,the user is uploading a pdf file which is been saved in FileSystemStorage because I am unable to read it without saving it(would appreciate if you could suggest a way to do it without saving the file) now after reading the pdf I am using the command os.remove({}.fromat(pdf_path)) to delete it from file system which causes the above mentioned error below is my code def upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() fs.save(uploaded_file.name,uploaded_file) pdf_path = os.path.join(settings.MEDIA_ROOT, uploaded_file.name) doc = fitz.open("{}".format(pdf_path)) #doing some thing with the content of pdf doc.close() os.remove(pdf_path) return render(request,'upload.html',context) -
how to assign foreign key for two different types of classes
I have 3 classes: class Student(models.Model): name=models.CharField(max_length=200) class Background(models.Model): stud_name=models.CharField(max_length=200) surname=models.CharField(max_length=200) address=models.CharField(max_length=200) class Meta: managed=False db_table='background' class Class101(models.Model): stud_name=models.CharField(max_length=200) math=models.DecimalField(max_length=200) english=models.DecimalField(max_length=200) class Meta: managed=False db_table='class101' Class Student is input model whereas class Background and Class101 are static data taken from DB. When user writes down name the code goes and matches naem to stud_name in class Background and Class101 . In this case how to assign Foreign key ? i am confused here. Any helped is appreciated. Thanks in advance. -
Class Property method not read/called - Django Rest Framework
I am trying to add a class property method to the Game model, however it is not appearing on the frontend when I call game.owner_username. Model: class Game(models.Model): location = models.CharField(max_length=100) players = models.ManyToManyField(User) kickoff_time = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) max_player_count = models.IntegerField(null=True) goal_type = models.CharField(max_length=100) notes = models.CharField(max_length=300, null=True) status = models.CharField(max_length=6) owner = models.ForeignKey( User, related_name="games", on_delete=models.CASCADE, null=True) @property def owner_username(self): return self.owner.username -
Retrieving objects
I made a GET function that will retrieve posts and will make it available only to a particular user as well as its friends list. To make this work partially, I developed a raw query to get my desired output, and somehow it works fine for me. Now, I am trying to learn making queries in django without implementing raw query, so I am trying to maximize the Django ORM and not use raw query but I'm kinda stucked and kept wondering how I am gonna be able to make my queryset works without using raw query. this is my raw query: FeedMedia.objects.raw("""SELECT DISTINCT feed_media.* FROM feed_media INNER JOIN feed ON feed_media.feed_id = feed.id INNER JOIN media ON feed_media.media_id = media.id INNER JOIN profile ON profile.id = feed.profile_id INNER JOIN gosam_friend_profile ON gosam_friend_profile.profile_id = feed.profile_id INNER JOIN friendship_friend ON friendship_friend.id = gosam_friend_profile.gosam_friend_id WHERE friendship_friend.to_user_id = %(friend)s OR gosam_friend_profile.profile_id = %(profile)s""", params={'friend': request.user.pk, 'profile': profile.pk}) -
How to deal with Dynamic form in addition of common form in Django
I am new to Django. I am very confused to store the dynamic form with the common form I have created a model like class AudioDetail(models.Model): filename = models.ForeignKey(AudioData, default=1, on_delete=models.CASCADE) audio_type = models.CharField(max_length=20, null=True, choices=SPEECH_CHOICES) start_time = models.CharField(max_length=20, null=True) end_time = models.CharField(max_length=20, null=True) label = models.CharField(max_length=20, null=True) sentence = models.TextField(null=True, blank=True) class AdditionalFields(models.Model): word = models.CharField(max_length=20, null= True) transcript= models.CharField(max_length=20, null= True) language = models.CharField(max_length=20, null= True, choices=LANG_CHOICES) These 3 fields should be dynamic. if the 'sentence' field in 'AudioDetail' model has the value 'How are you?', then in 'AdditionalFields' it should be saved in 3 rows('How', 'are', and 'you') with the same 'AudioDetail' information in 3 rows. -
Django rest framework create data after check a condition
#View @permission_classes([IsAuthenticated]) class PageUserProjectView(viewsets.ModelViewSet): queryset = PageUserProject.objects.all() serializer_class = PageUserSerializer() def create(self, request): result = PageUserProject.objects.values('id').filter(page=request.data['page'], user=request.data['user'], project=request.data['project']) if len(result)>0: return Response("Selected page access is already given to selected user under this project", status=status.HTTP_200_OK) else: if PageUserSerializer.is_valid(request.data): return PageUserSerializer.create(request.data) #Model class PageUserProject(models.Model): allow_deny_enum = (('Allow', 'Allow'), ('Deny', 'Deny')) page = models.ForeignKey(Page, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) create_date = models.DateTimeField(default=datetime.now) access_status = models.CharField(max_length=20, choices=allow_deny_enum, default='Allow') I just need to add new data if the if condition in views is not satisfied. How to do that? Also with a response of JSON format like, { "id":5, "access_status": "Allow", "page": 2, "user": 1, "project": 2 } If condition is working properly but unable to work with the code inside else condition. -
How to set-up google oauth using django-allauth without the admin panel
Is there a way to set-up google oauth using django-allauth WITHOUT using the admin panel? I am building a website and don't want to use the default django admin app. I've acquired the required Google client id and secret, now I'm not able to understand how to configure the django-allauth SocailApp setting without the admin app. # SETTINGS.py # Django-allauth config SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": ["profile", "email",], "AUTH_PARAMS": {"access_type": "online",}, "APP": { "client_id": env("GOOGLE_CLIENT_ID"), "secret": env("GOOGLE_CLIENT_SECRET"), }, } } How should I add site to this configuration? -
parameters in request to DRF
I'm trying to parse an API page written using DRF import requests from bs4 import BeautifulSoup import time URL = 'url' data = {'user': 'admin','auth':'admin'} full_page = requests.get(URL, params=data) print(full_page) But I get a 403 error. I understand that I do not correctly transfer the login and password. Tell me how to transfer them? -
Django: Override form.errors messages on UserCreationForm
I'm trying to override (add languages) the messages of form.errors. I've tried this: forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) self.error_messages['duplicate_username'] = 'some message' After the form is submitted, it's not saved because username are unique and the error is displayed on the template. I'd like to make the same with the password but I can't find out the errors' key for each password validation. Can you provide me it? -
How can i inspect the db again in django?
I created my class in models.py with python manage.py inspectdb how can i generate new class if exists somebody new table in db -
Display success message in Django after download
I am trying to trigger a download of an AWS S3 object using Django 3. views.py def pagelanding(request,slug): if some_condition: URL='URL_to_s3_file' return redirect(URL) So far everything works fine, when I trigger the condition in my template, the download is triggered. The problem is that I would like to display a success message. Since the redirect is occupied by the download directive, I can't for example use the Django messages framework on the template. Is there any way to trigger the download and display the message at the same time? -
Docker with Django/Wagtails has a critical error
I am trying to build a Docker image with a Django/Wagtails site, including API endpoints. This works locally, however when I try to build a Docker image and push it up, it throws an error. Here's what my Dockerfile looks like: FROM python:3.7 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim \ ffmpeg # Set environment varibles ENV PYTHONUNBUFFERED 1 ENV DJANGO_ENV dev COPY ./requirements.txt /code/requirements.txt RUN pip install --upgrade pip # Install any needed packages specified in requirements.txt RUN pip install -r /code/requirements.txt RUN pip install gunicorn # Copy the current directory contents into the container at /code/ COPY . /code/ # Set the working directory to /code/ WORKDIR /code/ RUN python manage.py migrate RUN useradd wagtail RUN chown -R wagtail /code USER wagtail EXPOSE 8000 CMD exec gunicorn appname.wsgi:application --bind 0.0.0.0:8000 --workers 3 If desired, I can put my settings file, my api.py and my urls.py file, but none of them are changed from my local copy which works. Here's the error I get: AttributeError: 'WSGIRequest' object has no … -
Django - Return Object of Arrays
I'd like to have my API endpoint send data in the format {'column_name1': [result_array1],'column_name2': [result_array2]} -
error: No module named 'register.forms', using crispy-forms django
I am trying to install a django user registration module in crispy-forms and I am getting the error: No module named 'register.forms' The exact line giving me issues appears to be from .forms import RegisterForm I do have crispy-forms installed (secret) user@client:~/www/src/exchange $ pip3 install django-crispy-forms Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple Requirement already satisfied: django-crispy-forms in /home/kermit/Env/secret/lib/python3.7/site-packages (1.9.0) . (secret) user@client:~/www/src/exchange $ cat register/views.py from django.shortcuts import render, redirect #from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from .forms import RegisterForm # Create your views here. def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("home/") else: form = RegisterForm() form = UserCreationForm() return render(response, "register/register.html",{"form":form}) (secret) user@client:~/www/src/exchange $ cat register/form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate #from django.models import models class RegisterForm(UserCreationForm): email = models.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] . (secret) user@client:~/www/src/exchange $ cat exchange/urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view, user_view from userdash.views import userdash_detail_view, userdash_create_view from django.conf.urls import include from register import views as v from pages import views urlpatterns = [ path('', views.home_view, name='home'), path('', … -
(pre-receive hook declined) while deploying on heroku
When I try git push heroku master, this error pops up ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/web--dev.git' Also this is in my settings.py file where it can be an error import dj_database_url from decouple import config DATABASE = { 'default': dj_database.config( default=config('DATABASE_URL') ) } -
Now able to register using class based view.?
I want to work with company model where i am to register using subdomain and have to login using that same domain name. I created a model using following fields : models.py class Company(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=2000) sub_domain = models.CharField(max_length=30) user_limit = models.IntegerField(default=5) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) And my registration form is like something below: forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Company fields = ['name', 'address', 'sub_domain', 'country'] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs = {"class": "form-control"} But when it comes to views i dont know how to handle class based views and as i am a newbie facing problem to save data in db. views.py class RegistrationView(CreateView): model = Company form_class = RegistrationForm template_name = "company_register.html" def is_valid(self, form): company = Company.objects.create_company(form.cleaned_data['name'], form.cleaned_data['address'], form.cleaned_data['sub_domain'], form.cleaned_data['country']) company.save() return super(RegistrationView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(RegistrationView, self).get_context_data(**kwargs) Please someone help!!! -
TemplateSyntaxError while using typeform sdk to pass url parameter to class
I am using Django. I have pip installed typeform sdk using https://pypi.org/project/django-typeform/ I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0 But this gives me Exception Type: TemplateSyntaxError Exception Value: 'sekizai_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache django_typeform i18n l10n log static tz