Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Happy new year Stackoverflow
Happy new year everyone! Thanks for all the support you give to noobs! happy new year Does anyone know where django-channels store channel_name? -
AWS Elastic Beanstalk Django website won't show up
I have set Elastic Beanstalk of Python3.6/Amazon Linux with Django 1.11. The application has been successfully uploaded via EB CLI and installed. INFO Deploying new version to instance(s). INFO New application version was deployed to running EC2 instances. INFO Environment update completed successfully. set .config files without errors: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: myproject.settings SECRET_KEY: TempKey aws:elasticbeanstalk:container:python: WSGIPath: myproject/wsgi.py The EB parses wsgi.py well. I have included the current EB address(like projectname.us-west-1.elasticbeanstalk.com) in ALLOWED_HOSTS. After all these 'no-error' processes, however, the actual website does not show up. (while, the EB sample application was working) There is even no 400, 500 error message page at all. No Django error message no matter what DEBUG=True or False. Just browser shows a blank timed out page. When I run Django in local environment with python manage.py runserver, it works nicely. ------------------------------------- /var/log/httpd/error_log ------------------------------------- [mpm_prefork:notice] [pid 3150] AH00169: caught SIGTERM, shutting down [suexec:notice] [pid 20456] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [so:warn] [pid 20456] AH01574: module wsgi_module is already loaded, skipping [http2:warn] [pid 20456] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm … -
use jenkins to run cron job that queries a database used by django rest app and store results in file in django app or back in database
I have a django rest app with a view that is dependent on the performance of each user in a category within my app. I don't want to have the query this view requires be to done every time the view is called, because I want this view to be an example of a snapshot in time every 4 hours. Additionally I have learned from various reading that we can use jenkins to do cron jobs with ( I tried the unix os way, and its a mess, functionality is a lot nicer with jenkins) I want to use jenkins to query my database for the information I need, then store that information back in my database in another table, or even better a file in my django project if possible, to then be used with my view. Thing is I have no idea how to start doing this. Can someone walk me through a bit. All the tutorials are on pipelines. -
I made a login page ,After I put in the login credentials, the page is not moving to the next page
when I try to login to the page, it is not moving onto the next page. The project is linked to a db and the db stores the superuser data, but the login is not moving further login_page.html : <div class="card"> <div class="card-body login-card-body"> <p class="login-box-msg">Sign in to Student Management System</p> <form action="/doLogin" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <input type="email" class="form-control" placeholder="Email" name="email"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-envelope"></span> </div> </div> </div> <div class="input-group mb-3"> <input type="password" class="form-control" placeholder="Password" name="password"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> urls.py : from django.conf.urls import url from django.contrib import admin from django.conf.urls.static import static from student_management_app import views from student_management_system import settings urlpatterns = [ url('demo',views.showDemoPage), url(r'^admin/', admin.site.urls), url('',views.ShowLoginPage), url('doLogin',views.doLogin), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) The doLogin function is supposed to output the login credentials entered in the login page, but it is not going to the output part of it views.py : import datetime from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render def showDemoPage(request): return render(request,"demo.html") def ShowLoginPage(request): return render(request,"login_page.html") def doLogin(request): if request.method != "POST": return HttpResponse("<h2>Method not Allowed</h2>") else: return HttpResponse("Email : "+request.POST.get("email")+" Password : "+request.POST.get("password")) -
How do I setup django on Linode with domain name?
I have created Linode and domain name on Linode now I want to deploy my local Django app to Linode. How can I do Please suggest to me. -
Page not found (404) in Django, whenever I tried adding <int:pk> in urls.py
What I wanted to achieve is for the product's id to be shown in the url, whenever a user clicks it. So I tried putting int:pk in the url, but it says, Page Not Found (404) Request Method: GET Request URL: http://127.0.0.1:8000/book-details/ Below is my code homepage.html {% for book in random %} <a type="submit" href="{{% url 'book-details' %}}"> <img src="{{book.cover.url}}" height="300px" width="200px"> </a> {% endfor %} views.py def book_details(request,pk): return render(request, 'book-details.html') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', homepage, name='home'), path('fiction', fiction, name='fiction'), path('nonfiction', nonfiction, name='nonfiction'), path('book-details/<int:pk>/', book_details, name='book-details'), path('search-result', search_result, name='search-result') -
Elastic Beanstalk Django error when running eb create
I'm trying to upload my Django based Python server to AWS Elastic Beanstalk. It all works fine until eb create. Here, in the error logs, I get the error: An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/include/python3.7m: no such file or directory This is the layout of my folder in which I initialized eb: This is the layout of my folder inside src, which is the Django Application: All of the folders have been uploaded to my git repository. I realize this may not be enough information, so please ask me for more and I'll reply ASAP. -
Django Admin Create Child Item Directly From Parent
I have two models basically the category and the product (having a foreign field related to the category). Several categories have been created through the admin page and next would be creating the products under each category. I would like to know in Django Admin, if there is a way I could click on the individual category and create a product directly under the category I selected. Note that I understand I can create a product and select the category directy, but I just want to know if I can do it from the category side. Thank you. # my models class Category(models.Model): code = models.CharField(max_length=45, unique=True) name = models.CharField(max_length=45) class Product(models.Model): part_number = models.CharField(max_length=45, unique=True) category = models.ForeignKey(Category, on_delete=models.RESTRICT) brand = models.CharField(max_length=45, blank=True, null=True) specification = models.CharField(max_length=45) Currently I have -
django crontab not execution function
i installed crontab and I am on a 2020 macbook pro pip installed pip install django-crontab added cron to my installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', 'corsheaders', ... added my cronjobs setting and set the interval for every minute CRONJOBS = [ ('*/1 * * * *', 'shofidecksite.cron.testcron') ] made a cron.py file in my app directory added the testcron function from users.models import ContentCreatorUsers def testcron(): users = ContentCreatorUsers.objects.all() for user in users: user.delete() ran the cron add command python manage.py crontab add removing cronjob: (a590457763fe7584cac7e45a045d5955) -> ('*/1 * * * *', 'shofidecksite.cron.testcron') adding cronjob: (a590457763fe7584cac7e45a045d5955) -> ('*/1 * * * *', 'shofidecksite.cron.testcron') then ran python manage.py runserver I started with 30554 test ContentCreatorUsers 2 minutes later I still have the same, none where deleted. Did I do something wrong? -
Django-Channels: How to get channel_name from user_id?
Below code prints the channel_name of a client class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.channel_name) How to get the channel_name from user_id (user.id) for an authenticated user (It needs to be accessed outside the consumer)? Something like below import foo channel_name=foo.get_channel_name_from_user_id(user_id) print(channel_name) Thanks! Happy new year! -
Django: Channels and Web Socket, how to make group chats exclusive
Eg i have a chat application, however, i realised that for my application, as long as you have the link to the chat, you can enter. how do I prevent that, and make it such that only members of the group chat can access the chat. Something like password protected the url to the chat, or perhaps something like whatsapp. Does anyone have any suggestion and reference material as to how I should build this and implement the function? Thank you! -
Error Could not deserialize key data when Using RSA Algorithm Django Rest Framework Simple JWT
I got an Error when using django rest framework simple jwt authentication when i'm using algorithm RSA in [ SIMPLE_JWT ] when i'm using RS Algorithm my the code work very well but when i'm change the Algorithm to RS the error has raised like this: Could not deserialize key data. The data may be in an incorrect format or it may be encrypted with an unsupported algorithm. My Settings SIMPLE_JWT = { 'ALGORITHM': 'RS512', 'SIGNING_KEY' : 'ssh-rsa MIIBPAIBAAJBALZ+WuuTIol2cwEALcqn+/d0AER+sX269KVZt7sdl9C0QcspNHvHGYBWLoYIV5i72fsINX4V5IvkqsIn83O4jQMCAwEAAQJBAJ8E/Y73GAo2V8IQeNZ1iH646x7EUz9e8J1Az3PSNp7ZZ4tNjEhyA817qQGT9nfvRPXqIKkKFVe0THfmWmbK5cECIQD4M/qhoT2n99iIJwJq2DhbVvqx74hal+ocuboSwDZuIwIhALw58q4+YZlg79fGc2PyK8MUQLIx/i+O3bK7moMCf6OhAiEA04E/15IWf1clzsgnODMuuy9AjHaJJGIGHxpppObkuy8CIGqjwhRqD02gmAH90x5K8/RAIy9SF5rGLGC43R9gaQRBAiEAoLxLZuvXosXy6XR67ODCgZI7yB1XXVIwB73LxWXrnkk=', 'VERIFYING_KEY' : 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALZ+WuuTIol2cwEALcqn+/d0AER+sX269KVZt7sdl9C0QcspNHvHGYBWLoYIV5i72fsINX4V5IvkqsIn83O4jQMCAwEAAQ==' } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } Views and Other Using Djoser Package Request POST | http://localhost:8000/api/jwt/create/ username : userExample, password : ********** Note : Using Postman for testing -
How to save a python list object in Django into Redis hash using hset after getting model id's using values_list
I am trying to set a list object from Django values list inside my Redis hash using json.dumps() however, I get the error: the JSON object must be str, bytes or bytearray, not list Currently, I am getting the id's of a model using values_list: ids = list( Product.objects .filter(...) .values_list("id", flat=True) ) then I do: redis_client.hset('my-hash','subhashid',json.dumps(ids)) But I get that error. How can I save an array to a Redis hash? What would be the fastest way to encode/decode that array, I was trying to do it using json, but I get this error. -
Beginner question: Filtering dates to match the date of another model in Django
Beginner in Django here, I have been trying to work this out on-and-off for the last few days and have tried reading the docs and googling for solutions, but to no avail. My django project has two apps - blog and weather, each with a model. blog.models import datetime from django.db import models class BlogEntry(models.Model): date = models.DateField('Date') blog_name = models.CharField('Name',max_length = 255, null=True) weather.models import datetime from django.db import models class WeatherEntry(models.Model): date = models.DateField('Date') weather = models.CharField('Weather',max_length = 255, null=True) The weather app is meant to be filled in once daily, but the blog app is only to be filled in occasionally. Now, I want to produce a DetailView for my BlogEntry model which would also show the weather on the day the blog was created. My plan was to override get_context_data() but I could not filter the Weather queryset according to the date. In the view import datetime from django.views.generic.detail import DetailView from blog.models import BlogEntry from weather.models import WeatherEntry class BlogDetailView(DetailView): model = BlogEntry template_name = 'Blog/blog_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['weather'] = WeatherEntry.objects.filter(date__=date) return context I would get the error NameError: name 'date' is not defined. I've using F expressions too and they … -
Show person list based on group selection list in django
I'm pretty new in django/ Python and any help will be appreciated I'm trying to populate a list of person based on click on another list (Group) Model: class Grupo(models.Model): Nome = models.CharField(max_length=20) View class GruposListView(ListView): model = Grupo template_name = 'reports/relatorio_form.html' context_object_name = 'Grupo' HTML <h4 class="mb-3">Select a group:</h4> <select id="Group" name="Group" size="5"> {% for Grupo in Grupo %} <option value="Grupo">{{Grupo.Nome}}</option> {% endfor %} </select><br><br> -
How to save user when saving a form using post within Class-Based Views in Django
Currently the form instance is being saved but the user who filled out the information isn't being saved when I save this form. I am wondering how to grab the user and have it be added to the creation of the new form object. class ObjectListView(LoginRequiredMixin, FormMixin, ListView): model = Object template_name = 'ui/home.html' context_object_name = 'objects' form_class = OrderForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): form.save() order_type = form.cleaned_data.get('order_type') price = form.cleaned_data.get('price') **user = request.user** messages.success(request, f'Your order has been placed.') return redirect('account') -
Multiple-select form and query django
One of my fields in my model has a choice field: STATUS = Choices( ('first', _('car')), ('second', _('motorcycle')), ('third', _('bicycle')), ) My filter function looks like this: choice = request.GET.get('choice') vehicles = vehicles.filter(status=choice).order_by('-date_posted') The filter works, when I select only one choice, but when I am trying to select more than one choice it only catches the last one selected. The query looks like that: ?choice=first&choice=second Any idea how to make it, so it would display items, based on more than one choice? -
Why am I getting "No module named 'django_celery_beat'" after installing django_celery_beat to my virtual env and putting it in INSTALLED_APPS?
I am working on a Django project, and need to run cron tasks periodically to go through and delete all outdated files. I tried this same method with django_extensions and crontab, but I keep getting this same error. Within settings.py, I have: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Data_Science_Web_App', 'django_celery_beat', ] in my INSTALLED_APPS section. 'Data_Science_Web_App' is the name of my application. When I used pip3 install django_celery_beat, it worked fine. However, when I try to migrate changes, I get this message: (djangoenv) Daeyongs-Air:Data_Science_Project daeyong$ python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site- packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site- packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site- packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site- packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site- packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_celery_beat' When I check using pip freeze, it is evident that … -
Django Form Select From another model without Foreign Key
I want to make th_wali get value from another mode. In User_Admin model there is no 'th_wali' class InsertUser(forms.ModelForm): class Meta(): model = User_Admin fields = '__all__' labels ={ 'username': 'Username', 'password': 'Password', 'role' : 'Role', 'th_wali' : 'Tahun Wali', } widgets = { 'username':forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'username', 'required' : True, 'minlength' : 8, } ), 'th_wali':forms.ModelChoiceField(queryset=Mhs_SI.objects.values('th_masuk').distinct()), } I call in template like this, but doesn't show up <div class="form-group row"> <label class="control-label col-md-3 col-sm-3 ">{{formUser.th_wali.label_tag}}</label> <div class="col-md-9 col-sm-9 "> {{formUser.th_wali}} </div> </div> -
rdb vs key-value store for django functionality
Going through the django documentation, this sentence on mixins states: "In practice you’d probably want to record the interest in a key-value store rather than in a relational database..." Why? Why would one want to record the interest in a key-value store, as opposed to in my postgres db I already have for my django app? Does it affect performance? -
Filtering dropdown queryset based on URL parameter
I am building a CRM where I want each client to have multiple plans, and each plan to have multiple notes. When a user creates a new note, I want them to be able to select a relevant plan from a dropdown of plans belonging to the client. From what I can find, I should be able to get the contact_id from the kwargs, but my errors show nothing in kwargs. I know there should be a way to do this, but I can't seem to find it. Variable Value __class__ <class 'lynx.forms.SipNoteForm'> args () kwargs {} self <SipNoteForm bound=False, valid=Unknown, fields=(sip_plan;note;note_date;fiscal_year;quarter;class_hours;instructor;clients)> Views.py @login_required def add_sip_note(request, contact_id): form = SipNoteForm() if request.method == 'POST': form = SipNoteForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.contact_id = contact_id form.user_id = request.user.id form.save() return HttpResponseRedirect(reverse('lynx:client', args=(contact_id,))) return render(request, 'lynx/add_sip_note.html', {'form': form}) Forms.py class SipNoteForm(forms.ModelForm): class Meta: model = SipNote exclude = ('created', 'modified', 'user', 'contact') def __init__(self, *args, **kwargs): super(SipNoteForm, self).__init__(*args, **kwargs) self.fields['sip_plan'].queryset = SipPlan.objects.filter(contact_id=kwargs.get("contact_id")) Urls.py path('add-sip-note/<int:contact_id>/', views.add_sip_note, name='add_sip_note'), -
Wagtail profile avatar into ImageRenditionField serializer
I want to serialize the profile avatar from Wagtail admin with ImageRenditionField. Basing on the answer from the question I tried this: # models.py class User(AbstractUser): def get_avatar(self): return self.wagtail_userprofile.avatar # serializers.py class PersonSerializer(serializers.ModelSerializer): avatar = ImageRenditionField('width-190', source='get_avatar') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'avatar'] I got this: Django Version: 3.1.4 Exception Type: AttributeError Exception Value: 'ImageFieldFile' object has no attribute 'get_rendition' How do I throw user avatar into ImageRenditionField? -
Django formset.is_valid() returns False, creates additional forms (even with extra=0)
I have 2 formsets (RefLocFormSet and RefNoteFormSet), and one other form (ref_form) that I am displaying within one HTML element. The ref_form is split into 2 tabs, and the other 2 tabs on the page contain one formset each. If I make changes to the notes field in the first form in the RefLocFormSet shown below (i.e. by changing "Lethbridge and surrounding area" to some other text) and then press SAVE CHANGES, formset.is_valid() returns False. The cleaned_data for each form in the formset (which is set up to print in views.py when .is_valid() returns False), appears as follows: {'location_01': <location_01: Canada>, 'location_02': <location_02: Alberta (Province)>, 'ref_loc_note': 'Lethbridge and surrounding area, test', 'id': <location_join: Canada:Alberta (Province) (LastName2011: Title here)>} {'location_01': <location_01: Canada>, 'location_02': <location_02: Ontario (Province)>, 'ref_loc_note': 'GTA', 'id': <location_join: Canada:Ontario (Province) (LastName2011: Title here)>} {'location_01': None, 'location_02': None, 'ref_loc_note': ''} {'location_01': None, 'location_02': None, 'ref_loc_note': ''} [{}, {}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}] Although there should be only 2 forms in the formset, it appears that there are 4. Any ideas on how to stop these extra … -
Django / uwsgi / Docker Configuration
I have a working implementation of a Nginx, Uwsgi, and Django application running on a local server. I am trying to recreate the application minus the Nginx portion inside of a docker container, so that I can easily port it to a system like AWS. I am getting the following error message with the following configuration files. unable to load configuration from www-data I believe that this is due to a permissions error, as when I remove the --gid www-data flag, the process starts, but running in root mode, which curses the process. I have tried the following commands to no avail, with repo being the project folder. chown -R myuser:www-data Repo/ chmod -R 744 Repo/ Dockerfile FROM python:3.8 FROM node:12 RUN apt-get update && \ apt-get upgrade -y && \ apt-get clean -y && \ apt-get install -y --no-install-recommends apt-utils tar git build-essential python3 python3-pip python3-setuptools python3-dev net-tools RUN mkdir /var/log/uwsgi /shared COPY . /app WORKDIR /app RUN pip3 install --upgrade pip virtualenv RUN virtualenv venv RUN /bin/bash -c "source venv/bin/activate" RUN pip3 install --no-cache-dir -r requirements.txt RUN npm install --prefix frontend RUN npm run build --prefix frontend RUN ln -sf /dev/stdout /var/log/uwsgi/djangoapp.log && ln -sf /dev/stdout /var/log/uwsgi/emperor.log VOLUME … -
user can't create articles
from django.shortcuts import render,HttpResponse,redirect from . import models,forms from django.contrib.auth.decorators import login_required def articles_list(request): articles=models.Article.objects.all().order_by('-date') return render(request,'articles/articleslist.html',{'articles':articles}) def articles_detail(request,slug): # return HttpResponse(slug) article = models.Article.objects.get(slug=slug) return render(request,'articles/article_detail.html',{'article':article}) @login_required(login_url = "/userAccounts/login") def create_article(request): if request.method=='POST': form = forms.CreateArticle(request.POST,request.FILES) if form.is_valid: instance = form.save( commit = False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request,'articles/create_article.html',{'form':form})