Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login Error: save() got an unexpected keyword argument 'update_fields', this happens when i try to login
I just got an error when I try to log in. the error happens only when I add the save method in the User model. But when I remove the save method there is no error at all. I want to decrease the quality of the user picture using PIL to load the website faster, that's why I add the save method. THANKS! here is the user model: class User(AbstractUser): is_student = models.BooleanField(default=False) is_lecturer = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) phone = models.CharField(max_length=60, blank=True, null=True) address = models.CharField(max_length=60, blank=True, null=True) picture = models.ImageField(upload_to='profile_pictures/%y/%m/%d/', default='default.png', null=True) email = models.EmailField(blank=True, null=True) username_validator = ASCIIUsernameValidator() def __str__(self): return '{} {}'.format(self.first_name, self.last_name, self.email) @property def get_full_name(self): full_name = self.username if self.first_name and self.last_name: full_name = self.first_name + " " + self.last_name return full_name def get_absolute_url(self): return reverse('profile_single', kwargs={'pk': self.pk}) def save(self): super().save() try: img = Image.open(self.picture.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.picture.path) except: pass def delete(self, *args, **kwargs): if self.picture.url != settings.MEDIA_URL + 'default.png': self.picture.delete() super().delete(*args, **kwargs) The full log of the error is here: Internal Server Error: /accounts/login/ Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 115, … -
Using TinyMCE with filebrowser and grappelli
I've been wanting to set up a blog app with a WYSIWYG editor. I use S3 as the storage backend for image uploads outside of the editor. For that purpose, I use "django-storages". I have deployed this on Heroku and for that purpose, I use django-heroku as well. To enable image upload for TinyMCE i went ahead and installed Grappelli and filebrowser. I added the URLs for the same added the context processor for Grappelli, set the TINYMCE_FILEBROWSER setting to true. I ensured the URLs for filebrowser and grappelli come before the URL for admin When I call collectstatic, I get this messages like this Found another file with the destination path 'admin/js/timeparse.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. When I open up admin and go to the image upload button on the editor, it doesn't show the upload icon. I was wondering if anyone who has had any experience with this can help me out? I am open to setting up some time with them as well :) Here's the rundown on settings.py INSTALLED_APPS = [ 'django.contrib.admin', … -
User registration, Login, Logout, etc... Django
Is there a way to register, login, logout users, etc... in a Django REST APi. I am using DjangoRestFramework. For authentication, I am using djangorestframework-jwt for JSONWebTokenAuthentication. If I want to be able to have users register, login, logout, etc... What are the options? Also is it customizable? what is the most used out there in the industry, in terms of reliability, etc... Thanks. -
Django - like unlike system - how changing the button color for unliking?
Here is my follow/unfollow system. If user clic first, he adds if he clics seconds time he removes. What's the best way to change the color of the text of the button? After user clics for the first time? user/views.py @login_required(login_url='/cooker/login') def FollowView(request, pk): userprofile = get_object_or_404(UserProfile, user_id=pk) if request.method == "POST": _followed = request.user in userprofile.follow.all() if _followed: userprofile.follow.remove(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: userprofile.follow.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_follow(self): return self.follow.count() Here is my template: user/template/exemple.html <div class="col-sm-4"> <form action="{% url 'user:follow_public' current_user.pk %}" method="POST">{% csrf_token %} <button type="submit" name="user_id" value="{{ current_user.id }}" style="width: 100%;background: #ff6670;padding: 10px;border-radius: 10px; margin-bottom: 15px;outline:none;">Follow {{current_user.username}}</button> </form> </div> -
ModuleNotFound cause 502 deploying django with zappa on aws lambda
I've faced ModuleNotFound error when try to deploy django to aws via zappa. when i tried to run server locally using below commmand it works well (venv) python manage.py runserver or (venv) python manage.py runserver --settings=remoteMedi.settings.prod zappa settings is like folder hierachy is like installed_app is like why i can't get it? -
How can i add registration data in another model and can login from that data in django
Recently i am facing a problem in registration. I have made a ** accounts** app in my project for registrations. I don't want to save data in default User model in dB. i am trying to make an eCommerce site where people can register to buy products. What is the best way for registrations and log in? Extending the user model could have solved the problem but I want a totally different model for that user who wants to buy products for registration and login. Is it the best way what i am thinking for an eCommerce site registration? How can i do it? -
how do i write this type of code using python django? [closed]
I need to write code that will have three levels. i.e. person;A,B,C. person A joins a club. he refers person B. Person B then refers person C. I need person A to get a point for inviting person B.since person B also invited person C and B was invited by A.Person B needs to get a point while person A gets half a point.Person B is a direct referal to person A while person C is an indirect referal.person C is a direct referal to person B. I need the code to continue like that such like if person C now invites person D. person C will get a point and person B will get half a point. And it goes on like that.I just need someone to get me the code. -
how to put tags in articles in python django
My client want me to build an web application in which user send articles. and put tags at the end of articles. I am a python developer but i do not know how to do coding for tags in front-end as well as back-end.Kindly help me -
Manually render CSS and JS files in Django?
Based on this answer, I was trying to manually render my css and javascript files before loading. My project level urls.py: from django.contrib import admin from django.urls import path, re_path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'(?P<filename>[a-zA-Z_-]+\.css)$', views.css_renderer), re_path(r'(?P<filename>[a-zA-Z_-]+\.js)$', views.js_renderer), path('', include('mapmaker.urls')) ] And the corresponding views.py: from django.shortcuts import render # Create your views here.# def css_renderer(request, filename): print('rendered ' + filename) return render(request, filename + '.css', {}, content_type="text/css") def js_renderer(request, filename): print('rendered ' + filename) return render(request, filename + '.js', {}, content_type="text/js") However, the routes are not being matched at all. I have checked the regular expression as well. My server log: ... [06/Sep/2020 17:11:18] "GET / HTTP/1.1" 200 15728 [06/Sep/2020 17:11:18] "GET /static/mapmaker/map-styles.css HTTP/1.1" 200 4455 [06/Sep/2020 17:11:18] "GET /static/mapmaker/menu-styles.css HTTP/1.1" 200 1369 [06/Sep/2020 17:11:18] "GET /static/mapmaker/index.js HTTP/1.1" 200 4630 [06/Sep/2020 17:11:18] "GET /static/mapmaker/styles.css HTTP/1.1" 200 439 [06/Sep/2020 17:11:18] "GET /static/mapmaker/favicon.ico HTTP/1.1" 200 1150 What is the problem here? Fairly new to django here. -
How to check if there is a existing websocket connection or not?
Check websocket connection : get list of all existing websocket connection or check whether there is any websocket connection or not? -
Why cannot i access the about page when i can access the home page in the same directory?
I can access the home.html (http://127.0.0.1:8000/) without any issues but about page (http://127.0.0.1:8000/about/) gives me the below error: Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order: admin/ [name='blog-home'] about [name='blog-about'] The current path, about/, didn't match any of these. django project folder urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] app folder urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about', views.about, name='blog-about'), ] app folder views.py: from django.shortcuts import render def home(request): return render(request, 'blog/home.html') def about(request): return render(request, 'blog/about.html') directory structure: . ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-37.pyc │ │ ├── apps.cpython-37.pyc │ │ ├── __init__.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── static │ │ └── blog │ │ ├── css │ │ │ ├── main.css │ │ │ └── test.css │ │ ├── images │ │ │ ├── favicon.png │ │ │ └── freedom.jpg │ │ … -
Permission denied: '/home/ubuntu/django/media/images' while saving image on django production server on Apache2 running on ubuntu
I'm using an AWS instance to run django on production server on Apache2 server running on ubuntu. In one of the operations, I'm trying to save the profile image of the user, though I'm getting permission denied error, though everything's running smoothly on development server. Following are my settings.py configs: MEDIA_ROOT =os.path.join(BASE_DIR, "media") MEDIA_URL ='/media/' I've followed various solutions given on this thread, though still the same error persists. Can I try anything else? -
Django queryset concatenate many rows
I need to get all my customers and all the companies where they work I've tried this: customers = Customer.objects.all() customers.values('id','name','surname','city').annotate(companies=Subquery(Company.objects.filter(customer_id=OuterRef('pk')).values('name'))) but obviously I get this error: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression I would like receive this output: <QuerySet [{'id': 1, 'name': 'Matt', 'surname': 'Roswell', 'city': 123, 'companies': ['Acme','McDonalds','Burger king']}]> -
How can i solve this error "type object 'User' has no attribute 'object'"
from django.shortcuts import render from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method =='POST' : if request.POST['password1'] == request.POST['password2']: user = User.object.create_user( username=request.POST['username'], password=request.POST['password1']) auth.login(request, user) return redirect('home') return render(request, 'signup.html') this is my code. when i try to sign up, my code makes this error page enter image description here where's the angel? Help me plz -
Like Button in Django
What is the preferred method of implementing like button functionality in Django: Using only Jquery and AJAX OR Django REST Framework along with a short AJAX code? -
How to calculate the sum of a filtered column value using Django Queries
I have 2 models class Horses(models.Model): race = models.IntegerField(null=True) name = models.CharField(max_length=200, null=True) owners = models.ManyToManyField(Owners) class BetOrders(models.Model): customers =models.ForeignKey(Customers, null = True, on_delete=models.SET_NULL) horses = models.ForeignKey(Horses, null = True, on_delete=models.SET_NULL) amountBet = models.FloatField(null = True) horseprice = models.IntegerField(null=True) timeOfBet = models.DateTimeField(auto_now_add = True, null = True) I am trying to calculate the sum of amountBet based on similar horse name. i have tried this query set but in vain BetOrders.objects.filter(horses__name='white river').annotate(total_sales=Sum('amountBet')) May I Know whats wrong with this Query? and what is the correct way to get the Sum of the filtered value. Note: horse name is a FK. Here is a representation of my Table +-------+------------------+ | Horse Name | Amount Bet | +-------------+------------+ | jals jiger | 50 | | white river | 80 | | white river | 70 | | jals jiger | 10 | | jals jiger | 98 | | chivas | 10 | +-------------+------------+ -
How to Convert text fields in Dropdown fields in Django?
I am trying to convert text values to dropdown in Django filters, but I am unable to do this. I have multiple locations store in my database but I want the location dropdown filter, and I want to display all locations in the dropdown, I am using Django-filters and widget_tweaks packages, but when I am getting data from the database in the filter it's giving me an input box, please let me know how I can convert this to a dropdown. Here is my filters.py file... class MyFilters(django_filters.FilterSet): class Meta: model = Property fields = ['proprty_for'] here is my views.py file.. def property_list(request): list =PropertyFilters(request.GET, queryset=Property.objects.select_related('project')) template_name='propertyt.html' context={'list':list} return render(request, template_name, context) and here is my propertyt.html file..here I am trying to display dropdown but it's giving me an input box... <form method="GET" action=""> <div class="row"> <div class="col-xl-12 col-lg-4 col-sm-6 col-12 mb-3"> <label>Select Sale or Rent</label> <div class="dropdown bootstrap-select hero__form-input form-control custom-select"> {% render_field listing.form.proprty_for class="hero__form-input form-control custom-select" tabindex="-98" %} </div> </div> </div> </div> </form> -
Unable to upload file on a modal and get the form with objects's instance in Django
I have confused how to upload file to DB by form in a modal, as it cannot load the form with instance equal to order before open the upload form by modal. views: def user_info(request): user = request.user orders = Order.objects.filter(user=request.user, ordered=True).order_by('-start_date') order_items = OrderItem.objects.filter(user=request.user) form = Upload_File(request.POST or None, request.FILES or None)<-- the form will not not be load if I don't set the form in this view context = { 'user': user, 'orders': orders, 'order_items': order_items, 'form': form } return render(request, 'userinfo.html', context) def upload_page(request, id): order = get_object_or_404(Order, id=id) form = Upload_File(request.POST or None, request.FILES or None, instance=order)<-- but I should put the form with instance here if request.method == 'POST': if form.is_valid(): form.save() order.save() messages.success(request, 'Succeed') return redirect('user_info') else: messages.warning(request, 'Failed') return redirect('user_info') else: form = Upload_File() context = { 'form': form, 'order': order } return render(request, 'payment_upload.html', context) template including modal: {% for order_item in orders %} <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#upload-{{ order_item.id }}"> Open Modal</button> {% endfor %} modal template: <form method="post" enctype="multipart/form-data" action="{% url 'upload_page' id=order_item.id %}"> {% csrf_token %} {{ form }} <button class="form-group btn btn-success" type="submit">Confirm</button> </form> -
Django Rest Framework form in include template wont receive data
I have an empty form in a 'network' app displaying in a memberform.html template. This template is included in a index template in another 'content' app. I'm receiving a 'str' object has no attribute 'data' error during template rendering Traceback (most recent call last): File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ml/PycharmProjects/newproject/content/views.py", line 21, in index return render(request, 'index.html', context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render result = block.nodelist.render(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/Users/ml/.virtualenvs/newproject/lib/python3.7/site-packages/django/template/base.py", line … -
I'm working on a blog project I want to rank all posts by views divide by likes
I'm working on a blog project I want to rank all posts by views divide by likes I made a function which I want but I don't know how to pass it in views in .order_by(). Please help. My Post model with ranking function. class Post(models.Model): """Blog Post""" title = models.CharField(max_length=255) title_tag = models.CharField(max_length=55) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added= models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=255) likes = models.ManyToManyField(User , related_name='liked_posts' ) pins = models.ManyToManyField(User , related_name='posts' ) views = models.IntegerField(default=0) def ranking(self): total_likes = self.total_likes() if total_likes == 0: total_likes = 1 My views for Posts. def posts(request): posts = Post.objects.order_by('-views') context = {'posts': posts} return render(request, 'blog/home.html', context) I want to add ranking instead of views in ordr_by() in my views So that My posts ranks according to views divided by likes. -
Django override save method , dublicate image on update model
when i update the model , images dublicate. from django.db import models from io import BytesIO from PIL import Image from django.core.files import File #image compression method def compress(image): im = Image.open(image) im_io = BytesIO() im.save(im_io, 'JPEG', quality=60) new_image = File(im_io, name=image.name) return new_image class PhotoGallery(models.Model): image_caption = models.CharField(max_length=50, null=True, blank=True) image = models.ImageField(upload_to='gallery') #calling image compression function before saving the data def save(self, *args, **kwargs): new_image = compress(self.image) self.image = new_image super().save(*args, **kwargs) def __str__(self): return self.image_caption -
Django: Facebook like system clone
I'm new to Django and I'm trying to make a like system. I'm able to unlike every post. The problem is, the user who's logged in is not able to like the posts posted by other users(which means its not saving likes for other users' posts in database). Even though they're able to like their own posts. I don't get any errors though. Any idea where I'm going wrong? A little help would be appreciated. Here's my form: {% for i in Post %} <form action="{% url 'like_post' i.pk %}" method="post"> {% csrf_token %} <div class="like"> <button type="submit" name="post_id" value="{{ i.id }}"> <i class="fal fa-heart"></i> Like </button> {% if i.like %} <div class="show_likes"> {{ i.like.count }} Like{{ i.like.count|pluralize }} <div class="username_liked"> {% for p in i.like.all %} <div>{{ p.username }}</div> {% endfor %} </div> </div> {% endif %} </div> </form> {% endfor %} Here's my views.py: @login_required # The view to save likes and dislikes def like_post(request, pk): Post = get_object_or_404(post, id=request.POST.get('post_id')) if Post.like.exists(): Post.like.remove(request.user) else: Post.like.add(request.user) return redirect('usersfeed') @login_required # The view to load likes and other stuff def usersfeed(request): user= User.objects.all() Pos = post.objects.order_by('-created') comment = Comment.objects.all() return render(request, 'social_media/feed.html', {'Post':Pos,'User':user,'form':PostForm(),'Profile':profile,'Form':CommentForm(),'Comment':comment}) My models.py: class post(models.Model): user = models.ForeignKey(User, … -
Class based view won't work while function based view works(Django)
When I try to create a function based view it would work, displaying my queryset. This is the code I used bellow. in views.py def restaurant_listview(request): template_name ="restaurant/restaurantlist.html" query_set = Restaurant.objects.all() #all the objects that are stored in da DB context={"list": query_set} return render(request,template_name, context) But when I try to do it as a class based view it doesn't show my Queryset. in views.py `class RestaurantListView(ListView): queryset = Restaurant.objects.all() template_name ="restaurant/restaurantlist.html"` in urls.py path('restaurants', RestaurantListView.as_view() How can i solve this problem? -
Django displaying data by date range
start_date = request.GET['start_date'] # '2020-09-01' end_date = request.GET['end_date'] # '2020-09-05' data_list = WeatherModel.objects.filter(date__range=(start_date, end_date)) -
Using django model as argument for pytest parametrization
I'm trying to test if users of different business groups are allowed to make an action in a webapp using parametrization features of pytest but I can't get access to fixtures values inside parametrize. First approach: @pytest.fixture def mike_user(): user = User(username="mike", email="mike@test.com",) user.set_password("test") user.save() return user @pytest.fixture def mike_business_group(mike_user): bg = BusinessGroup.objects.create( name="Mike Business Group", user=mike_user ) bg.save() return bg.pk @pytest.mark.django_db @pytest.mark.parametrize( "resource, user, serialized_data, success", [ ( "/business/", mike_user, { "name": "New business", "description": "Hi Stackoverflow", "group": mike_business_group, }, True, ), ], ) def test_create_model_with_related_owner( apiclient, user, resource, serialized_data, success ): apiclient.force_authenticate(user=user) response = apiclient.post(resource, data=serialized_data) assert ( response.status_code == 201 ) is success Seeing lazy_fixture package I tried the following but it only success resolving mike_user having the following dictonary value for the second resolution: {'name': 'Marina L4bs', 'description': 'Happy BioHacking', 'group': <LazyFixture "mike_business_group">} Second approach: @pytest.mark.django_db @pytest.mark.parametrize( "resource, user, serialized_data, success", [ ( "/business/", pytest.lazy_fixture("mike_user"), { "name": "Marina L4bs", "description": "Happy BioHacking", "group": pytest.lazy_fixture('mike_business_group'), }, True, ), ], )