Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The profile_pic and profile_bio do not get updated in Update View in Django
So, I am trying to create a Profile Update Form. My problem is that my form updates every field except profile_pic and profile_bio. However, I have updated them successfully directly through the PostgreSQL admin. Most of the answers I found for this problem were to include enctype="multipart/form-data" in the template tag, but I have it already. How do you think I can resolve this issue? This is the Profile Model class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') profile_bio = models.TextField(null=True, blank=True) def __str__(self): return str(self.user) This is the form for Profile Update class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'username', 'email', 'profile_bio', 'profile_pic'] first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) profile_bio = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'})) password = None This is the View that is supposed to update the profile, it updates all the field successfully except profile_bio and profile_pic class UserEditView(UpdateView): form_class = EditProfileForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user The registration/edit_profile.html Template {% extends 'base.html' %} {% block title %} Edit Profile {% endblock %} {% block content %} <div class="d-flex justify-content-center"> <div class="card" style="width: … -
django postgres DateTimeField auto_now It adds 10 minutes to the current time automatically
model updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) settings TIME_ZONE = "Asia/Seoul" LANGUAGE_CODE = "en-us" USE_I18N = False USE_L10N = True USE_TZ = True if now => 2021-03-24 14:16:22.248579+00 but saved updated_at => 2021-03-24 14:26:22.248579+00 created_at => 2021-03-24 14:26:22.248579+00 I can't find the cause. Where can I check it? -
Django: API with accumulated data
I am new to python and want to implement an API with accumulated data. I've seen a lot of information about the possibility to browse the database with the django rest framework but I cannot find the right solution to view data which is analyzed or summarized. For example, I have data about some newspaperarticles: articles: [ { name: "test 1", views: 10000 }, { name: "test 2", views: 20000 }, { name: "test 3", views: 30000 } ] I want to show analyzed data like summary: { name: "articles", sum_views: 60000, article_count: 3 } What would be the best practice if I want to use django and the django rest framework? -
How can I create children of a non-existent parent page in the Wagtail CMS for Django?
I want to create children of a page (such as "/questions/example"), without having to create the root page "/questions". Is there a quick way of implementing something like this? -
Get messages from django query
def search(request): query=request.GET.get('q') if query: queryset = Q(adm__exact=query) result = Mymodel.objects.filter(queryset).distinct() return render(request, 'h.html',{'result':result} I'd like to have message get back to me incase what is in the query is not available in the database. How/where do I insert the code?? -
Atomic transaction Django not getting rolled back when second Query fails on mongoDb
I am trying to implement Atomic transaction on mongoDb using django(python) but when the second query fails it does not roll back the insertion happend in previous statement following is my API code from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.core.exceptions import ValidationError from django.views.decorators.csrf import csrf_exempt from django.db import IntegrityError, DatabaseError, transaction from rest_framework.decorators import api_view from rest_framework import status from .models import Invoice, Item # Create your views here. @api_view(["POST"]) @csrf_exempt def add(request): try: with transaction.atomic(): invoice = Invoice( Number = request.data['number'], Date = date.today() ) invoice.save() for itemReq in request.data['items']: item = Item( Invocie_Id = invoice, Name = itemReq['name'], amout = itemReq['amount'], price = itemReq['price'], ) item.save() except DatabaseError: return JsonResponse({'error': 'Could not save element, possibly duplicate'}, safe=False, status=status.HTTP_403_FORBIDDEN) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return JsonResponse({'success': 'Saved Sucessfully'}, safe=False, status=status.HTTP_200_OK) -
How to convert money from a currencies to another in Python
I am using Django to build a money transfer application and I would like a way to build a template tag in order to automatically exchange money from one currency to another using the OPENEXCHANGE URL. So, I referred to this link: https://django-money-rates.readthedocs.io/en/latest/readme.html but it does not work and facing the issue in the attachment. How can I do it, please? Or is there another way to solve the problem? For more information, I am using Django-3.1.7 and Python-3.8 Thanks -
Django/Rest Framework Nest Serialization
I'm having a bit of trouble with implementing the serialization for my server. It is a host to demonstrate homomorphic encryption. Storage on the server consists of integers (really two integer tuples (X,q)), which are tied to a single set, sets are tied to sessions, sessions are tied to users... sets & sessions can both be posted. Posting a set includes the user_id, session_id and multiple integers in the request. Posting a set includes the user_id, session_id, then multiple sets in the request. Also, for a set the server generates an ID and sets that value for all integers in the set, and includes it in the response. Ideally, the user_id and session_id are going to be put in once in either type of request. So for a session post, each set does not have the user_id, session_id, but for a set post the set does have those values. For get requests, similar idea... one instance of user_id, session_id, and this time set_id because it was created in the post. A user can request a set or session in the GET request as well. I understand the basic idea of serialization, but I have trouble when nesting comes into play. … -
Simultaneous authorization of the administrator in the admin panel and on the site
When logging in through the admin panel, the administrator simultaneously logs in to the site and in the admin panel, how can I fix this, please tell me? The problem is that when I go on behalf of the admin in the admin panel, authorization occurs on the site that I am developing, and I do not need it. I would like the authorization to be performed separately on the site(for users) and on the admin panel(for admin).(DJANGO).Please help me with this question ??? -
Django - Trying to keep track of user's cart
I have a cart where I have two fields that I use to connect to a user. One is User, I use that if user is logged in. Other is session, this is used to keep track of logged out users. It uses session_key. Now the problem I am facing is that when a user logs in the cart disconnects because the session_key has changed. I know that I can use cookie to identify the browser or client. But I am not able to find an example of Django's set_cookies being used with JsonResponse(AJAX call). It is only for HttpResponse. I think I could use either of these two ways, if possible. Set cookie through AJAX Or Set cookie when user visits website. I want this with ability that no matter which page the user visits at fist the cookie should be set on that visit. Does anyone have a resource or example to achieve this? Thank you -
Toggle Structure in Django-cms toolbar is Disabled
Problem: CMS-toolbar is hiding Navigation bar menus & it's now disabled(not moving up). Django version = 3.0.8 Django cms = 3.8.0 {% cms_toolbar %}<!-- from cms toobar --> <body> <!-- Navigation --> <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="index.html">Start Bootstrap</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> {% show_menu 0 100 100 100 %} <!-- for cms menu --> <li class="nav-item"> <a class="#" href="about.html">About</a> </li> <li class="nav-item"> <a class="#" href="services.html">Services</a> </li> </ul> </div> </div> </nav> How can I convert that icon to arrow one which can be moved up and down easily? This is what I have This is what I need -
ERR_CONNECTION_REFUSED Serving Django Project on Ubuntu
I am serving Django Project on Digitalocean Ubuntu Droplet. When I am configure https connection everything collapse and I can nat browse my ip 188.166.117.124 On every browser I get ERR_CONNECTION_REFUSED error $ grep server_name /etc/nginx/sites-enabled/* -RiI /etc/nginx/sites-enabled/default: server_name _; /etc/nginx/sites-enabled/default:# server_name example.com; /etc/nginx/sites-enabled/personal_web_site: server_name 188.166.117.124; $ netstat -tlpdn Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:80 0.0.0.0:* listen - tcp 0 0 127.0.0.53:53 0.0.0.0:* listen - tcp 0 0 0.0.0.0:22 0.0.0.0:* listen - tcp 0 0 0.0.0.0:5432 0.0.0.0:* listen - tcp6 0 0 :::80 :::* listen - tcp6 0 0 :::22 :::* listen - tcp6 0 0 :::5432 :::* listen - $ netstat -tulpn | grep :80 tcp 0 0 0.0.0.0:80 0.0.0.0:* listen - tcp6 0 0 :::80 :::* listen - strong text $ sudo ufw status to action from ----- ----- -------- Nginx Full ALLOW Anywhere Nginx HTTP ALLOW Anywhere Nginx HTTPS ALLOW Anywhere 8000 ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6) Nginx HTTPS (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) I tried with $ sudo ufw disabled nothing changed What is the problem of my server -
How do you change django widget select attrs?
I'm trying to add new attributes to this ChoiceField so with help of ddslick() it should display images instead of text, but I'm unable to do so, I've tried declaring it explicitly before and after the meta class or simply as an normal widget, but without success, neither the generated <select> or <option> tags changed any of it's attributes, I was wondering if there's anything else that I can try. class MemoryForm(ModelForm): cover_image=(ChoiceField(widget=Select(attrs={'class': 'asdf'}))) class Meta: model = Memory fields = [ "title", "description", "date", "location", "accurate_date", "accurate_month", "accurate_day", "cover_image", ] labels = {"title": "", "description": "", "date": "", "location": ""} widgets = { "title": TextInput( attrs={"placeholder": _("Enter a title"), "class": "only-bottom"} ), "description": TextInput( attrs={ "placeholder": _("Add a description (optional)"), "class": "only-bottom", } ), "location": TextInput( attrs={"placeholder": _("Enter a location"), "class": "only-bottom"} ), "date": HiddenInput(), "accurate_date": HiddenInput(), "accurate_month": HiddenInput(), "accurate_day": HiddenInput(), "cover_image" : Select( attrs={"data-imagesrc": "/static/media/images/cherryimage/e2e4a952-e949-4b97-8597-eebd9bd445d5.jpg"} ), } -
Which is best method to deploy django site on production server?
In how many different ways I can deploy django web app? Can you explain any one method in detail? -
Django forms request
My Django application has two models. Which are Vehicle and Offer. So users can submit offers for vehicles. When submitting an offer I want to capture user_id and vehicle_id with the form. views.py def your_view(request): if request.method == 'POST': offer_form = Offerform(request.POST) if offer_form.is_valid(): instance = offer_form.save(commit=False) instance.user = request.user instance.vehicle = ? instance.save() messages.success(request, 'Offer submitted successfully') return redirect('vehicles') models.py class Offer(models.Model): name = models.CharField(max_length=90, blank=False) email = models.EmailField(max_length=90, blank=False) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) I can get the user with reqeust.user but how to get the vehicle_id that the user submits their offers to? -
Few ids in urlspattern
I am making a API with REST Framework. I can't find out how to create an urlspattern that got 2 id's from main model and primary model. Models: class Diary(models.Model): title = models.CharField(max_length=100, null=True) data = models.CharField(max_length=100, null=True) class DiaryRecord(models.Model): diaryID = models.ForeignKey(Diary, on_delete=models.CASCADE) data = models.CharField(max_length=25, null=True) Sample: path('api/diary/<int:firstID>/record-update/<int:secondID>/', views.defName) #firstId is id of Diary(Main model). Second id is DiaryRecord id. So i need to show a records, that belong to Diary. -
Django view decorator exception does not prevent view execution
A docorator that is suppose to send a 403 page let the rest of the view execute. request-token library provides a view decorator. If provided token is expired an exception is raised. Documentation says if such exception is raised, 403 response is send. When token is expired, decorator do raise an exception but the rest of the view is still executed and no 403 response is send. @require_POST @use_request_token(scope="my_scope") def my_view(request): print('after raised') # this code is executed return JsonResponse({ 'status': 'everything is fine !!!'}) # Wrong ! raise ExpiredSignatureError('Signature has expired') jwt.exceptions.ExpiredSignatureError: Signature has expired after raised Is this behavior normal ? How can I prevent view being executed if an exception is send by decorator ? -
Django form with fields and Ajax dependent Dropdown list from 4 different models
I want to insert data to the DB tables using Django ModelForm, the form is populated from 4 different Models. My Models: Region: name, District: name and region foreign key, Address: street, address, and district foreign key, Property: name, staff_manager(User model foreign key), and address foreign key. (All models' fields are set not to be blank) My forms: PropertyForm: fields = ['name', 'staff_manager'], AddressForm: fields = ['street', 'address'], for Region and District fields, I've used a dependent dropdown list with the help of Json, Ajax and Js, where districts will be shown depending on a selected region. My Challenge/Objective: I want to be able to simultaneously create a Property, and Address (insert it's street, address & district_id ---> which will be selected depending on region choosen from the form), all from a single form. My Models: Region & District Models, Address & Property Models My Form: ModelForm, Form HTML, Form-Frontend My Views: View, Region & District Json View Dependent Dropdown list Ajax & Js: Region Ajax Javascript Any help, insight or different perspectives of achieving my objective will be greatly appreciated. Thanks -
Overriding simple-jwt's TokenObtainPairSerializer to implement 2FA
I am currently trying to implement 2FA in my Django Application. The first thing I've done is to modify the Meta class in the UserSerializer class to add two fields enabled (indicates if 2FA is enabled for a user) and secret_key (the key to generate OTP, that is shared to the user when he enables 2FA). To minimally modify the login flow, I've modified the form that is sent to generate the access tokens to include a new field "otp". The user can fill it or not, and the backend will check if the user has 2FA enabled, and if yes, if the OTP is correct. Without 2FA, the login is simply a POST request with body {"username": usr, "password": pwd}. This has become a POST request with body {"username": usr, "password": pwd, "otp": otp}. If a user user hasn't enabled 2FA, he can simply leave the opt field blank. My urls.py looks like this: path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair") My idea is to override TokenObtainPairView to adapt to the new request. From what I've found, I have to change the validate method, but I don't really have a clue as to how to do that. I probably would have to get … -
How do we forward a InMemoryFile in request.files to other External APIs in Django
if "files" not in request.FILES: return Response({"sucess" : False, "code": 500, "message" : "Please select file and then click upload"}) if "documentCategoryUuid" not in request.data: return Response({"sucess" : False, "code": 500, "message" : "Please select document category"}) files = request.FILES.getlist('files') try: documentCategory = DocumentCategories.objects.get(documentCategoryUuid=request.data["documentCategoryUuid"]) except Exception as e: return Response({"sucess" : False, "code": 500, "message" : repr(e)}) for upload_file in files: documentName = upload_file.name.replace(" ", "_") -
Django m2m_changed signal, post_add is called automatically after post_remove
I want to remove user from moderatos, when it is removed from users field. but when i called instance.moderators.remove(*pk_set) it is removed and then added again by post_add signal. works in this way users.pre_remove > users.post_remove > moderators.pre_remove > moderators.post_remove > moderators.pre_add > moderators.post_add the last two (pre_add, post_add) are getting called unnecessarily I am using Django admin page for these operations. Model : class Tank(models.Model): device = models.OneToOneField(Device, on_delete=models.SET_DEFAULT, related_name="tank", default=1) users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="tanks", blank=True) hidden_for_users = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="hidden_tanks", blank=True) admins = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="tanks_of_admin", blank=True) moderators = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="tanks_of_moderator", blank=True) name = models.CharField(max_length=40) Signals : @receiver(m2m_changed, sender=Tank.users.through) def on_tank_users_change(instance, action,pk_set, **_): if action == 'post_remove': instance.moderators.remove(*pk_set) -
Ignore all current migrations and start from current model state WITHOUT deleting the migration files/history
Preface: Migrating from Oracle to Postgres with a VERY large, VERY old Django app. Need the ability to start a new db from the current state of my models, ignoring 5+ years of migrations, BUT without deleting any of the migration files. -
Django test returns 404 despite of correct URL
I am using this tutorial for learning Django Test. On running the following error: ➜ DjangoSimpleIsBetter python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F...... ====================================================================== FAIL: test_board_topics_view_contains_link_back_to_homepage (boards.tests.BoardTopicsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/X/Data/Development/PetProjects/DjangoSimpleIsBetter/boards/tests.py", line 47, in test_board_topics_view_contains_link_back_to_homepage self.assertContains(response, 'href="{0}"'.format(homepage_url)) File "/Users/X/Data/anaconda3/lib/python3.7/site-packages/django/test/testcases.py", line 462, in assertContains response, text, status_code, msg_prefix, html) File "/Users/X/Data/anaconda3/lib/python3.7/site-packages/django/test/testcases.py", line 434, in _assert_contains " (expected %d)" % (response.status_code, status_code) AssertionError: 404 != 200 : Couldn't retrieve content: Response code was 404 (expected 200) ---------------------------------------------------------------------- Ran 7 tests in 0.068s FAILED (failures=1) Destroying test database for alias 'default'... Below is the Test code: class BoardTopicsTests(TestCase): def test_board_topics_view_contains_link_back_to_homepage(self): board_topics_url = reverse('board_topics', kwargs={'id': 1}) response = self.client.get(board_topics_url) homepage_url = reverse('home') self.assertContains(response, 'href="{0}"'.format(homepage_url)) urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path from boards import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^boards/(?P<id>\d+)/$', views.board_topics, name='board_topics') -
Django3 Like Ajax Button Book By Antonio Mele
It works but when press like button it coun 2099 instead of 1, after refresh it turn 1..when unlike same problem happend...It counts correctly after refresh....before refresh it count 2099 or 3011 random number I tried some solution from stackoverflow but it didn't give me much better result.. Ajax: {% block domready %} $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "images:like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); {% endblock %} HTML: {% with total_likes=image.users_like.count users_like=image.users_like.all %} <div class="image-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <span class="count"> {{ total_views }} view{{ total_views|pluralize }} </span> <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}un{% endif %}like" class="like button"> {% if request.user not in users_like %} Like {% else %} Unlike {% endif %} </a> </div> {{ image.description|linebreaks }} </div> <div class="image-likes"> {% for user in users_like %} <div> <img src="{{ … -
SQL DATA BASE QUERY
City Id Name 1 Delhi 2 Noida 3 Gurugram Parameter Id Name 1 Health 2 Education 3 Employment Rating Id Rating City_Id Param_Id Quarter Year Value_Date 1 7.5 1 1 Q1 2017 2017-02-15 2 6.3 1 1 Q1 2017 2017-02-13 3 6.9 1 1 Q1 2017 2017-02-20 4 8.2 1 1 Q2 2017 2017-04-05 5 5.5 1 1 Q2 2018 2017-12-13 6 7.6 1 1 Q3 2017 2017-08-20 7 4.5 2 1 Q1 2017 2017-02-17 8 5.3 2 1 Q1 2017 2017-02-14 9 6.9 2 1 Q1 2017 2017-02-25 10 7.2 2 1 Q2 2017 2017-08-05 11 8.5 2 1 Q2 2018 2017-12-13 12 9.6 2 1 Q3 2017 2017-08-20 13 3.5 3 1 Q2 2018 2017-12-14 14 4.6 3 1 Q4 2017 2017-08-17 15 5.5 3 1 Q2 2018 2017-12-20 16 7.6 3 1 Q3 2017 2017-08-15 17 7.5 3 1 Q2 2018 2017-12-18 18 8.6 3 1 Q3 2017 2017-08-24 19 7.5 1 2 Q1 2020 2018-05-25 20 6.3 2 2 Q3 2018 2018-17-13 21 6.9 3 3 Q2 2019 2019-06-20 I want to fetch the data from the Rating Table. I have a list of city ids, parameter ids, Quarter and Year. For Example city_id = [1,2,3], …