Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mongoengine referencefield
Here's an example code: class A: pass class B: a = mongoengine.fields.ReferenceField(A, verbose_name='a') What would be the best practice to query A.b. Of course I can make a @property b with complicated query, but I thought maybe there is something out of the box specially for that, unfortunately I couldn't find anything. -
Why is my TypeError saying 'unsupported operand type(s) for +: 'int' and 'str'
I'm running Django and trying to do an e-commerce site. I'm working with totals in my cart to get the following: Total number of cart items Retrieve all cart items Total cost of all items. my code is as follows models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total line 54 in models.py is total = sum([item.get_total for item in orderitems]) views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: # Create empty cart for now for non-logged in user items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} context = {'items': items, 'order': order} return render(request, 'IT6041App/cart.html', context) cart.html {% extends "IT6041App/base.html" %} {% load static %} {% block content %} <br><br><br> <div class="row justify-content-md-center"> <div class="col-lg-6"> <br> <div class="box-element"> <div class="cart-row"> <a class="btn btn-outline-dark" href="{% url 'index' %}">Continue Shopping</a> <div style="flex:1"></div> <div style="flex:1" align="center"><strong>Item</strong></div> <div style="flex:1" align="center"><strong>Price</strong></div> <div style="flex:1" align="center"><strong>Quantity</strong></div> <div style="flex:1" align="center"><strong>Total</strong></div> </div> {% for … -
Failed lookup for key [user] in <User: test> error when testing a view
I have a freind requests app that can send/cancel/accept/delete friend requests and I am trying to test it, however when I'm accepting a friend request and adding users to each other friend lists I am getting a Failed lookup for key [user] in <User: test> exception. models.py class User(AbstractBaseUser, PermissionsMixin): name = models.CharField('Full Name', max_length=35, unique=True, null=False, blank=False) friends = models.ManyToManyField("User", blank=True) def __str__(self): return self.name class FriendRequest(models.Model): objects: models.Manager() to_user = models.ForeignKey(User, related_name='to_user', on_delete=models.CASCADE) from_user = models.ForeignKey(User, related_name='from_user', on_delete=models.CASCADE) views.py from django.db import transaction def accept_friend_request(request, pk): try: with transaction.atomic(): from_user = User.objects.get(pk=pk) f_request = FriendRequest.objects.filter( from_user=from_user, to_user=request.user ).first() user1 = f_request.to_user user2 = from_user user1.friends.add(user2) print(user1.friends.all()) user2.friends.add(user1) print(user2.friends.all()) f_request.delete() return redirect(request.get_full_path()) except Exception as ex: print(ex) return HttpResponse('User does not exist') Here as you can see I am using the transaction.atomic() to prevent the exception from breaking the unittest transaction. tests.py def setUp(self): self.client = Client() self.user = User.objects.create_user(email='test@gmail.com', name='test', password='test') self.user1 = User.objects.create_user(email='test1@gmail.com', name='test1', password='test1') self.client.force_login(self.user) def test_accept_friend_request(self): friend_request = FriendRequest.objects.create(from_user=self.user1, to_user=self.user) self.client.get(reverse('accept_friend_request', kwargs={'pk': self.user1.pk}), follow=True) self.assertIn(self.user, self.user1.friends.all()) self.assertIn(self.user1, self.user.friends.all()) In my test I create a friend request object and send an accept request to the view which should add each of the users to each one … -
Django formtools user registrations password
Trying to create user using django-formtools. forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = User fields = ('username', 'password1', 'password2') class CustomProfileCreateForm(forms.ModelForm): class Meta: model = User fields = ('name', 'email') views.py class SignupWizard(SessionWizardView): template_name = "user/registration.html" form_list = [CustomUserCreationForm, CustomProfileCreateForm] instance = None def get_form_instance(self, step): if self.instance is None: self.instance = User() return self.instance def done(self, form_list, **kwargs): self.instance.save() return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) All are ok except password. Password is not set. How to save form correctly -
Difference in time between database and value displayed
I am trying to fix strange problem with time in my project. First of all my settings are as follows: settings.py LANGUAGE_CODE = 'pl-pl' TIME_ZONE = 'Europe/Warsaw' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = 'Y-m-d H:i:s' DATE_FORMAT = 'Y-m-d' Every DateTimeField field, for example: models.py class Order(models.Model): date_zal = models.DateTimeField() is displayed correctly in my home.html file with the help of {{ order.data_zal }} but when I look into my database (still Sqlite3, going to switch to MySql soon) there is ALWAYS date with 1 hour earlier (e.g. 11:40 displayed vs 10:40 in database). Not sure where lies the problem since it is displayed properly. -
Django RestApi Problem : viewsets in views not found
I tried to create an api for my project, but somehow I cant retrieve the viewsets on my function, what did I do wrong? -
Make thumbnail from jpg, jpeg or png
I have the following method to create a thumbnail, but I would like it also to generate it in case the file type is png, as it currently throws an error for them: from io import BytesIO from django.core.files import File from PIL import Image def make_thumbnail(image, size=(600, 600)): im = Image.open(image) im.convert('RGB') im.thumbnail(size) thumb_io = BytesIO() im.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail How can I effectively accept png, jpg and jpeg to generate the thumbnail? -
drf_yasg - swagger request url issue
I have a project with Django + Nginx + Gunicorn setup. In this project, I am running Nginx with 8000 port, here when I test endpoints using postman it is working fine but when I use Swagger it is not working. Swagger was trying to access the URL without the port ( ex: curl -X GET "http://172.16.235.109/runs/" -H "accept: application/json" ). so it is not working. I explored a lot but I could not find the right way to solve this problem. Anyone, could you please help me to resolve this issue? Requirements am using Django==3.0.3 drf-yasg==1.17.1 (SWAGGER) gunicorn==20.0.4 -
QueryDict Object has no attribute session Django
So I basically have a login form which I have defined like this: def login_request(request): if request.method == 'POST': data = request.POST auth_backend = AuthenticationBackend() login_form = LoginForm(data) if login_form.is_valid(): user = auth_backend.authenticate(data, password=data['password'], email=data['email']) if user: login(data, user) # redirect to homepage else: login_form.add_error('password', "Password doesn't match email") else: data = {} login_form = LoginForm() return render(request, 'login.html', {'form': login_form, 'data': data}) If the given conditions match, the user must be logged in. However, when I do login(data, user) I get this error: Internal Server Error: /users/login/ Traceback (most recent call last): File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\users\views.py", line 34, in login_request login(data, user) File "C:\Users\Iyappan\PycharmProjects\pyDjangoTest\venv\lib\site-packages\django\contrib\auth\__init__.py", line 99, in login if SESSION_KEY in request.session: AttributeError: 'QueryDict' object has no attribute 'session' Why is this happening? How can I fix this? Please help me, thanks in advance! -
too late for learning flask? and how shloud I shoose my DB?
I'm a junior web developer and I completed all of what I need from front end develpoment and a little more: html/css/js vue python c# ps: dropped this one and now I'm starting with backend development, so I started with django and found out that it's a little too complicated but I continued for a while and now I hear people saying that if you want to start with a web framework you should start with flask even if your end goal is django. So that got me thinking that I'm still finding django a bit hard and slow to learn for me and I thought that am I doing it wrong and that I should stop learning django and just start slow. keep in mind I don't know that much of django to say I'm too late or early and I should switch. so what do you think I should do at this point? and additionally I searched about answers to what sql should I learn and got lost in the answers. sql sounds nice, sqlite comes with django and flexible, mongodb is too easy and postgresql also seems like a good choice so I don't know where to … -
index page not displaying and returning error 200 on Django terminal
i have an index page which extends a navbar.html in Django and is followed by other codes. when i run the server, the server runs but displays "GET /health/ HTTP/1.1" 200 4619" which i understand is a blank page but my index.html is not blank. The page shows the extended navbar.html but nothing more. The views look like: def index(request): return render(request, 'My_Doc/index.html') And urls look like: urlpatterns = [ path('', views.index, name='index'), ] Requesting for help>>>> -
Django 3.1.1 - changing password success but success page don't show
I config urls and add custom template (override registration/password_change_done.html and registration/password_change_form.html:) in my project but when I change password success the url have changed correctly (http://127.0.0.1:8000/accounts/password/change/done/ url) but success page didn't show, it still shows the change password form. My code as below: configuration urls.py: from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ url('password/change/', auth_views.PasswordChangeView.as_view(), name='password_change'), url('password/change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), url('password/reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), url('password/reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url('password/reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url('password/reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] password_change_done.html: {% extends "base.html" %} {% block content %} <div class='row'> <div class="col-12 text-center py-5"> <h1 class='my-5 py-5'>Password successfully changed!</h1> </div> </div> {% endblock %} password_change_form.html: {% extends "base.html" %} {% block content %} <div class='row'> <div class='col-md-6 col-10 mx-auto'> <h1>Change your Password</h1> <form method='post' action=''>{% csrf_token %} {{ form.as_p }} <span style='margin-bottom: 12px;'></span> <button type="submit" class='btn btn-block btn-info'>Save</button> </form> </div> </div> {% endblock %} -
DRF object with slug_field="" doesn't exist
I'm creating a very simple api with drf and that's my problem: I have this code in serializers.py: class PostSerializer(serializers.ModelSerializer): comments = serializers.SlugRelatedField( queryset= Comment.objects.all(), many= True, slug_field='body' ) class Meta: model = Post fields = ['pk', 'user', 'title', 'content', 'comments', ] read_only_fields = ['pk', 'user'] When l open api/1 in my browser l get this as expected: { "pk": 1, "user": 1, "title": "Lorem", "content": "First post", "comments": [ "My Comment", "Second Comment" ] } When l try to update this with PUT method all fields work fine, except comments, when l try to add a new one it gives me this error: { "comments": [ "Object with body=my new comment does not exist." ] } How do l solve that, so when l add a new comment it's get pushed to db? -
I use bootstarp navbar. When I scroll up.. the block content appear behind the navbar. Navbar fixed on the top
I use bootstarp navbar. When I scroll up.. the block content appear behind the navbar. Navbar fixed on the top. My Navbar <main id="navfix" class="m-5"> <nav class="navabar_bgc py-0 navbar navbar-expand navbar-light fixed-top"> {% include 'sidebar.html' %} <div class="collapse navbar-collapse" id="collapsibleNavId"> <ul class="navbar-nav ml-auto mt-lg-0"> <div>...</div> </ul> </div> </nav> </main> <div class="block__content"> {% block content %} {% endblock %} </div> My css: #navfix { width: 100%; } .navabar_bgc { background-color: rgba(103, 250, 34, 0.4) !important; box-shadow: 0px 0px 8px !important; z-index: 10 !important; } .block__content { z-index: 5; overflow: auto; } Any other suggestion please give me..Thanks. -
how to link to search results in pagination Django 3.1
I want to implement pagination on the search results page of my site. My Django project has a few apps that have different models and the search will look in every table for results. for ex.: # views.py def search(request): queryset_list_ip_sensor = Ip_sensor.objects.all() queryset_list = ControlValves.objects.all() queryset_list_water_quality_sensor = Water_quality_sensor.objects.all() context = { 'ip_sensors': result_list_ip_sensor, 'controlvalves': result_list_control_valves_2, 'water_quality_sensor': result_list_water_quality_sensor, 'values': request.GET, 'keywords': keywords } return render(request, 'pages/search.html', context) I implemented pagination like this: # views.py def search(request): # ... result = (result_list_ip_sensor, result_list_control_valves, result_list_water_quality_sensor) paginator = Paginator(result, 1) page = request.GET.get('page') paged_queries = paginator.get_page(page) context_pagination = {'ip_sensors': result_list_ip_sensor, 'controlvalves': result_list_control_valves_2, 'water_quality_sensor': result_list_water_quality_sensor, 'queries': paged_queries, 'keywords': keywords, 'values': request.GET } return render(request, 'pages/search.html', context_pagination) Before pagination I used to show results like this: {% if ip_sensors %} {% for ip_sensor in ip_sensors %} <div class="col-12 col-sm-12 col-md-4 col-lg-4 col-xl-4 mb-4"> <div class="card"> <div class="card-header"> I/P Sensor </div> <img class="card-img-top" src="{{ ip_sensor.cover.url }}" alt=""> <div class="card-body"> <div class="text-center"> <h4 class="text-dark">{{ ip_sensor.title }}</h4> <p> {{ ip_sensor.description | truncatewords:10 }}</p> </div> <hr> <div class="row py-2 text-dark"> <div class="col-6"> Product Name: {{ ip_sensor.product_name | truncatewords:2 }}</div> <div class="col-6"> Usage: {{ ip_sensor.usage | truncatewords:4}}</div> </div> <hr> <a href="{% url 'ip_sensor_item' ip_sensor.title %}" class="btn btn-light btn-block">More Info</a> </div> … -
How to play a generated mp3 on the user's browser?
My django view.py generates an mp3 file on the server at ./speech.mp3 after user interaction. How do I play it on the user's browser? If I just play the mp3 file using python code in view.py, it'll only be played on the server PC, not the user's browser. I'm thinking of 2 solutions: Either I have to pass the mp3 to the user's browser through ajax OR upload it to a cloud service. Not sure how to approach though. -
Django : Tables in SQL duplicates
I'm trying to migrate my migrations and I get those weird duplicated tables inside my SQL database. I have used Meta class for all my models to change their names inside the database: class Meta: db_table = 'User_Computer_Knowledge' I have two apps (accounts - for authentication and else, main - for all other things) Pastebin links: My whole accounts model My whole main model After migrating I get these results : What's the problem? -
Django limit user view rights for model object
I have an app with multiple users from different companies. I need to restrict access such that certain users from certain companies can only see model objets relevant to their company. For e.g. when I display a drop-down in a template, I want the dropdown contents to be different for each user based on their predefined permissions. I am not a developer so I may be reading the Django documentation poorly, but if I were to guess it doesn't seem possible. If indeed it is not straight forward via Django built-ins, is there any clever workaround? -
Bootstrap DatePickerPlus Format Doesn't Change
I am using Bootstrap DatePickerPlus and although I'm setting the format to DD/MM/YYYY, the form is often failing validation with the error Enter a valid date/time as it is trying to validate as MM/DD/YY. For example, 23/02/2020 will fail, but 02/23/2020 will pass. I have tried many things but the stuff I have tried seems to be for Django's DatePicker, not Bootstrap's DatePickerPlus. Any help would be greatly appreciated. models.py date = models.DateTimeField('Date (dd/mm/yyyy)', default=now) forms.py class Meta: model = Booking fields = '__all__' widgets = { 'date': DatePickerInput( options={ "format": "DD/MM/YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } Thank you. -
Error during WebSocket handshake: Unexpected response code: 400-ReactJs and django socket.io
I've a django socketio as server and reactjs as client django server wsgi.py import os from django.core.wsgi import get_wsgi_application from app.views import sio import socketio os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quantsite.settings') django_app = get_wsgi_application() application = socketio.WSGIApp(sio, django_app) views.py import os from django.http import HttpResponse import socketio async def index(request): return web.Response(text="hello", content_type='text/html') @sio.event async def connect(sid, environ): print('Client connected',sid) await sio.emit('message', "good") @sio.event async def disconnect(sid): print('Client disconnected',sid) @sio.on('message') async def message(sid, data): print("server received message!", data) await sio.emit('reply', data) Client side-Reactjs import io from 'socket.io-client'; let socket ; componentDidMount() { socket=io('localhost:8000',{transports:['websocket']}); socket.on('connect', ()=> { console.log("connected"); // true }); socket.on('message', function(msg){console.log('message!', msg)}); socket.on('reply', function(msg){console.log('reply!', msg)}); socket.on('disconnect', () => { console.log(socket.connected); // false }); } When i'm running both cilent and server,i'm getting error WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 at client side and "GET /socket.io/?EIO=3&transport=websocket HTTP/1.1" 400 11 at server side socket.io-client verison-2.3.0 -
Django - accessing a stored excel file in Django model viewer
I am trying to access excel files through the django-admin model viewing portal. Each excel file is generated through a seperate algorithm, and is already in a directory called excel_stored each excel file is generated with an ID that corresponds to its model # in django. So it would be excel_%ID%.xlsx or excel_23.xlsx for example. I want my django FileField() to access the relevant excel file so that I can download it from my django admin portal, just like I can access my other model information (city name, time uploaded, etc). Here is a pseudo-code of what I'd want to do: My models.py would look like this excel = models.FileField() The process of saving would look like this create_excel() ### EXCEL WAS SAVED TO DIR: excel_stored ### save_excel = Model(excel = file.directory((os.path.join(BASE_DIR, 'lead/excel_stored/excel_%s.xlsx' %ID)) save_excel.save() Id then be able to download it like this https://i.stack.imgur.com/4HRUU.gif I know there's a lot I'm missing, but most documentation I find refers to uploading an excel file through forms, not accessing it. I've been stuck on this for a while, so I'd appreciate some direction! Thank you! -
"Visual" set up project page for django?
I would like to sell app to lot of people. The problem i got is, i don't want people have to set variable into settings.py file, because they have no knowledge into programmation. So i would like to know if it's possible to do this kind of stuff : They connect to the site on admin (or maybe just connect first time) That redirect them to a page with form They choose their settings and that update it directlty into settings.py Like that they will just set the project with a beautiful view, and they have no edition of settings.py to do manually. Thank for your help ! -
How to count Artist in ManyToMany Field in Django
i want to count the number of videos made by a single artist so please tell me where am i wrong? Here is My code in admin.py File class ArtistAdmin(admin.ModelAdmin): list_display = ['name', 'date_of_birth', 'artist_videos'] def artist_videos(self, obj): count = 0 for artistcount in Artist.objects.all(): if artistcount.name == VideoList.artists: count = count + 1 return count And her is my code in models.py class Artist(models.Model): name = models.CharField(max_length=200) date_of_birth = models.DateTimeField() def __str__(self): return self.name class VideoList(models.Model): title = models.CharField(max_length=200) artists = models.ManyToManyField(Artist) def __str__(self): return self.title -
How to save json in django database?
I need to save json file from API in database (postgresql) using django. I have classic model which extends the AbstractUser with the default fields for first name, last name and etc. I made a research but can't find how to achieve saved json from API in database while using django. I will appreciate any help or guide. -
Recieving errors when running server with manage.py
im trying to run a server on my laptop, when in the console i type 'python manage.py runserver' i recieve some errors. could it be i need to import some modules i tried 'pip install python-cron' but that didnt work. the error says: [2020-11-10 09:04:47,241] autoreload: INFO - Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_cron' the cron.py file i have is: from django.contrib.auth.models import User import os import datetime from crontab import CronTab #from django_common.helper import send_mail from …