Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at /registration/list/ 'str' object has no attribute 'get'
I want to display the records from the table on the basis of the municipality login but it gives me the above error.Would someone please tell me how to fix it? Thank you. views.py class ListRegistration(LoginRequiredMixin, FilterView): model = models.NewRegistration template_name = 'registration_list.html' context_object_name = 'registrations' paginate_by = 10 def get_queryset(self): user_id=self.request.user.id profile_qs = Profile.objects.filter(id=user_id).values_list("user_id", flat=True) p_m=Profile.objects.filter(id=profile_qs).values_list("municipality",flat=True) all=Profile.objects.filter(municipality=p_m).values_list("user_id",flat=True) return models.NewRegistration.objects.filter(is_forwarded=False,user_id__in=all).order_by('-id') registration.html {% with registration.get_overall_registration_status as reg_status %} {% if reg_status|get_item:"iscomplete" %} <td> <div class="btn btn-success">Completed</div> </td> {% elif reg_status|get_item:"ispartial" %} <td> <div class="dropdown status-registration noborder"> <button class="btn btn-warning" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Partial</button> <div class="dropdown-menu"> {% with registration.get_initial_registration_status.iteritems as statuses %} {% for x,y in statuses %} <span style="display: block; margin-bottom: 2px;" class="dropdown-item glyphicon {% if y %} glyphicon-ok alert-success {% else %} glyphicon-remove alert-danger {% endif %}"> {[{ '{{ x }}' | translate_detail_registration_level }]}</span> {% endfor %} {% endwith %} </div> </div> </td> {% else %} <td> <div class="btn btn-danger">Noinfo</div> </td> {% endif %} {% endwith %} -
How I can store images in Database by using url to images
My problem is that I want to store images in database, but I don't want to store them physically in my project as static files, I want to save in database url to images which are already uploaded somewhere in Internet. How can I do this, just use CharField or TextField as type of field and paste url? But I also want later to display this photo in my template. class Image(models.Model): name = models.CharField(max_length=25, verbose_name='Image name') image_file = def __str__(self): return self.name -
How do I continue working on an existing django project from my laptop?
I created a django project in pycharm from my desktop computer. Now that I want to work on that same project from my laptop I'm not able to do so. What are the commands to be written in the terminal for continuing the project in pycharm from my laptop? (how do I work in that existing virtual environment and run the server now?) -
Can't dynamically create path with upload_to
In my user model, I have an ImageField that contains an upload_to attribute that will create the image path dynamically based on the user's id. avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path) def create_user_image_path(instance, image_name): image_name = str(instance.user.id) + image_name[-4:] return 'users/{0}/avatars/{1}'.format(instance.user.id, image_name) When I sign up, I get an error that looks like this: The system cannot find the path specified: 'C:\Users\xx\PycharmProjects\project_name\media\users\150\avatars' If I remove the id and avatars and just include the image name (with no new directories) it works successfully and writes the image. I have tried doing chmod -R 777 on this directory, but it still doesn't create these new directories dynamically. I'm not sure what I'm doing wrong. -
Serialize nested object as flat attributes of current parent object
I've model A and model B, model B is child of model A. I've implemented a ModelSerializer for my model A object and I need to represent all attributes of related model B as attributes (properties) of model A. How can I do that with Django Rest Framework? Thank you -
Django got an unexpected keyword argument while I'm making register page
I'm trying to make a register page in Django and got TypeError TypeError at /impassionuser/register/ Impassionuser() got an unexpected keyword argument 'useremail' Exception Type: TypeError Exception Value: Impassionuser() got an unexpected keyword argument 'useremail' Python Version: 3.7.2 Python Path: ['/Users/subin/Desktop/Django/3rd/impassion_community', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python37.zip', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python3.7', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python3.7/lib-dynload', '/usr/local/var/pyenv/versions/3.7.2/lib/python3.7', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python3.7/site-packages'] Server time: Sat, 22 Jun 2019 23:36:07 +0000 I added everything, but got this error and don't know what to do about it. why I got this problem? from register.html <div class="form-group"> <label for="useremail">사용자 이메일</label> <input type="email" class="form-control" id="useremail" placeholder="사용자 이메일" name="useremail"> </div> class Impassionuser(models.Model): username=models.CharField(max_length=64, verbose_name='사용자명') useremail=models.EmailField(max_length=128, verbose_name='사용자이메일') password=models.CharField(max_length=64, verbose_name='비밀번호') registered_dttm=models.DateTimeField(auto_now_add=True, verbose_name='등록시간') from views.py request.method == 'POST': username = request.POST.get('username', None) useremail = request.POST.get('useremail', None) password = request.POST.get('password', None) re_password = request.POST.get('re-password', None) res_data={} if not (username and useremail and password and re_password): res_data['error'] = '모든 값을 입력해야합니다.' elif password != re_password: res_data['error'] = '비밀번호가 다릅니다.' else: impassionuser = Impassionuser( username=username, useremail=useremail, password=make_password(password) ) impassionuser.save() -
How to make django admin logo dynamic?
i'm using django-cms admin style, here i had managed to change the default DjangoCMS logo, by following the solution mentioned here: Django cms 3.4.1 admin dlogo now the logo is a static one, i want it to be dynamic, means it should get the image path from the Database, where the location is stored. As these admin pages are not render through views.py, so i'm not able to sent the querysets to it. can anyone suggest, how to do it? -
Validate two inline models in the Django admin
I have three models that look like this (simplified from the actual models): class LayoutPage(models.Model): name = models.CharField(max_length=190, unique=True) height = models.DecimalField(max_digits=10, decimal_places=4) width = models.DecimalField(max_digits=10, decimal_places=4) class PageImage(models.Model): page = models.ForeignKey(LayoutPage) name = models.CharField(max_length=150) class Meta: unique_together = ('page', 'name') class PageText(models.Model): page = models.ForeignKey(LayoutPage) name = models.CharField(max_length=150) class Meta: unique_together = ('page', 'name') My admin definitions look like this: class PageImageInline(admin.TabularInline): model = PageImage form = PageImageForm class PageTextInline(admin.TabularInline): model = PageText form = PageTextForm class LayoutPageAdmin(admin.ModelAdmin): inlines = [LayoutImageInline, LayoutTextInline] And my forms look like this: class PageImageForm(forms.ModelForm): def clean(self): cleaned_data = super(PageImageForm, self).clean() page = cleaned_data.get('page') name = cleaned_data.get('name') if page.pagetext_set.filter(name=name).exists(): self.add_error('name', forms.ValidationError(_('Cannot be the same name as an existing layout text on the page'), code='name_conflict')) class PageTextForm(forms.ModelForm): def clean(self): cleaned_data = super(PageTextForm, self).clean() page = cleaned_data.get('page') name = cleaned_data.get('name') if page.pageimage_set.filter(name=name).exists(): self.add_error('name', forms.ValidationError(_('Cannot be the same name as an existing layout image on the page'), code='name_conflict')) This accomplishes two of the three things I need. 1) For each page, no two images can have the same name, and no two texts can have the same name. 2) When editing a page in the admin, you cannot rename an image to have the same name as … -
How do I properly import templates from HTML5 UP into django
Im trying to upload templates from HTLM5 UP into the Django framework. However I'm not sure where to place some of the supporting CSS, SASS, Webfonts, Javascript files. Link to the template I downloaded below. Files I'm referring to are in the "Assets" folder. https://html5up.net/strata I've tried placing them in the path below. I'm using the Pycharm IDE if that changes anything. ProjectName/mysite/templates/mysite/assets I've been trying to call them with href="mysite/assets/css/main.css" with no success. -
Doesn't show the video for some reason
I have a model of where the user can choose the title of their video and can upload the video but for some reason when I try to display the video in the html and I visit that page it does a GET request on the file but the file doesn't include .mp4 on the end so it doesn't work. Tried a few things but I can't remember what exactly since it was a few days ago and none of them worked. My models.py: # Create your models here. class Video(models.Model): title = models.CharField(max_length=40, blank=False) video_file = models.FileField(name="Upload a mp4 file", upload_to=f"uploadvideos/video", validators=[FileExtensionValidator(['mp4'])], blank=False) def __str__(self): return self.title My views.py: def movie(request, movie_id): video = get_object_or_404(Video, title=movie_id) context = {'video': video} return render(request, template_name=f'uploadvideos/movie.html', context=context) My html template: </head> <body> <h1 class="movietitle">{{ movie }}</h1> <div class="videoDetails"> <video width="700" height="430" controls> <source src="{{ idk what to put here }}" type="video/mp4"> </video> </div> </body> </html> -
How to calculate the total after applying discount in Django?
I want to calculate the total amount after applying the discount. For that i have made cart.py. But when i call the functions from cart.py in templates.html. It neither display the total amount after discount nor the discounted percentage. cart.py created in cart app from decimal import Decimal from django.conf import settings from shop.models import Product from coupons.models import Coupons class Cart(object): def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True @property def coupon(self): if self.coupon_id: return Coupons.objects.get(id=self.coupon_id) def get_discount(self): if self.coupon: return (self.coupon.discount / Decimal('100')) * self.get_total_price() def get_total_price_after_discount(self): return self.get_total_price() - self.get_discount() template.html <tr class="gray2"> <td colspan="2"> coupon ({{discount}}) % off</td> <td colspan="3"></td> <td class="num neg"> {{cart.get_discount|floatformat:"2"}}</td> </tr> <tr class="total"> <td>Total</td> <td colspan="4"></td> <td class="num">{{cart.get_total_price_after_discount|floatformat:"2"}}</td> </tr> </table> <div class="divo"> <p> coupon code to apply discount </p> <form action="{% url 'coupons:apply' %}" method="post"> {{coupon_apply_form}} {% csrf_token %} <input type="submit" value="apply" class="btn"> </form> </div> views.py @require_POST def coupon_apply(request): now = timezone.now() form = CouponApplyForm(request.POST) if form.is_valid(): code = form.cleaned_data['code'] try: coupon = Coupons.objects.get(code__iexact=code, valid_form__lte=now, valid_to__gte=now, active=True) request.session['coupon_id'] = coupon.id except Coupons.DoesNotExist: request.session['coupon_id'] = None return HttpResponseRedirect(reverse("cart")) This portion of template.html is not displaying. Please … -
Extend admin page for users from specific groups with custom html and js
I need to implement moderator functionality and the builtin django admin suffices except I need additional form to send some data and receive result from an API endpoint. What's the easiest way to do this. Do I need to create middleware to catch requests from the specified user and return extended versions? -
ManyToMany field returns None despite having a value
I have 2 classes: categories and pizzas. One of them is a list of categories for the object and another one is the object. Problem is, when I call an object, I can see all the fields except that ManyToMany field returns catalog.Category.None instead of the assigned value. Here is my models.py: class Category(models.Model): CLASSIC = 'Classic' VEGETARIAN = 'Vegetarian' SPICY = 'Spicy' TYPE = [ (CLASSIC, 'Classic'), (VEGETARIAN, 'Vegetarian'), (SPICY, 'Spicy') ] type = models.CharField( max_length=100, choices=TYPE ) def __str__(self): return self.type class Meta: verbose_name_plural = 'Categories' class Pizza(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() size = models.OneToOneField( Size, on_delete=models.CASCADE, primary_key=True ) category = models.ManyToManyField(Category) def __str__(self): return f"name = {self.name}, size = {self.size}, category = {self.category}" And here is my shell output: >>> from catalog.models import Pizza >>> from catalog.models import Category >>> pizza = Pizza.objects.all() >>> pizza <QuerySet [<Pizza: name = Chicken, prices = 8, 10, category = catalog.Category.None>, <Pizza: name = Pepperoni, prices = 8, 12, category = catalog.Category.None>, <Pizza: name = Mushroom, prices = 7, 9, category = catalog.Category.None>]> >>> cat = Category.objects.filter(pizza=1) >>> cat <QuerySet [<Category: Classic>]> >>> cat = Category.objects.filter(pizza=2) >>> cat <QuerySet [<Category: Classic>, <Category: Spicy>]> -
How to make QuerySet JSON serializable?
I have a problem with creating a new object in my Rest Framework. As much I as understand, when I tried to overwrite item's field so it could have all the items that are in my database. I thought, that this would work, and it showed me the working page and I could choose an item. But when I tried to post it to create a new object, it said "Object of type 'Item' is not JSON serializable" I was trying to figure it out, how to convert Item.objects.all() into JSON data. But nothing helped me. I understand, that this isn't really hard to do, but I can't figure it out on my own. So I ask for your help, how to solve this problem? Here's my serializer from rest_framework import serializers from items.models import OrderItem, Item class OrderItemSerializer(serializers.ModelSerializer): item = serializers.ChoiceField(choices=Item.objects.all()) class Meta: model = OrderItem fields = ('item', 'size', 'quantity', 'id') -
Django - using 1-1 relationship method to create two different user profiles, same authentication
I have a Django project in which I have currently used the default user authentication process, and extended it to allow for user profiles. I now want to create profiles for two different types of users, e.g. User type 1: = WP. User type 2: = W. I have looked at some of the suggested solutions but wanted some specific guidance on my particular scenario and code. As I understand it, there are three ways of attempting to do this 1. Proxy Model 2. 1-1 Relationship Method 3. Custom User Model. I want to use option #2 - 1-1 Relationship Method and avoid the other two, with the objective being to a) allow users to log in b) allow a user to specify if they are user type 1 (WP) or user type 2 (W) c) If a user is user type 1 (WP) they are directed to a WP profile, and if a user is user type 2 (W) they are directed to user type 2 (W) profile. I currently have this in my models.py (for users) from django.db import models from django.contrib.auth.models import User from PIL import Image from django import forms class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) … -
Accessing containerized Django app from ECS public IPv4 endpoint
I have a dockerized django app that is stored in ECR. When I set-up a new ECS cluster (using Fargate), this image loads correctly and I can see the logs in Cloudwatch: 20:12:21 Operations to perform: 20:12:21 Apply all migrations: admin, auth, contenttypes, sessions 20:12:21 Running migrations: 20:12:21 No migrations to apply. 20:12:23 No changes detected 20:12:25 Watching for file changes with StatReloader 20:12:25 Performing system checks... 20:12:25 System check identified no issues (0 silenced). 20:12:26 June 22, 2019 - 20:12:26 20:12:26 Django version 2.2.2, using settings 'config.settings' 20:12:26 Starting development server at http://127.0.0.1:8000/ 20:12:26 Quit the server with CONTROL-C. but when I got to the public ipv4 listed under the task network details, and go to :8000 in my browser, nothing loads and I dont see any requests going to the server in the container in cloud watch. I'm wondering if the issue is related to using: python manage.py runserver 0.0.0.0:8000 in my container set-up. Alternatively, a setting in the security group, etc. But i've allowed inbound traffic to 127.0.0.1 & 0.0.0.0 port 8000 inside the settings there already. I'm somewhat at a loss as I've looked around at a variety of documentation and I seem to have my … -
How can I make my django channels websocket server work over ssl?
I'm setting up a web application that has a chatroom system. I originally followed the tutorial here: https://channels.readthedocs.io/en/latest/tutorial/index.html It worked flawlessly in development, but I had to use daphne to get it to work when I deployed the app because I'm using apache. sudo daphne -b 0.0.0.0 -p 81 myapp.asgi:application But when I used certbot to get ssl certificates for https, I started getting the following console errors whenever I try to send a message: Mixed Content: The page at: https://example.com/home/chat/46508f6fc17b04ad04ba0e8e5095e4b233944ed3d4145e5501ada21bab7042c6/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://example.com:81/ws/chat/46508f6fc17b04ad04ba0e8e5095e4b233944ed3d4145e5501ada21bab7042c6/'. This request has been blocked; this endpoint must be available over WSS. My first thought was to change the javascript in room.html from this: var chatSocket = new WebSocket( 'ws://' + window.location.host + ':81/ws/chat/' + roomName + '/'); to this: var chatSocket = new WebSocket( 'wss://' + window.location.host + ':81/ws/chat/' + roomName + '/'); this did not work and resulted in the following error when I try to send a message: (index):150 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. mysite-le-ssl.config: <VirtualHost *:443> ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/me/myproject/myapp> <Files wsgi.py> Require all granted … -
Django - multiplication two arrays
I have two arrays sent with ajax from template. One array contains the product id and the second is the quantity. The problem is when I get the price of product per piece from database I must to multiply with the quantity. How i do price_product[ a, b, c,d] * quantity[30,50,40,70] => a*30, b*50 .... This is my current code def price(request): price = request.POST.getlist('price[]') quantity = request.POST.getlist('quantity[]') price_product = list(set(ListProduct.objects.filter(id__in=price).values_list('price_buc', flat=True))) context = { 'data': price_product } return JsonResponse(context) -
ERROR:The SECRET_KEY setting must not be empty. (even though there is a secret key in my settings.py file )
getting django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. this error even though i have a secret key assigned in my settings.py file i have tried changing this code of line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') to os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapshut.settings' i have tried to set environmnet variable set DJANGO_SETTINGS_MODULE=mysite.settings django-admin runserver and when i run the server with that following command i just get django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing se ttings. this error and whenever i run manage.py runserver command im still getting the same error (no secret_key) i dont know what's the reason and why django isnt able to find my secret_key -
Django does not save form model
I'm using Django 1.8 and Python 2.7 job_form.is_valid() is True, but it does not save anything because Django can't detect the changed data. I attach a picture. View code: Python 2.7 str has no attribute iter, only python 3+ but I can't upgrade it. why is not working Django 1.8 with Python 2.7? job_form = JobEditForm(request.POST, instance=job) if job_form.is_valid(): job_form.save() return HttpResponse(status=200) else: return HttpResponse(job_form.errors.as_json(), status=404) -
Django quiz: Save user's choice and include them in a result
I want users to take a series of questions each with different choices to select from. Then, after the last question a page containing results should be displayed that is based on the user's choices (for simplicity let's say the user's score). I am new to Django and I am unsure on how to save the user's choices, so I can work with them. I read some posts about this, but couldn't find a final solution. First of all, will it require a setup/login feature to be able to save user data? Also, will I need some sort of customized UserModel (see code below as an example) and/or a class that contains question_id, answer_id, user_id? My models: class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class UserAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Choice, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) answered = models.BooleanField(default=False) def __str__(self): return str(self.question) + "_" + str(self.answer) class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.IntegerField(default=0) -
Django: Filter data based on expiration date coming within next 1 week and 2 weeks
I have a model class: class Products(models.Model): product = models.Charfield( field specs here . ) expiration_date = modelsDateTimeField ( . field specs here . ) Now I want the users to be able to see all the products which will expire in 1 week or/and 1 month or/and 3 months from today. I have already tried: from django_filters import rest_framework as filters expiration_date_after = filters.DateFilter(field_name='expiration_date', lookup_expr='gte') expiration_date_before = filters.DateFilter(field_name='expiration_date', lookup_expr='lte') with this, I have to pass two parameters in the url: /products/?expiration_date_after=2019-06-06&expiration_date_before=2019-06-12 But I want to pass in the url only 1 or 2 or 3 which will display data for 1 week, 2 weeks and 3 weeks . So if i pass products/1 . it should filters expiration date for next 1 week. and if i pass products/2 . it should filter expiration date for next 1 month. I am new to django.... So please let me know what is best approach to this problem. -
Html not showing the title of the django model
I created a model in django and wanted to show the title of the object I created using the model in my html code. My code for the model is: class Video(models.Model): title = models.CharField(max_length=40, blank=False) def __str__(self): return self.title And my html code is: <body> <header> <div class="container"> <!-- Branding --> <a href="/"><span class="branding">Movies & Other</span></a> <a href="/admin"><span class="adminpanel">Admin panel</span></a> </div> </header> <h1 class="movietitle">{{ video.title }}</h1> <div class="videoDetails"> <video width="700" height="430" controls> <source src="uploadvideos/videos/yt/yt.mp4" type="video/mp4"> </video> </div> </body> </html>``` I created a object in the Video model in the admin panel but it doesn't show the title of it. -
Django Admin: Restrict staff to update
I had a Blog Model. All new blog post has DRAFT status. In the admin page, admin would be all permissions (CRUD) on the Blog Model. I can solve this by using Django's register method. What I want is is_staff user can view all the Blog Post but can't update Status (Eg. from DRAFT to APPROVE). Is there any way to check the request's group, then allow the user to update or not? Thanks. -
Django Vuejs -- Using Axios
I am trying to use VueJs inside my Django Framework ( Using it as Backend) for Front-End. However, I very new with axios, which I found more easier to use with VuejS Dajngo Front-End. On integrating all other, I didn't see anything coming up