Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get the count of model related by foreignkey
say I have two models post and comment. I want to get the count of comment that's related to post by foriegnkey. I'm trying to list post by the order of comment. but I'm not sure how to get the count of comment related to each post. class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) class Post(models.Model): title = models.CharField(max_length=100) and in views.py class PostListView(ListView): model = Post template_name = 'community/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 4 #ordering = ['-#comment'] #how do I do this one?hmm -
How to print a value obtained from a form in Django?
I am trying to create a form which asks user to input a value, do some calculations on it and show the results back to the user. Here is what I've done: I have created an app called QMarcum. Inside this app I have this views.py, forms.py and urls.py: #views.py from django.shortcuts import render from scipy.integrate import quad import scipy, numpy, math from scipy import integrate from django.http import HttpResponse from .forms import Calculate def integrand(x): Q_y = (1/(math.sqrt(2*math.pi)))*math.exp((-x**2)/2) return Q_y y = Calculate.y ans, err = quad(integrand, float(y), math.inf) print(ans) return render(request, 'test.html', {'form': Q_y}) And forms.py #forms.py from django import forms class Calculate(forms.Form): y = forms.FloatField() and urls.py from django.urls import path from . import views urlpatterns = [ path('form', views.integrand), ] the form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> </body> </html> The form asks user to input a value (y) ( y is printed on terminal successfully), however, print(ans) doesn't print the value AND also I don't know how to show the calculated result (ans) to user. Thanks in advance. -
Keyword error 'user' updating user profile in serialized profile
Hello guys am new to rest-framework and am facing a problem updating userprofile which I nasted user serializer in it's serializer. my sprofile serializer looks like this class CompanyOwnerSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, required=False) profile_pic = serializers.FileField(source='profile', required=False) class Meta: model = CompanyOwner fields = "__all__" def update(self, instance, validated_data): data_user = validated_data.pop('user') instance.gender = validated_data.get('gender', instance.gender) instance.job_title = validated_data.get('job_title', instance.job_title) instance.description = validated_data.get('description', instance.description) instance.location = validated_data.get('location', instance.location) instance.address = validated_data.get('address', instance.address) instance.longitude = validated_data.get('longitude', instance.longitude) instance.latitude = validated_data.get('longitude', instance.latitude) instance.save() if 'id' in data_user.keys(): current_user = User.objects.get(id=data_user['id']) current_user.username = data_user.get('username', current_user.username) current_user.first_name = data_user.get('first_name', current_user.first_name) current_user.last_name = data_user.get('username', current_user.last_name) current_user.save() return instance my issue that when I send data from post man I get error KeyError at /profile-update/1/ 'user' Request Method: PUT the data I am sending is "user": { "username": "kim_apps", "first_name": "", "email": "kimrop@examplemail.com", "last_name": "", "date_joined": "2019-06-06T21:00:32.612338Z" }, "gender": "", "job_title": "", "description": "", "location": "KE", "address": "", "longitude": 36.23456, "latitude": -1.234567 } can anyone help me the console says that key user is not found that is in the line data_user = validated_data.pop('user') I tried printing the validated_data but it gives an empty dictionary -
Can I pass api response from a django views without using django-rest framework
I want to pass values from django views to a react front end.I have not worked with django rest framework.I want to know if I can pass values from views in django to a react app, if so how?What should the views function return which can be given to the react app? -
django: search by ingredients in a Drinkdatabase
I want to create a Django filter, which looks for ingredients, which are included in a drink. However, no other ingredients may be present, only those I enter. Example: Drink: Gin Tonic Ingredients: Gin, Tonic Drink: Whiskey Cola Ingredients: Whiskey Cola Drink: Rum Cola Ingredients: Rum, Cola I admit I have cola and gin and tonic. The following drinks should come back: Gin Tonic Whiskey Cola Rum cola isn't coming back because I don't have rum. How I can do this in Django? I have a database calles TankAllocation. There I enter the ingredients for every tank. I tryed with Django filter, but there I don't get the correct drinks. Maybe i can compare the query set of the ingredients of Ingredients table and Tank table and delete duplicate entries, then start a non-equal query with: from django.db.models import Q. But how can I delete duplicate entries in the querieset? both entries should be deletet for a new filter query. Models.py from django.db import models class Drink(models.Model): name = models.CharField(max_length=256, unique=True) description = models.TextField() image_path = models.ImageField(upload_to=".\images") slug = models.SlugField(unique=True) ingredient = models.ManyToManyField('Ingredient', through='IngredientRatio', related_name='mischung',) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=256, unique=True) alcohol = models.BooleanField() def __str__(self): … -
add an explicite field in django admin page for a self recursive model
@admin.register(Group) class GroupAdmin(admin.ModelAdmin): list_display = ( 'group_id', 'group_name', 'groupParent_id', ) list_filter = ( 'group_name', ) models.py class Group(models.Model): group_id = models.AutoField(primary_key=True) groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='Parent', on_delete=models.CASCADE) group_name = models.CharField(max_length=100) -
How to place links in django templates
VERY new to Django and I am a little confused. I have placed a link in my html template file; however, clicking the link reports a 404 error. App views.py file: from django.shortcuts import render def index(request): return render(request, "login/index.html", None) def terms(request): return render(request, "login/terms.html", None) App urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('', views.terms, name="terms") ] Offending code in index.html: By signing in, you agree to our <a href="/login/terms.html">Terms Of Use Policy</a> Clicking on the link pops a 404 error. Any help would be appreciated as I learn a new framework. -
Can't get the value by key from request.session; I use django
I'm trying to do online shop with django. But i got some problem. During making the cart I'm getting the error 'local variable 'cart_id' referenced before assignment' in views.py. Here is this file: def cart_view(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) request.session['total'] = cart.items.count() except: cart = Cart() cart.save() cart_id = cart_id request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) categories = Category.objects.all() return render(request, 'cart.html', locals()) Here is the traceback Traceback: File "C:\Users\tankr\Django_projects\django_shop\ecomapp\views.py" in product_view 13. cart_id = request.session['cart_id'] File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\contrib\sessions\backends\base.py" in __getitem__ 54. return self._session[key] During handling of the above exception ('cart_id'), another exception occurred: File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tankr\Django_projects\django_shop\ecomapp\views.py" in product_view 19. cart_id = cart_id Exception Type: UnboundLocalError at /product/macbook-pro/ Exception Value: local variable 'cart_id' referenced before assignment Then I tried to solve it by adding global cart_id to function cart_view and got another error: name 'cart_id' is not defined. Here is new traceback: Traceback: File "C:\Users\tankr\Django_projects\django_shop_2\ecomapp\views.py" in product_view 14. cart_id = request.session['cart_id'] File "C:\Users\tankr\Django_projects\django_shop_2\eComEnv\lib\site-packages\django\contrib\sessions\backends\base.py" in __getitem__ 54. return self._session[key] During handling of the above exception ('cart_id'), another exception occurred: File "C:\Users\tankr\Django_projects\django_shop_2\eComEnv\lib\site-packages\django\core\handlers\exception.py" in inner … -
Trying to use objects from an entirely different model using a foreign key
So I want to assign a 'Rank' to specific users with a Foreign key (I created a model for Ranks with other objects such as an image, description, etc). What I want to do is to use those objects from the Rank Model and bring them over to my template. So that when I assign the rank "Newbie" to a specific user, it will show all the objects from the Rank like image, and descriptions. Can anyone help? Thanks Here's my views.py from .models import user as UserModel def index(request): return render(request, 'pages/index.html') def user(request, user_id): profile = get_object_or_404(UserModel, pk=user_id) context = { 'profile' : profile, } return render(request, 'user/user.html', context) Here is the model for Ranks from django.db import models class Ranks(models.Model): rank_name = models.CharField(max_length=300) photo = models.ImageField(upload_to='photos/&Y/%m/%d/') description = models.TextField(blank=True) rank_points = models.IntegerField() rank_promotionss = models.IntegerField() def __str__(self): return self.rank_name -
How to pass dropdown/select values to the form's action part in django?
I've a simple form with a dropdown menu on my index page. I want the user to be redirected based on the value he/she selects from the drop down. As a workaround I collected the dropdown value in the views, while my index page form redirects them to an intermediate page. After it goes through the intermediate page, the next page would be displayed based on the selected value from the form. But I would like to have a more dynamic approach to it, where the action part of the index form could catch the dropdown value. {% extends 'raffle_form/base.html' %} {% block content %} <form role="form" action="{% url '<choice value to be dynamically appear here!>' %}" method="post" validate> {% csrf_token %} <div class="form-group"> <label class="col-md-12" align="center">Select Your Choice!</label> <select class="form-control" name="choice" size="0" style="border-radius: 35px;"> <option value="choice1">CHOICE 1</option> <option value="choice2">CHOICE 2</option> <option value="choice3">CHOICE 3</option> </select> </div> <div class="form-group"> <div class="col-md-12"> <button type="submit" class="btn btn-primary btn-md btn-block">Proceed</button> </div> </div> </form> {% endblock%} Any suggestions/guidelines would be appreciated. -
Django: AttributeError: type object 'GroupModel' has no attribute '_meta'
I am new in Django, in my code when I requested from postman I got this error, may someone help me what's wrong in my code? model: from django.db import models class GroupModel(object): title=models.CharField(max_length=20) description = models.CharField() class Meta: db_table = 'group' def __str__(self): return self serializer: from rest_framework import serializers from .models import GroupModel class GroupSerializer(serializers.ModelSerializer): print('hello4') class Meta: model = GroupModel fields = '__all__' views: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .serializer import GroupSerializer from .models import GroupModel from rest_framework.decorators import api_view from rest_framework import status @api_view(['POST']) def InsetGroup(request): data = GroupSerializer(data = request.data) if request.method == 'POST': if data.is_valid(): data.save() return JsonResponse('saved was saccessfull', safe = False) return JsonResponse(data.errors, status = status.HTTP_400_BAD_REQUEST, safe = False) -
How To Add 'Likes' On The Main Page For Multiple Objects With Django?
I have an Ajax Like/Dislike button that works for the product detail page. However, I want to add it on the main page, where multiple products are listed. Here is what I currently have in the models.py: class Product(models.Model): ... likes = models.ManyToManyField(User, blank=True, related_name='likes') ... def total_likes(self): return self.likes.count() views.py: def home(request): products = Product.objects.all().order_by('-pub_date') f = ProductFilter(request.GET, queryset=products) return render(request, 'product/home.html', {'filter': f}) def detail(request, product_id): product = get_object_or_404(Product, product_id=product_id) is_liked = False if product.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'product': product, 'is_liked': is_liked, 'total_likes': product.total_likes() } return render(request, 'product/detail.html', context) def like_product(request): product = get_object_or_404(Product, id=request.POST.get('id')) if product.likes.filter(id=request.user.id).exists(): product.likes.remove(request.user) is_liked = False else: product.likes.add(request.user) is_liked = True context = { 'product': product, 'is_liked': is_liked, 'total_likes': product.total_likes() } if request.is_ajax(): html = render_to_string('product/likes.html', context, request=request) return JsonResponse({'form': html}) Appreciate your help! -
Customize update_last_login in Django
This is django update_last_login: #django.contrib.auth def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login']) I want to change timezone of update_last_login signal and customize it. How can I do this ? -
How to provide file as input to django backend script from angularjs?
I have a python desktop application, which accepts 2 files(.hex, .XML) as input and generate output as another file. Now I want to make it as web application using Django and angular. I want to keep python business logic at server and interface part at client-side. I am confuse because my app accepts files as input and how to solve it. Is it good practice to upload and send input files to backed and get the result at front end? Or any other better approach is there? -
First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'function'
I'm trying to show some data based on the user_id in the database but it keeps getting this ValueError. Can anyone help me find out what I am doing wrong? This is my views.py from django.shortcuts import render, get_object_or_404 from .models import user def index(request): return render(request, 'pages/index.html') def user(request, user_id): profile = get_object_or_404(user, pk=user_id) context = { 'profile' : profile } return render(request, 'user/user.html', context) -
How to upload Django static file (Images) to imgur?
I am using Django and DjangoRestFramework. By using "models.ImageField(upload_to='image/')" i am able to store images to my servers local directory. My question is, is it possible to upload my image to an external site like Imgur using there API and then storing Link to that image in my database. (Basically, when they fetch my database, it should point them to a link which contains image, but is not stored in my server local directory). -
pg_restore: [archiver] input file does not appear to be a valid archive error in PostgreSQL using Pgadmin 4 in ubuntu 18.04
I'm trying to restore sql file backup of database in postgresql. It gives me above error. I have done following operations. psql test </opt/backup.sql and pg_restore -U postgres -d test </opt/backup.sql -
Custom Serializer
I would like to have an API endpoint which delivers me customised data. Every time a QR code is scanned (can also be the same QR code several times) a new basket data set is created. My goal is to have an API endpoint where I can query the QR-Code and get a JSON response with that QR-Code, the picker who is tagged to it and the number of times that specific QR code has been scanned. I know how to do that using normal views. However, I would prefer to use the rest-framework api. I have read through the rest-framwork's documentation (https://www.django-rest-framework.org/api-guide/relations/#custom-relational-fields) but feel a bit lost. I have the following models: class Picker(models.Model): class Meta: verbose_name_plural = 'Pickers' # First name of picker first_name = models.CharField(max_length=30) # Last name of picker last_name = models.CharField(max_length=30) def __str__(self): return f'{self.first_name} {self.last_name}' class QRCode(models.Model): # Code code = models.CharField(max_length=250) def __str__(self): return f'{self.code}' class Basket(models.Model): # DateTimestamp timestamp = models.DateTimeField(auto_now_add=True) # QR-Code scanned qr_code = models.CharField(max_length=30) # Picker from who the basket comes picker = models.ForeignKey(Picker, related_name='picker', on_delete=models.DO_NOTHING) def __str__(self): return f'{self.timestamp} - {self.qr_code}' -
How can i restrict a django template to certain user categories?
I'm building a Django site where a user can register and do some stuff. After registering, the email should be confirmed. Here is how a user is confirmed: in my database, i added a table called account_emailaddress. The verified column, in this table, will give 0 when the email address is not confirmed and 1 when it is confirmed. Now, i have a template, this template should throw an error when the email address is equal to 0. Is this doable at all? I don't know where to put my feet to do this, so can someone guide to me an approach to do this? I'm not using a custom user model edited by me, but the Django user model. Here is what the template looks like: I'm assuming i need to sort this in my template's file, by adding an if statement like the one below: {% block content %} {% if email_is_confirmed %} <style> </style> <body> <p> CONFIRMED </p> <div> <p>Here goes a bunch of features</p> </div> </body> {% else %} <p> Your email is not confirmed </p> {% endif %} {% endblock %} -
How to make a file upload and download system in Django?
I made a website which features blogging and tutorials and I want to make a system in which users can upload files and download them. I don't want to use S3 and Google Cloud(which need credit card for registration). How can I achieve this? Please post code for storage backend and for file upload handler. My website is :- http://pyworldpy.herokuapp.com/ -
TypeError in models
I'm getting this error: user = models.OneToOneField(User) TypeError: init() missing 1 required positional argument: 'on_delete' from django.db import models from django.contrib.auth.models import User Create your models here. class UserProfileInfo(models.Model): # creating relationship user = models.OneToOneField(User) # additional attributes portfolio = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username -
django.core.exceptions.ValidationError: ["'urvi' value must be an integer."]
I am getting an error when I try to access the admin panel. It says ValidationError at /admin/["'urvi' value must be an integer."]. I have already tried using id and auto incrementing it but nothing works. Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. Roles = ( ('sales', 'SALES'), ('operations', 'OPERATIONS'), ('cashier', 'CASHIER'), ('frontdesk', 'FRONTDESK'), ('admin', 'ADMIN'), ('client', 'CLIENT'), ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='none') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=50) username = models.CharField(max_length=50) role = models.CharField(max_length=50, choices=Roles, default='client') def __str__(self): return self.username -
mezzanine on pythonanywhere error secret key
Error running WSGI application 2019-06-08 10:42:02,089: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Above is the error I get even after I followed the Will's instruction The SECRET_KEY setting must not be empty || Available at Settings.py and it's what I wrote in my wsgi and settings.py file in mezzanine project route folder: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "venmz.settings") I cloned my mezzanine project? folder through clone git. and the name of this is mez and the mezzanine route foldername is venmz -
ModuleNotFoundError: No module named 'django' while deploying to ElasticBeanstalk
Tried multiple solutions online but couldnt get it working ! Basically my application is deployed but http response is "Internal Server Error". On investigating EB logs i found the following traceback. [Sat Jun 08 10:28:56.880823 2019] [:error] [pid 4776] [remote 172.31.4.251:180] Traceback (most recent call last): [Sat Jun 08 10:28:56.880846 2019] [:error] [pid 4776] [remote 172.31.4.251:180] File "/opt/python/current/app/modelforms/modelforms/wsgi.py", line 12, in <module> [Sat Jun 08 10:28:56.880863 2019] [:error] [pid 4776] [remote 172.31.4.251:180] from django.core.wsgi import get_wsgi_application [Sat Jun 08 10:28:56.880878 2019] [:error] [pid 4776] [remote 172.31.4.251:180] ModuleNotFoundError: No module named 'django' [Sat Jun 08 10:29:10.828039 2019] [:error] [pid 4776] [remote 172.31.42.54:180] mod_wsgi (pid=4776): Target WSGI script '/opt/python/current/app/modelforms/modelforms/wsgi.py' cannot be loaded as Python module. [Sat Jun 08 10:29:10.828089 2019] [:error] [pid 4776] [remote 172.31.42.54:180] mod_wsgi (pid=4776): Exception occurred processing WSGI script '/opt/python/current/app/modelforms/modelforms/wsgi.py'. My requirements.txt is placed in all directories and yet django module is not recognised. It seems it hasn't been installed at first place. The file's contents are: Django==2.2.1 Pillow==6.0.0 pytz==2019.1 sorl-thumbnail==12.5.0 sqlparse==0.3.0 Any help is appreciated. -
Django main class for decorators
i want to have a main class at my Django Application (i never worked with that before, im new to python/django) where i can use a decorator on like for example: https://github.com/jsocol/django-ratelimit so i don't have to set this for every single view. can smb provide an example of how to do this or can expalin where i have to place something like this: @ratelimit(key='header:Cookie', rate='10/m', block=True) def main(): print("python main function") if __name__ == '__main__': main() thanks and regards