Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django app deployment fails after trying to install python requirement
I installed django-user-visit with pip install django-user-visit , tested it in my local environment and everything seems to work fine, but when i try to deploy my app to production with Heroku i get the following error : remote: Collecting django-cors-headers==3.6.0 remote: Downloading django_cors_headers-3.6.0-py3-none-any.whl (12 kB) remote: ERROR: Could not find a version that satisfies the requirement django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) (from versions: none) remote: ERROR: _No matching distribution_ found for django-user-visit==0.4.1 (from -r /tmp/build_940d12d0/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed Does anyone know why Heroku can't find the package and if i can fix this ? My packages are being installed by running the libraries indicated in my requirements.txt file: asgiref==3.3.1 Django==3.1.5 django-cors-headers==3.6.0 django-user-visit==0.4.1 djangorestframework==3.12.2 gunicorn==20.0.4 psycopg2==2.8.6 pytz==2020.5 sqlparse==0.4.1 ua-parser==0.10.0 user-agents==2.2.0 whitenoise==5.2.0 What i've tried so far is to change the version to 0.4 and to not specify a version at all -
How can I use regex in django's Replace function
I'm trying to update all urls in my query by using django's update and Replace function using regex. Here's what I've tried so far but it seems like django's Value expression did not recognize my regex. from django.db.models import Value from django.db.models.functions import Replace Foo.objects.filter( some_url__iregex=r'^\/some-link\/\d+\/').update( some_url=Replace( 'some_url', Value(r'^\/some-link\/\d+\/'), Value('/some-link/'))) My goal is to remove all numbers after /some-link/ (e.g. /some-link/55/test to just /some-link/test) -
Django - Cannot get console.log to output in VSCode Terminal
I'm new to using Javascript with django and am trying to use console log to test my Javascript code but am having trouble getting it to work. I check the terminal, outpout, problems, and Debug console but none show the output of console.log. I know my javascript is working because the ui dropdown menu is populated when I use the ajax code below and it displays nothing if I remove it. However, I cannot tell if the event listener is working.. here is my html: <div class="ui selection dropdown" id = "cars"> <input type="hidden" name="car"> <i class="dropdown icon"></i> <div class="default text">Choose a car</div> <div class="menu" id = 'cars-data-box'> </div> </div> Here is my Javascript const carsDataBox = document.getElementById('cars-data-box') const carInput = document.getElementById('cars') $.ajax({ type: 'GET', url: '/cars-json/', success: function(response){ console.log(response) const carsData = response.data carsData.map(item=>{ const option = document.createElement('div') option.textContent = item.name option.setAttribute('class', 'item') option.setAttribute('data-value', item.name) carsDataBox.appendChild(option) }) }, error: function(error){ console.log(error) } }) carInput.addEventListener('change', e=>{ const selectedCar = e.target.value console.log(response) }) urls.py urlpatterns = [ path('', page), path('cars-json/', get_json_car_data), ] views.py def page(request): qs = Car.objects.all() return render(request, 'testenv/home.html', {'qs' : qs}) def get_json_car_data(request): qs_val = list(Car.objects.values()) return JsonResponse({'data' : qs_val}) -
heroku[router]: at=error code=H14 desc="No web processes running" (Deploying Docker Image)
So trying to deploy a docker image, these are my setting, and these are the errors i keep getting. I keep getting the error heroku[router]: at=error code=H14 desc="No web processes running". I've installed posgres plugin on heroku and also have a dynos active. docker-compose.yml: version: "3" services: {redacted}: build: context: . ports: - "8000:8000" volumes: - .:/{redacted} command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST={redacted} - DB_NAME={redacted} - DB_USER={redacted} - DB_PASS={redacted} depends_on: - db db: image: postgres:12-alpine environment: - POSTGRES_DB={redacted} - POSTGRES_USER={redacted} - POSTGRES_PASSWORD={redacted} Dockerfile: FROM python:3.8-alpine MAINTAINER {redacted} ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /{redacted} WORKDIR /{redacted} COPY . /{redacted} RUN adduser -D user USER user requirements.txt: asgiref==3.2.10 beautifulsoup4==4.9.1 bootstrap4==0.1.0 certifi==2020.6.20 chardet==3.0.4 dj-database-url==0.5.0 djangify==1.0.0 Django==3.1 django-bootstrap4==2.2.0 django-crispy==1.8.1 django-filter==2.4.0 django-heroku==0.3.1 django-i18n==1.0.4 djangorestframework==3.12.1 djangorestframework-simplejwt==4.6.0 flake8==3.8.4 gunicorn==20.0.4 heroku==0.1.4 idna==2.10 mccabe==0.6.1 psycopg2==2.8.5 psycopg2-binary==2.8.6 pyclean==2.0.0 pycodestyle==2.6.0 pyflakes==2.2.0 PyJWT==2.0.1 python-dateutil==1.5 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 slugify==0.0.1 soupsieve==2.0.1 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==5.2.0 settings.py: from pathlib import Path from datetime import timedelta import django_heroku import os # Build paths inside … -
Django saving the registration extends AbstractBaseUser
Good day SO. I am new to Django and having troubles with something basic. When I click on sumbit, the template returns my Account(the OneToOneField) This field is required. Though my methods might be not aligned with good practice, but I hope that you can help me with this. I have been trying to check with other resources for two days but I can't seem to find the solution to my concern. Here is my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Account, CompanyAccount class AccountCreationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text="Required") class Meta: model = Account fields = ("email", "username", "password1", "password2", "account_type") class CompanyAccountForm(forms.ModelForm): class Meta: model = CompanyAccount fields = "__all__" my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, account_type, password): if not email: raise ValueError("Users must have an Email Address") if not username: raise ValueError("Users must have an Username") if not account_type: raise ValueError("Users must have an Account Type") user = self.model( email=self.normalize_email(email), username=username, password=password, account_type=account_type, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, account_type, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, account_type=account_type, ) user.is_admin = True user.is_staff … -
Flask or Django Framework Livestream
how can i get livestream on yt etc. with API with on flask or django to my website i want to add livestream for example tv stream, i researched but i didnt find anything on google. how can i get this can u help me ? For example I reserved a certain area for live broadcast on my website, I add live broadcast stream to that area, but I want to broadcast live broadcast on my site, for example youtube or twitch api on the internet, not webcam broadcast. #!/usr/bin/env python from flask import Flask, render_template, Response from camera import Camera app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) This is not what I want. -
composite key not displaying orrecyl on django admin
I have an intermediary model betwen "estados" e "listaflor", the flora2estado uses a composite key- and a primary key to trick django not to throw errors at me-. When i click in one object at django admin i get this error: MultipleObjectsReturned at /admin/accounts/flora2estado/99/change/ get() returned more than one Flora2Estado -- it returned 5! my models.py class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'estados' class Familia(models.Model): familia_id = models.AutoField(primary_key=True) familia_nome = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'familia' class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, ) especie_id = models.IntegerField() flora2estado_id = models.AutoField( primary_key=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie_id'),) admin.py admin.site.register(Flora2Estado) -
How to make a variable number of fields in django models?
I want to make a model of Grades of students and this model has a variable number of fields that I can change from the admin page. -
django: FileField model - 404
This is my first Django project and I have one problem. file1 is saved to media folder\files however when I try to download the file I'm getting 404. Any help is appreciated! 127.0.0.1:8000/about/files/2021/01/22/pyqt_tutorial_EB2ZapN.pdf models.py class Links(models.Model): file1 = models.FileField(upload_to = 'files/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) html {% for link in links %} <div class="links1"> <h3><a href = "{{ link.file1 }}">Download Link</a></h3> <p>{{ link.publish_date }}</p> </div> {% endfor %} urls.py> urlpatterns = [ path('admin/', admin.site.urls), path('about/', about, name = 'about') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py> # Media Folder Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Update: from the admin panel if I click on the link I can see it. Maybe In the {{ link.file1 }} url something need to be changed? -
How do I import a model from another app in Django?
So in my project book_letter, I have an app named contents. Inside it, I have a model named Book. As below. class Book(models.Model): objects = models.Manager() title = models.CharField(max_length = 30) author = models.CharField(max_length = 20) def __str__(self): return self.title And I have another app named recommendation, with a model named Recommendation. As below. from book_letter.contents.models import Book class Recommendation(models.Model): objects = models.Manager() source = models.ForeignKey("Book", related_name='book', on_delete=models.CASCADE) However, when I run python manage.py runserver, I get an error saying ModuleNotFoundError: No module named 'book_letter.contents' I don't see what I've done wrong. Any ideas? Thanks :) -
Django: Group by foreign key then get max id from group
I'm looking to grab the latest message in a conversation. My conversation model has attributes id (primary key) and user1 and user2, which are both foreign keys to a User model. My message model consists of a conversation(foreign key) and message primary key. These both just return only the very latest message. Message.objects.values('conversation').latest('id') Message.objects.order_by('conversation').latest('id') Any recommendations for getting this query? -
Django access pk id in class
I have this site, and I want to be able to have views. When you go to url /post/int:pk it shows the post in more detail. When the user goes here, I want to add one to an field in models.py. Here is models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=0) people_read = models.IntegerField(default=0) # Add one to this data user_liked = models.ManyToManyField(User, related_name='user_liked') user_disliked = models.ManyToManyField(User, related_name='user_disliked') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) And views.py: class PostDetailView(DetailView): model = Post post = get_object_or_404(Post, pk=pk) post.people_read = post.people_read + 1 post.save() The problem with this is that it won't get the pk id. So how do I get the posts pk in an class, or is there another way to add to a models field when going to a url? Thanks. -
Add additional fields to form after click - the node before which the new node is to be inserted is not a child of this node
I have a form in which I need to add a button that will allow the user to add a new field. I'm trying to do it with javascript, but since I don't know much this language I'm lost with some concepts. The form I use is one where the data is completed in steps, and the fields I want to add are the following <div class="job-form row mb-3"> {% for form in add_trabajo %} <div class="col-md-6"> <label for="ref" class="">Nombre</label> {% render_field form.trabajo class="form-control" type="text" placeholder="Ej: Reparación de envolvente delantero" %} </div> <div class="col-md-2"> <label for="ref" class="">Descuento</label> {% render_field form.descuento class="form-control" type="text" %} </div> <div class=" col-md-2"> <label for="ref" class="">Precio</label> {% render_field form.precio class="form-control" type="text" %} </div> <div class="col-md-2 d-flex align-items-end"> <button id="addButton" type="button" class="btn-icon btn-icon-only btn btn-success p-2"><i class="pe-7s-plus btn-icon-wrapper"> </i></button> </div> {% endfor %} </div> I'm trying to add these fields after existing ones that are identical I already have the button and some code in javascript but it indicates the following error Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. at HTMLButtonElement.addForm This is my javascript code let jobForm … -
Django File upload in model
Considering that we`ve got the model below: class Project(models.Model): file1 = models.FileField(upload_to='projects/', blank =True) file2 = models.FileField(upload_to='projects/', blank =True) file3 = models.FileField(upload_to='projects/', blank =True) file4 = models.FileField(upload_to='projects/', blank =True) file5 = models.FileField(upload_to='projects/', blank =True) How many file1 can we create? If I want to create severals files, I usually write my code this way: class File1(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) file = models.FileField(upload_to='projects/', blank =True) Instead to create severals models File1, File2, File 3, Is there a way to upload several file1 in Django using only the model Project? I mean to not have to create a model for each file1, file2, file3 if we need to upload several of them. Many Thanks, -
django project not working with apache2, working ok with inbuilt web server
I have a django project and working with the in-built webserver. I am trying to move it to apahce and having trouble.Would anyone please be able to help. My project structure is: home/p/prjct |-- setest | `-- wsgi.py | |-- manage.py |-- penve | |-- hello | |-- tsts penve is the virtual environment hello and tsts are apps. I have made changes in my apache2.conf and it looks like: WSGIScriptAlias / /home/p/prjct/setest/wsgi.py WSGIPythonHome /home/p/prjct/penve WSGIPythonPath /home/p/prjct <Directory /home/p/prjct/setest> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> DocumentRoot /home/p/prjct Listen 80 AccessFileName .htaccess <FilesMatch "^\.ht"> Require all denied </FilesMatch> LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent Am I missing something. Thanks in advance for help. sp -
Django Email Token Sending Blocked
For a user registration, I try and send a url that the user has to click in order to register. This url contains a uid, and token. However, gmail seems to block emails from the specified email in settings.py when I try and send them. I think it's because my local address is used as the website for now and which is seen as 'less secure' but I am not exactly sure why. I know it has to do with the token because when I send an email with just text in the body, it does not pose an error. The error is shown as below: Here is the email body (note that when I simply change this to text, the email is sent): email_body = render_to_string('mainapp/acc_activate_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) -
how do you add an avatar profile to django inbuilt forms?
How can you add a field to add images on a inbuilt Django form? Here is the code of my form.py: class CreateUserForm(UserCreationForm): password1 = forms.CharField( label="Password", widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Password'}), ) password2 = forms.CharField( label="Confirm password", widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Confirm Password'}), ) class Meta(UserCreationForm.Meta): model = get_user_model() widgets = { 'username': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Username'}), 'first_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'First Name'}), 'last_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Last Name'}), 'email': EmailInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Email Address'}), } fields = ['username', 'first_name', 'last_name', 'email'] -
VSCode pytest test discovery fails when debugging Django tests
I'm trying to debug my first django test, but VSCode is returning: Ran 0 tests in 0.000s. On the other hand, when I use an integrated git bash (I'm using a windows OS) in VSCode terminals or externally, it returns: Ran 1 test in 0.0014s. It also echoes FAILED and a traceback for a valid error within the test. My vscode launch.json: { ... "configurations": [ ... { "name": "Django Tests", "type": "python", "request": "launch", "program": "${workspaceFolder}\\testprojectname\\manage.py", "args": [ "test" ], "django": true, } ] } My vscode settings.json: { "python.pythonPath": "C:\\Users\\user\\.virtualenvs\\backend-Vg-KBKTA\\Scripts\\python.exe", "python.testing.pytestEnabled": true, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": false, "python.testing.pytestArgs": [ "testprojectname" ] } Note that C:\Users\user\.virtualenvs\backend-Vg-KBKTA\Scripts\python.exe is a valid path to the pipenv shell [(1) it is echoed when I type in the bash: pipenv --venv (2) it works when I launch the django debugger] So far, I've tried: Updating my pytest according to VSCode pytest test discovery fails Changing around the name of my tests.py file to test_example.py according to Pytest - no tests ran Changing the class of the tests to prefix with Test_ according to the same link in (2) This is what the test currently looks like class Test_Contacts(unittest.TestCase): def test_create_contact_message(self): """Create a new contact message.""" … -
Postgres - can't acces database, no acces
I am trying to acces my postgres database but I am having permission denied error. I created database + table(was created in python but it is there): sudo -u postgres psql postgres=# create user lukasz1 with encrypted password '<password>'; postgres=# create database mydatabase owner lukasz1; So far so good: List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ------------+----------+----------+-------------+-------------+----------------------- mydatabase | lukasz1 | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =Tc/lukasz1 + | | | | | lukasz1=CTc/lukasz1 postgres | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | template0 | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) and lukasz1 is an owner of mydatabase. But when I try to connect it I am having permission denied. I can't even select from my table to view it as permission is denied: mydatabase=> select article_id from articles; ERROR: permission denied for table articles I checked multiple anwers to simmilar questions and tried checking user valid_until and got an empty values in that column: mydatabase=> select usename, valuntil from … -
Django Image upload not POSTing
I am trying to let a user upload and change their picture. Currently the form displays the current picture for the user without any issues, but I seem to have messed something when it comes to the upload part since the upload is not working (no error messages). Also, is it possible to create a custom image form? Currently, this makes use of Djangos default one which is not that style-friendly. Views.py @login_required def edit(request): if request.method == "POST": FormImage= UserProfileForm(request.POST, request.FILES, instance=request.user) if FormImage.is_valid(): FormImage.account_id = request.user.id FormImage.save() return HttpResponseRedirect(request.path_info) else: imageForm = UserProfileForm(instance=request.user) return render(request, 'accounts/info.html', { "FormImage": FormImage, }) Forms.py class UserProfileForm(UserChangeForm): FRUIT_CHOICES = ( ('Banana', 'Banana'), ('Orange', 'Orange'), ('Apple', 'Apple'), ) fruits = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES)) class Meta: model = Account fields = ( 'fruits', 'profile_picture', ) Template <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <label class="col-lg-3 col-form-label form-coantrol-label">Change picture</label> <div class="col-lg-9"> {{ FormImage.profile_picture }} </div> <div class="form-group row"> <div class="container"><input class="btn btn-primary" type="submit" value="Save profile"></div> </div> </form> My model field for profile pic profile_picture = models.ImageField(default="default.png", null=True, blank=True) -
How register and login in django in same time with class based views?
I have a simple registration view, i want to create a view can register user and login him at same time. my code not working, what should do i do to do it? my views.py: class user_register(SuccessMessageMixin,CreateView,): model = User template_name = 'register.html' success_url = reverse_lazy("company:home") form_class = UserRegisterationForm success_message = "You registered successfully." def form_valid(self,form): user = authenticate(username=form.cleaned_data.get('username'),password=form.cleaned_data.get('password')) if user is not None: login(self.request,user) return redirect('company:home') return super().form_valid(form) -
How to pass the product id dynamically to the Django view?
How to change (id=3) automatically? When I click on a product to get a detailed view, the slug in the url is correct, but the displayed data doesn't match. views.py works fine: def product_detail_view(request, slug_text): obj = Product.objects.get(id=3) context = { 'object': obj } return render(request, 'store/product.html', context) urls.py works fine: urlpatterns = [ path('<slug:slug_text>/', views.product_detail_view, name ="product"), ] -
Duplicated querysets in each view - django
I have a few querysets that I need in each of my view. I'm wondering if there is a better way that duplicating those in every single view. Querysets results are the same for every view They look like this Company_user = Company.objects.get(User = request.user) User_info = User_info.objects.get(User = request.user) Groups_user = request.user.groups.values_list('name',flat = True) Sales_company = Sales.objects.filter(Company = Company_user) -
Django + https on localhost
I have files of TLS certificate(.crt) and key(.key) How can i add them in settings.py and run localhost with https( it is need to add them as text variables not path to these files)? Thanks in advance! -
python - django extra_context wont show
I have a form in ListView view using FormMixin that form takes a string lastname and querys to take a queryset of Account object, I want that Queryset on my template via extra_context. The form works and I have the queryset that I want, I pass it into self.extra_context and I can see it on console with print BUT it dosent show in my template. Im feeling stacked, please help me if tou can. def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): lastname = form.cleaned_data['lastname'] lastname = valuateLastname(lastname) self.extra_context['operators'] = Account.objects.filter(is_active=True, department=self.request.user.department, last_name__contains=lastname) print(self.extra_context['operators']) return super(DepartmentFilesListView, self).form_valid(form) In my template I can see anything else is in my self.extra_context but anything Im tried to pass in my form_valid function doesnt shown. It is like my extra_context cant update in this function.