Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to split a form field to display multiple values in Django
My Journey model contains two fields, distance and time: class Journey(models.Model): distance = models.PositiveIntegerField(default=0) time = models.PositiveIntegerField(default=0) I am trying to create a Modelform where the time field will be split to display inputs for 'hrs', 'min' and 'sec'. I would then like these values to be compressed in order to return one single value. Currently my forms.py looks like this: from django import forms from django.forms import MultiWidget from .models import Journey class DistanceTimeModelForm(forms.ModelForm): time = forms.MultiValueField(widget=MultiWidget(widgets=[forms.IntegerField(attrs={'placeholder': 'hrs'}), forms.IntegerField(attrs={'placeholder': 'min'}), forms.IntegerField(attrs={'placeholder': 'sec'})]), require_all_fields=True, error_messages={'incomplete': 'Please enter a number'}) class Meta: model = Journey fields = ['distance', 'time'] I am receiving TypeError: __init__() got an unexpected keyword argument 'attrs' when I attempt to run the server. Is anyone able to help me understand how to fix this? I have been searching for a solution online for some time but so far am still stumped. -
getting issue when trying to build docker image on aws on ubuntu 18.04
I am trying to build a docker image on AWS for Defect-Dojo using the below method I have cloned the defect dojo repo from github and trying to build the docker image using this git clone https://github.com/DefectDojo/django-DefectDojo cd django-DefectDojo # building sudo docker-compose build when I run sudo docker-compose build, it throws the following error. I am unable to get the reason. any help please. I am a newbie to docker. thanks here is the output. <pre>mysql uses an image, skipping initializer uses an image, skipping rabbitmq uses an image, skipping celeryworker uses an image, skipping celerybeat uses an image, skipping Building uwsgi Step 1/23 : FROM python:3.5.7-buster@sha256:4598d4365bb7a8628ba840f87406323e699c4da01ae6f926ff33787c63230779 as build ---&gt; 4ae385ba9dd2 Step 2/23 : WORKDIR /app ---&gt; Using cache ---&gt; 4cebcde37520 Step 3/23 : RUN apt-get -y update &amp;&amp; apt-get -y install dnsutils default-mysql-client postgresql-client xmlsec1 git &amp;&amp; apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists &amp;&amp; true ---&gt; Using cache ---&gt; 9fee66bc8f58 Step 4/23 : COPY requirements.txt ./ ---&gt; Using cache ---&gt; b30515f1dfcc Step 5/23 : RUN pip3 wheel --wheel-dir=/tmp/wheels -r ./requirements.txt ---&gt; Using cache ---&gt; 6c5e964ee4ac Step 6/23 : FROM python:3.5.7-slim-buster@sha256:127fee645393d311c7fbc5e8c2e5034f10a4e66b47c9273d4dbe5da2926fc3f2 ---&gt; 5b0283c5034b Step 7/23 : WORKDIR /app ---&gt; Using cache ---&gt; fc28b1a681b0 Step 8/23 : RUN apt-get -y … -
Set currently logged in user as the user in the model when creating an object in Django
I've tried to implement the solutions offered by some of the other posts I see on here, but nothing seems to be working. I'm brand new to django and backend in general, so I may just be lacking in skill. The situation is that I'm letting users generate a listing based on a django model Listings using a ModelForm. Everything seems to be working except for the fact that I can't set the currently logged in user as the user for the listing. I understand that the user is stored in request.user, but I can't seem to set it within my form and I consistently get this error: IntegrityError at /create NOT NULL constraint failed: auctions_listings.listing_user_id Here's the code for my User and Listings model: class User(AbstractUser): pass class Listings(models.Model): title = models.CharField(max_length=64, default="") description = models.TextField(default="") image = models.URLField(blank=True, null=True) initial_bid = models.DecimalField(max_digits=8, decimal_places=2) category = models.CharField(max_length=64, default="Misc") listing_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing_user") # listing.bid.all()???? and here is my form: from .models import Listings class ListingsForm(forms.ModelForm): class Meta: model = Listings exclude = ('listing_user') fields = [ 'title', 'description', 'image', 'initial_bid', 'category' ] Some of the suggestions I've found have figured out that I can excluse the user requirement … -
I want to make a website like StreamYard, what technology can I use?
I want to make a website like StreamYard, I want my website to have live streaming, screen sharing with the audience, file uploading. I have some experience in Django. Can I use Django to make a website like this? -
How to use the bulk_update with multiple fields?
Here user from the frontend gives the list of values like this ['1','2'] for the model fields so I tried to use the bulk_update but this way neither it is giving me any error nor updating the values of the fields. I tried the similar way for creating with bulk_create and it worked perfectly but with the update it is not working. What I am doing wring here ? models class PVariant(models.Model): name = models.CharField(max_length=255, blank=False, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) sku = models.CharField(max_length=255, blank=True, null=True) ..other fields views names = request.POST.getlist('name') print(names)#['mark','ed'] up = request.POST.getlist('ups') print(up) # ['12','13'] sku = request.POST.getlist('sku') #['1','2'] fields = ['name', 'up', 'sku'..] params = zip(names, up, cp, sku, quantity, weight, v_attributes) #PVariant.objects.filter(product=product).update() variants = [PVariant(name=param[0], up=param[1], sku=param[2],product=product..) for param in params] PVariant.objects.bulk_update(variants, fields) -
Getting NoReverseMatch even though url patterns are correct?
I've been learning Django for like a month so apologies if I'm doing something stupid, but, I'm getting a NoReverseMatch Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<use>[^/]+)$'] error when trying to render a "profile" page under the url '/profile/[a user's name]', and I'm pretty sure all my paths/patterns are correct?? Here's my code, could someone help me with this? All my other url patterns work fine. This path also worked fine before, I just renamed the "user" variable into "use" and this happened. urls.py: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("profile/<str:use>", views.profile, name="profile"), path("following", views.following, name="following"), #api path('', include(router.urls)), ] views.py: def profile(request, use): currentuser = str(request.user) followers = [] following = [] for follow in Follow.objects.filter(following=use): followers.append(follow.person) for item in Follow.objects.filter(person=use): following.append(item.following) follower_count = len(followers) following_count = len(following) try: Follow.objects.get(person=currentuser, following=use) followed = True except: followed = False post_list = Post.objects.filter(user=use) dates = [] for post in post_list: dates.append(post.timestamp) dates.sort(key = lambda date: datetime.strptime(date, '%B %d, %Y, %I:%M %p'), reverse=True) formattedlist = [] for date in dates: postobject = Post.objects.get(timestamp=date) formattedlist.append(postobject) paginatorlist = Paginator(formattedlist, 10) now_page_content = paginatorlist.page(1) nowpage = 1 if request.method == "POST": … -
Django | Redirect on First Login
I have to assume I'm going about this the wrong way... But I'm just learning Django, so I'd like some help. I have a basic blog app. I'd like a user to be taken to the feed regularly after login, but I'd like the user to be taken to their profile on the very first login. Right now, this is in my settings.py: LOGIN_REDIRECT_URL = 'Home' LOGIN_URL = 'login' So, the user is always taken to the feed, 'Home'. I've tried importing the User model to settings and attempted something like this: if not User.last_login: LOGIN_REDIRECT_URL = 'Profile' else: LOGIN_REDIRECT_URL = 'Home' LOGIN_URL = 'login' but as soon as I've imported the User model to the settings.py file, the server will no longer run. I guess that's something I can't do. What's the best approach to achieve the desired outcome? -
Create Log files in Python-Djnago application
i want to create log files in daily basis, want a log file for each day with date in file name and automatic generate log files for each day and automatic rename with date i added a log details in settings.py and tried to add log details . my code is showing below But no log file is creating , no data is writing in the log files. error.log always showing empty and not renaming with date my setting.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {asctime} {module} {funcName} {lineno:d} {message}', 'style': '{', } }, 'handlers': { 'errors_file': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_DIR, './log/error.log'), 'when': 'D', 'interval': 1, 'formatter': 'simple', }, }, 'loggers': { 'error_logger': { 'handlers': ['errors_file'], 'level': 'WARNING', }, }, } my view.py try: dev_id = Device.objects.get(DeviceId=input_data["DeviceId"]) return Response({msg: validation["FDP34"]}, status=status.HTTP_200_OK) logging.getLogger("error_logger").exception(validation["FDP34"]) else: return Response({msg: validation["FDP35"]}, status=status.HTTP_400_BAD_REQUEST) logging.getLogger("error_logger").exception(validation["FDP35"]) except Device.DoesNotExist: logging.getLogger("error_logger").exception(validation["FDP8"]) -
My comments are not being displayed in a django blog
I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site. The snippet of my code is below. views.py from .models import Post from django.utils import timezone from .forms import PostForm, CommentsForm from django.contrib.auth.decorators import user_passes_test # Create your views here. def home(request): return render (request, 'blogapp/home.html') def blog_list(request): post = Post.objects.order_by('-published_date') context = { 'posts':post } return render(request, 'blogapp/blog_list.html', context) def blog_detail(request, pk=None): detail = Post.objects.get(pk=pk) context = { 'detail': detail } return render(request, 'blogapp/blog_detail.html', context) def add_post(request, pk=None): if request.method == "POST": form = PostForm(request.POST) if form.is_valid: body = form.save(commit=False) body.published_date = timezone.now() body.save() return redirect('blog_list') form = PostForm() else: form = PostForm() context = { 'form': form } return render(request, 'blogapp/add_post.html', context) def add_comments(request, pk=None): if request.method == "POST": form = CommentsForm(request.POST) if form.is_valid: comment = form.save(commit=False) comment.date_added = timezone.now() comment.save() return redirect('blog_detail') form = CommentsForm() else: form = CommentsForm() context = { 'form': form } return render(request, 'blogapp/add_comments.html', context) urls.py from django.urls import path from . import views urlpatterns … -
how do i provide a Foreign key for two models
let us consider two models Quotes and QuoteUsers. class QuoteUsers(models.Model): created_at = models.DateTimeField(auto_now_add=True) ip_address = models.GenericIPAddressField(blank=True, null=True) class Quote(models.Model): quote_number = models.IntegerField() job_title = models.CharField(max_length=50, blank=True, null=True) reference = models.TextField(blank=True, null=True) quote_type = models.CharField(max_length=45, blank=True) Now here i want to ip_address of each quote and in which model should i apply my ForeignKey and how can i filter the model ? -
Error Message: Internal Server Error Heroku
I keep getting this error when launching my heroku app Internal Server Error then I went to cmd and did this heroku logs --tail and I found out the error was ModuleNotFoundError: No module named 'main.url' my rules from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.url")), ] then I went to settings.py and on my ROOT_URLCONF = 'mysite.urls' I changed instead of mysite.urls I put just urls I still get the same Error message ModuleNotFoundError: No Module named urls my settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a49c&2is^-d$y8ycdycbenh*@dm3$3phszrs_72c*fh-ti1449' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # remember to change to false ALLOWED_HOSTS = ['anim3-domain.herokuapp.com'] # 'https://anime-domain.herokuapp.com/' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', … -
My Django app doesnt Run again on my local computer Since i changed to Heroku postgrel database
my database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DatabaseName', } } DATABASE_URL = os.environ['DATABASE_URL'] conn = psycopg2.connect(DATABASE_URL, sslmode='require') import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) When ever I try run the server on my computer it shows the error .It happened when i tried changing my database fromsqlite to postgre. the error File "C:\Users\stephen\favprojects\favprojects\settings.py", line 94, in <module> DATABASE_URL = os.environ['DATABASE_URL'] File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'DATABASE_URL' -
why do I get error in Django : unsupported operand type(s) for |: 'Model' and 'Model'
So I have a model named Question. There are three types of objects in Question, and I'm trying to query those objects separately, then merge first objects of each. Like this: def getQuestion(request): typeOne = Question.objects.filter(type=1).order_by('question_number') typeTwo = Question.objects.filter(type=2).order_by('question_number') typeThree = Question.objects.filter(type=3).order_by('question_number') questionsOfTheDay = depthOne[0] | depthTwo[0] | depthThree[0] # I've tried below as well, with chain imported # questionsOfTheDay = chain(depthOne[0], depthTwo[0], depthThree[0]) serialized = QuestionSerializer(questionsOfTheDay, many=True) return Response(serialized.data) I don't see what I've done wrong, but I keep getting the error "unsupported operand type(s) for |: 'Question' and 'Question'". What do you think is the problem? I appreciate it in advance. -
XmlHttpRequest request element is None
I am using Django and trying to send webcam data using XMLHttpRequest to background (view.py) in order to process each frame. I follow this link and most people suggests similar method for my problem. $(document).ready(function(){ $('#trigger_button').click(function(){ navigator.mediaDevices.getUserMedia(constraints) .then(stream => { document.getElementById("myVideo").srcObject = stream; }) .catch(err => { alert('navigator.getUserMedia error: ', err) }); drawCanvas.width = v.videoWidth; drawCanvas.height = v.videoHeight; imageCanvas.width = uploadWidth; imageCanvas.height = uploadWidth * (v.videoHeight / v.videoWidth); drawCtx.lineWidth = 4; drawCtx.strokeStyle = "cyan"; drawCtx.font = "20px Verdana"; drawCtx.fillStyle = "cyan"; imageCanvas.getContext("2d").drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth)); imageCanvas.toBlob(postFile, 'image/jpeg'); }); }); function postFile(file) { var formdata = new FormData(); formdata.append("image", file); formdata.append("threshold", scoreThreshold); var xhr = new XMLHttpRequest(); xhr.open('POST', apiServer, true); xhr.onload = function () { if (this.status === 200) { var objects = JSON.parse(this.response); drawBoxes(objects); imageCtx.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth)); imageCanvas.toBlob(postFile, 'image/jpeg'); } else { alert(this.status); } }; xhr.send(formdata); } Then, I am trying to access data in the request in view.py as follow: def control4(request): print(request.POST.get('image')) print(request.POST.get('threshold')) return render(request, 'local.html') However, although request.Post.get('threshold') returns a value, request.POST.get('image') returns None. Besides, this method repeats three times and then it stops to send feedback. I … -
define you own Meta class options
the following link list all possible metadata options for a Django model: https://docs.djangoproject.com/en/3.1/ref/models/options. Does Django provide a framework to extend the list by defining my own metadata options? e.g., I want to add a custom option secured = True to mask the value of some fields. If so, how? -
Django TypeError 'dict' object is not callable
I get an Error for the line: username = login_form.cleaned_data('username'), because somewhere it seems to be a dict, but I cannot understand why. Can anyone please tell me, what the problem is? views.py def index(request): return render(request, 'web/base.html') def register_view(request): register_form = UserCreationForm() if request.method == "POST": register_form = UserCreationForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data("username") password = register_form.cleaned_data("password1") user = authenticate(request, username=username, password=password) if user: login(request, user) return render(request, 'web/register.html', {'register_form': register_form}) def login_view(request): login_form = AuthenticationForm() if request.method == 'POST': login_form = AuthenticationForm(data=request.POST) if login_form.is_valid(): username = login_form.cleaned_data('username') password = login_form.cleaned_data('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return render(request, 'web/login.html', {'login_form': login_form}) def logout_view(request): logout(request) return redirect(reverse('web:index')) -
How to select data from oracle table and return into nested json with django rest framework
I have data in oracle as below And I want to return nested json like this I have data in oracle as below Currently I have to create another table for machine code to use foreign key in models.py and serializers.py but I want to know is it possible to select from 1 table and return into nested json? -
how to display the information that related to a specific user
i have this Model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = models.CharField(max_length=200, null=False) zipcode = models.CharField(max_length=200, null=False) date_added = models.DateTimeField(auto_now_add=True) and this view def view_profile(request): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.all() args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} return render(request, 'store/profile.html', args) template {% for sa in shippingAddress %} <p>address: {{ sa.address }}</p> <p>city: {{ sa.city }}</p> <p>state: {{ sa.state }}</p> <p>zipcode: {{ sa.zipcode }}</p> {% endfor %}`enter code here` the problem is the template display all the Shipping Addresses in the DB and i want it just to display the Shipping Address that related to the signed in user Thanks -
Translating a pluralized string in Django
When working with a translated string that needs a pluralized word, is it best to just pass in the pluralized word or use ngettext and have a singular/plural sentence? Example 1 (passing in the pluralized word): ugettext("You have {count} {apple_pluralized}").format( count=apple_count, apple_pluralized=ngettext("apple", "apples", apple_count) )` Example 2: ngettext("You have {count} apple", "You have {count} apples", apple_count).format(count=apple_count) My understanding is the second approach is always recommended because it's not always as simple as swapping in a word. For example, even in English, there is 1 object vs there are 2 objects. Is this correct? And if so, are there any situations where the first approach might be preferred? -
not able to access any course materiel in open edx
I have installed open edx and now want to set up ios app but I can not see my courses content I get this error ( your action could not be completed) -
Django admin: created users have plain text password and can't login
I want to have a custom tab for staff users so in admin.py I do: class StaffUser(User): class Meta: proxy = True @admin.register(StaffUser) class AdminUserAdmin(admin.ModelAdmin): pass But on the admin site, whenever I add a new user with this interface I can't log in with it since for some reason it sets it's password as plain text instead of hashing it. I've read this post BUT if I do that and change StaffUser to inherint from AdminUserI get this other error AttributeError: type object 'StaffUser' has no attribute '_meta' -
How to print all model fields ignoring reverse related and relates fields
I am trying to print all model fields and their values as follows def pretty_print_model_fields(m: Model): if not m: data = None else: data = {} for f in m._meta.fields(): data[f.name] = getattr(m, f.name) return data The issue is some of reverse_related does not exist -> error RelatedObjectDoesNotExist How can I ignore reverse_related and related fields all together -
When deploying Django application on cpanel, application does not connect to static files
I am trying to deploy django application from cpanel. I have managed to deploy the site and everything works apart from the static files part, because my website loads without any styling. My settings.py part looks like this : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'assets'), ] STATIC_ROOT= os.path.join(BASE_DIR,'static') When I run command on cpanel terminal command "python manage.py collectstatic", It runs fine and copies over the files however website loads without styling. Also my base html looks something like this (in case I need to change something there however on local server everything was running fine): {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>About</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Work+Sans:100,200,300,400,700,800" rel="stylesheet"> <!-- {% static 'website/css/owl.carousel.min.cs' %} --> <link rel="stylesheet" href="{% static 'website/css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'website/css/animate.css' %}"> -
Trying to write a unit test for django-rest-passwordreset, but the password seemingly will not change in the test?
I have the standard installation of django-rest-passwordreset. I am trying to test the password reset process. Here is my unit test: def test__password_reset_resets_password_success(self): testing_password = "Testing12345" # Generate a user and trigger the password reset user = self.login_basic_user() user.set_password(wrong_password) body = {"email": user.email} self.make_request("POST", url=self.password_reset_url, data=body) # Go and get the password reset email and token self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] url, token = self.get_url_and_token(message.body) # Resetting the password body = {"password": testing_password, "token": token} resp = self.make_request("POST", url=self.password_change_password_url, data=body) self.assertEqual(resp["status"], "OK") self.assertTrue(user.check_password(testing_password)) However, for some reason the check_password at the end does not return True with the new password. It only returns true with the old password. It seems that for some reason the POST is not causing the new password to be saved to the database. Why might this be? I have tested the urls manually with the DRF interface, so I know the password resets successfully that way. -
Django: MultipleChoiceFilter on Model TextChoices
I have a Model which holds models.TextChoices. class Visit(BaseModel): class VisitStatus(models.TextChoices): INQUIRED = 'INQ', _('Inquired') OPTIONAL = 'OPT', _('Optional') CONFIRMED = 'CON', _('Confirmed') ACTIVE = 'ACT', _('Active') INACTIVE = 'INA', _('Inactive') CANCELLED = 'CXL', _('Cancelled') I am trying to use the MultipleChoiceFilter from django-filter as follows: class VisitFilter(django_filters.FilterSet): status = django_filters.filters.ChoiceFilter(choices=models.Visit.VisitStatus, empty_label=None) class Meta: model = models.Visit fields = ['status'] I keep getting the following TypeError Exception Type: TypeError Exception Value: __call__() missing 1 required positional argument: 'value' Any suggestions?