Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How could I work with Django simultaneously with my friends?
I need your help with Django. How can I work in team in Django? And what instruments I will have to have? -
how can I translate content by calling a locale file in template?
so I'm trying to translate the content of a website using locale files based on the language chosen by the user from a drop-down menu but I can't figure out how to call a locale file or translate in templates. I mean in views we write translation.activate(lang) but how to do it in html templates? I want something as: if($("#select").val('spanish')){ get_local_file.name("es") } <div class="language"> <p id="lang">Languages:</p> <select id="select"> <option value="english">English</option> <option value="spanish">Spanish</option> <option value="arabic">Arabic</option> </select> </div> -
Django-filter and restframework pagination infinitely appends query
I have a viewset with settings looking like below class JobPostViewSet(viewsets.ModelViewSet): ... filter_backends = (DjangoFilterBackend,) filterset_class = filters.JobPostFilter pagination_class = DefaultCursorPagination My filter is as below class JobPostFilter(FilterSet): class Meta: model = models.JobPost fields = { 'company__type': [ 'in' ], 'approval_status': [ 'exact' ], 'sex': [ 'in' ], 'education': [ 'in' ], 'business_strategy': [ 'in', ], 'base_salary': [ 'in' ], 'settlement_support': [ 'in' ], 'scout_royalty': [ 'in' ], 'mortgage': [ 'in' ], 'db_availability': [ 'in' ], 'experience': [ 'in' ] } When I send a pagination request to http://localhost/api/paginate?approval_status=true I get additional ?approval_status=true appended to the URL every time I paginate. For example nextLink value from first pagination from django returns http://localhost/api/paginate?approval_status=true&approval_status=true&cursor=xxx. The next pagination returns http://localhost/api/paginate?approval_status=true&approval_status=true&approval_status=true&cursor=xxx and so on, infinitely adding existing query parameters. How do I make sure that query params don't get duplicated? -
Send element id from div to javascript file
I am trying to trigger a file input using javascript. I am using Django formset and I have obtained the id of the input fields current my Javascript functions looks like: $(document).ready(function(){ $("#show-image-upload-inputs").click(function(){ $("#image-upload-div").toggle(); }); function open_input (id,input_id) { $(this.id).on("click", function () { $(this.input_id).trigger("click"); }); } }); And in my HTML I am passing them to the function, using onclick: <div id="file-0-selector" class="add-image" onclick="open_input(this.id,document.getElementById('id_form-0-image'))"><i class="mt-2 fas fa-plus fa-5x"></i></div> However, when I click on it I do not see the upload box opening, I was wondering how I can achieve this. I have acquired the image input fields form my formset and the id seems to be correct. Thanks in advance. -
Error of "Command 'pip' not found" when trying to install requirements.txt
I'm trying to do: pip install -r requirements.txt on an AWS server. I recently pulled a git commit. I get this error: Command 'pip' not found, but can be installed with: sudo apt install python-pip So I tried entering: sudo apt install python-pip install -r requirements.txt and then sudo apt install python-pip -r requirements.txt But both attempts gave me this error: E: Command line option 'r' [from -r] is not understood in combination with the other options. What is the correct command to install this? Thank you. -
How to set cursor nextLink domain correctly in Django app behind nginx
I have nginx config as below location /api { rewrite /api/(.*) /$1 break; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://rest; proxy_redirect off; } it's trimming out the /api/ part of the url to send to django app. The initial request works fine; however, the nextLink sent from django app pagination does not include the /api/ part. So for example if I send the first request to http://localhost/api/paginate django should send http://localhost/api/paginate?cursor=xxx under nextLink but I get http://localhost/paginate?cursor=xxx instead. How do I overcome this problem at the nginx level? -
Django, how to render view in recursive python function after each call?
When I press a html button JavaScript does a ajax call to a python function in django. The function runs recursively changing objects each time. I want render a view every time the object changes. How can render the template on every step of the python function recursive call? Or how can I approach this problem? -
call_command not working, did everything like the tutorial
So just like the title suggest. i followed the instrcutions. this is the code. the command doesnt work not from the command line either. zero idea why import time from django.db import connections from django.db.utils import OperationalError from core.management.base import BaseCommand class Command(BaseCommand): """django command to pause execution is available""" def handle(self, *args, **options): self.std.write('waiting for database...') db_conn = None while not db_conn: try: db_conn = connections[default] except: self.std.out('Database unavailable, wait 1 sec') time.sleep(1) self.std.write(self.style.SUCCESS('Database available')) in the call is in a unit test just a line with command_call('wait_for_db') (the name of the file ofcourse) this is the test unit and this is the wait for db command thnkx yall -
How do I install GDAL on Centos 6?
I'm trying to install GeoDjango, it looks like I need PostGis. I got PostGis install fine on my mac, but I can't get it install on Centos 6. Following this here: https://gis.stackexchange.com/questions/211962/yum-install-postgis-on-centos-7 I get stuck on: yum install gdal-devel.x86_64 Here's what I get for errors --> Finished Dependency Resolution Error: Package: gpsbabel-1.5.0-3.el6.x86_64 (epel) Requires: libQtCore.so.4()(64bit) Error: Package: gdal-1.9.2-4.el6.x86_64 (elgis) Requires: libpoppler.so.5()(64bit) Error: Package: gdal-libs-1.9.2-4.el6.x86_64 (elgis) Requires: libpoppler.so.5()(64bit) Error: Package: gdal-java-1.9.2-4.el6.x86_64 (elgis) Requires: libpoppler.so.5()(64bit) You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest -
Getting a Page not found(404) which is raised by another view
Getting Page not found error that's is raised by another view Tried a lot searching what caused the error but no luck. Help, please! Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/customer/register/ Raised by: products.views.ProductDetailSlugView Not found! product views # Create your views here. class ProductListView(ListView): # queryset = Product.objects.all() template_name = 'products/product-list.html' def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) return context def get_queryset(self, *args, **kwargs): request = self.request return Product.objects.all() class ProductDetailSlugView(DetailView): queryset = Product.objects.all() template_name = 'products/product-detail.html' def get_context_data(self, *args, **kwargs): context = super(ProductDetailSlugView, self).get_context_data(*args, **kwargs) return context def get_object(self, *args, **kwargs): request = self.request slug = self.kwargs.get('slug') try: instance = Product.objects.get(slug=slug, active=True) except Product.DoesNotExist: raise Http404("Not found!") except Product.MultipleObjectsReturned: qs = Product.objects.filter(slug=slug, active=True) instance = qs.first() except: raise Http404("Umm....") return instance product urls urlpatterns = [ path('', ProductListView.as_view(),name='products-class'), url(r'(?P<slug>[\w-]+)/$', ProductDetailSlugView.as_view(),name='products-class-detail'), ] account urls urlpatterns = [ path('customer/register/', customer.register_page, name='customer-register'), ] base html #navbar part <li class="nav-item"> <a class="nav-link" href="/">Products</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'accounts:customer-register' %}">Signup</a> </li> register html {% extends 'base.html' %} {% block content %} <h1>Customer</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit"> </form> {% endblock %} -
Django form submission with search option
I am building a fairly long Django form (based on 2 models) collecting data from the user. All data have to be then submitted to the database so I’m using post. At some point in the mock-up form there is a possibility for the user to filter database data on the defined criteria, then based on those criteria, user should receive a result list, pick the desired value and move on with filling rest data finally submitting the form. I’m stuck with searching/filtering data on post. Neither django-filter or native Django search would work on post method and I cannot use get. My guess is there must be some really simple solution to circumvent that problem as such forms seem to be quite common. So, in a nutshell: How to combine a database search and a form submission under a post method using a one view only? Any hint, advice, suggestion much appreciated. -
Adding SSL to nginx in docker container on AWS returns connection refused
seeking some help with adding SSL using certbot on Ubuntu 18.04 + nginx. The issue is I get a ERR_CONNECTION_REFUSED error after adding SSL using certbot, I was able access my website (on port 80) before adding SSL. My Django app runs on port 3000 which has been exposed in my Dockerfile and passed in my nginx.conf file as well. docker-compose.yml db: image: postgres uwsgi: restart: always build: . nginx: restart: always image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./uwsgi_params.par:/etc/nginx/uwsgi_params.par:ro - /etc/ssl/certs:/etc/ssl/certs:ro - /etc/ssl/private:/etc/ssl/private:ro redis: restart: always image: redis:latest I have already copied the generated certificates to their respective directories as shown in volumes. nginx.conf server { listen *:80; server_name mydomain.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name mydomain.com; root html; client_max_body_size 8000M; client_body_buffer_size 8000M; ssl_certificate /etc/ssl/certs/chained.pem; ssl_certificate_key /etc/ssl/private/domain.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA; ssl_session_cache shared:SSL:50m; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_prefer_server_ciphers on; location /static { alias /var/www/static; } location ~ (\.php|.aspx|.asp|myadmin) { deny all; } location / { include /etc/nginx/uwsgi_params.par; uwsgi_pass uwsgi:3000; uwsgi_max_temp_file_size 10024m; } } I’ve also updated mydomain.com with my actual domain. -
Saving image after manipulation
I have 2 models. One called Choice and the other called ChoiceImage. class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to='some-path/') ChoiceImage img takes an ImageField. If the user uploads one image field, then that image is cut in half shown by this function: def slice_image(img): reader = misc.imread(img) height, width, _ = reader.shape with_cutoff = width // 2 s1 = reader[:, :with_cutoff] s2 = reader[:, with_cutoff:] misc.imsave(settings.MEDIA_ROOT + "/" + img.name, s1) return ContentFile(np.ascontiguousarray(s2)) The first image half gets resaved and the second image half gets saved for the second choice. Here's how the logic looks like: class CreateChoiceSerializer(serializers.ModelSerializer): choiceimage = ChoiceImageSerializer(many=False, required=False) class Meta: model = Choice fields = ('choice', 'choiceimage') def create(self, validated_data): image_uploaded = validated_data.get("choiceimage") if not image_uploaded["img"]: q = validated_data.get("question") if not q.choice_set.exists(): raise APIException("You must upload either an image or a cover.") else: img = q.choice_set.all()[0].choiceimage.img img2 = slice_image(img) validated_data["choiceimage"]["img"] = img2 image_validated_data = validated_data.pop('choiceimage') choice = Choice.objects.create(**validated_data) image_serializer = self.fields['choiceimage'] image_validated_data['choice'] = choice image_serializer.create(image_validated_data) It seems everything works fine. The first image gets cut in half and resaved in the media folder, however, the second image does not get saved and has the … -
Django get modelformset_factory input field ID's in html template
I am trying to get the input ids for my forms in an HTML template in order to write a javascript code to trigger the input field from as you click on a div. I am trying to print the id of every input field in the template however right now my code is not showing anything on the page: in my **template I currently have:** {% for form in formset %} {% for field in form.fields %} {{ field.auto_id }} {% endfor %} {% endfor %} And this is my view: @login_required def post_create(request): data = dict() ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4) if request.method == 'POST': form = PostForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() for f in formset: try: i = Images(posts=post, image=f.cleaned_data['image']) i.save() except Exception as e: break data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm formset = ImageFormset(queryset=Images.objects.none()) context = { 'form':form, 'formset':formset, } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) I was wondering if this is the best way to do this, however, is there any way to get the ID of the … -
NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/$']
I got this error using django 2.0.7. Here are my codes: urls.py: urlpatterns = [ url(r'^home/$', HomeView.as_view(), name='ACRMS-Home'), url(r'^cart/(?P<slug>[\w-]+)/$', carts_views.update_cart, name='update_cart'), url(r'^cart/$', carts_views.view, name="cart"), ] views.py in carts: def view(request): cart = Cart.objects.all()[0] context = {"cart": cart} template = "cart/view.html" return render(request, template, context) def update_cart(request, slug): cart = Cart.objects.all()[0] try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) return HttpResponseRedirect(reverse("cart")) template: <div> <h1>{{ product.name }} <a href='{% url "update_cart" product.slug %}' class ='pull-right'>Add to Cart</a></h1> </div> I am trying to add an item to the cart, but keep getting that error. I cannot tell why it is not able to find a reverse pattern, since I am very new to django. Please help. Thank you! -
Django: Serializer VS CustomUserManager
I was wondering, being new to Django and trying different practices, I was wondering whats the difference between using methods with a CustomUserManager and using the similar methods in the serializer. For exemple, I'm creating a User, and to correctly save the password I've put a method using user.set_password() When I'm only using the serializer it looks like this: from rest_framework import serializers from django.contrib.auth import get_user_model from ..models.model_user import * class UserIndexSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( username=validated_data['username'], password=validated_data['password'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'], is_a=validated_data['is_a'], is_o=validated_data['is_o'] ) user.set_password(validated_data['password']) user.save() return user class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' And when I'm using the CustomUserManager it looks like this: from django.db import models from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def … -
Python - ugly code, refactor code into something simpler and more readable
ugly code, refactor code into something simpler and more readable if a <= b and f <= g and c<=d and d<=f and b<=c: print('pass') else: print('fail') ugly code, refactor code into something simpler and more readable min_length = min(len(colours),len(fruits)) for i in range(min_length): print(colours[i],fruits[i]) ugly code, refactor code into something simpler and more readable for i in range(len(colours)): print(i,colours[i]) ugly code, refactor code into something simpler and more readable for i in range(len(colours)-1,-1,-1): print(colours[i]) -
Django/Python Stripe stripeToken doesn't seem to load/work properly
I am trying to charge a subscription on Stripe API in test-mode and my charge keeps getting declined. Everything seems to be working fine, except I cannot retrieve the "stripeToken" via POST. I tested this by printing the various variables I need and they all work fine... but when it comes to printing stripeToken, I get this error: MultiValueDictKeyError at /memberships/payment/ 'stripeToken' Request Method: POST Request URL: http://127.0.0.1:8000/memberships/payment/ Django Version: 2.2 Exception Type: MultiValueDictKeyError Exception Value: 'stripeToken' Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/datastructures.py in __getitem__, line 80 Python Executable: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 Python Version: 3.8.2 Python Path: ['/Users/fred/Documents/yonder/videoservice', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/fred/Library/Python/3.8/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages'] Server time: Wed, 1 Apr 2020 16:20:53 -0700 Here is my view code: def PaymentView(request): user_membership = get_user_membership(request) try: selected_membership = get_selected_membership(request) except: return redirect(reverse("memberships:select")) publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == "POST": token = request.POST['stripeToken'] try: token = request.POST['stripeToken'] customer = stripe.Customer.retrieve(user_membership.stripe_customer_id) customer.source = token # 4242424242424242 customer.save() subscription = stripe.Subscription.create( customer=user_membership.stripe_customer_id, items=[ { "plan": selected_membership.stripe_plan_id }, ] ) return redirect(reverse('memberships:update-transactions', kwargs={ 'subscription_id': subscription.id })) except: messages.info(request, "An error has occurred, investigate it in the console") context = { 'publishKey': publishKey, 'selected_membership': selected_membership } return render(request, "memberships/membership_payment.html", context) And here is my HTML code {% extends 'courses/base.html' %} {% load static %} … -
Model property displays default value for a field instead of actual value
I am a Django beginner and I started working on my first project. I implemented a model "extendedUser" with a medic_code field, extending User. It appears to be a problem when displaying the medic_code in a template. It doesn't display the actual property of the user, but the default value: "". Template {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }} </p> <p class="text-secondary">{{ user.medic_code }}</p> (empty string here) </div> </div> <!-- FORM HERE --> </div> {% endblock content %} models.py: from django.db import models from django.contrib.auth.models import User class extendedUser(User): medic_code = models.CharField(max_length=20, default='') users/forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from users.models import extendedUser class UserRegisterForm(UserCreationForm): email = forms.EmailField() medic_code = forms.CharField(max_length=20) class Meta: model = extendedUser fields = ['username', 'email', 'medic_code', 'password1', 'password2'] views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() #user.refresh_from_db() user.medic_code = form.cleaned_data.get('medic_code') user.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now … -
Grouping Form Fields using Django Crispy Forms
I'm trying to group fields in Django Model Form like this. But it doesn't work in Model Form. Is it possible to group? How do I do? class RegisterForm(forms.ModelForm): class Meta: model = People; exclude = ['isverified',] def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset('Group 1', Field('field1'), Field('field2')), Fieldset('Data 2', Field('field3')) -
How can we speed this up without modifying the body of the get_resource_identifier function?
How can we speed this up without modifying the body of the get_resource_identifier function -
Python websockets: cannot use AsyncToSync in the same thread as an async event loop
I am trying to write a multiplayer game using python websockets, The async server code is as below from websockets import WebSocketClientProtocol from asgiref.sync import async_to_sync class Player: def __init(self, websocket): self.websocket = websocket @async_to_sync async def send(self, msg): await self.websocket.send(msg) @async_to_sync async def receive(self): msg = await self.websocket.recv() return msg class Server: players = list() async def register(self, websocket): self.players.append(websocket) # register layers and if number of player greater than 2 start the game if len(self.players) >= 2: Game(self.players[:2]).start_game() self.players=self.players[2:] asyncio.get_event_loop().run_until_complete( websockets.serve(Server().ws_handler, 'localhost', 6191)) asyncio.get_event_loop().run_forever() The sync Game code is as below class Game: def __init__(self, players): self.players = players def start_game(self): self.players[0].send('hello') msg = self.players[0].receive() The issue is whenever I run the server code I get an error RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. Can someone point the issue in my code? -
how can use two types of queryset models override save method?
I have two types of queryset. one is featured=true second is featured=false. i want to ask you if i POST an article with featured=True then the old featured=true get transferred to featured=false queryset. i just want two [:2] values in featured=true queryset. here is the example there are two article in featured=true queryset which i want the second article automatically get updated to featured=false when i create new article. i also try this method that method get this output! models.py def save(self, *args, **kwargs): if self.featured == True: Article.objects.filter(pk__in=(Article.objects.filter(featured=True,).values_list('pk',flat=True)[:2])).update(featured=False) self.featured = True super(Article, self).save(*args, **kwargs) -
Django Postgres syntax error at or near "SEPARATOR"
I recently migrated from mysql to postgres, and now I'm trying to see the admin page for a model in my app. Django responds with ProgrammingError at /admin/app/model/ syntax error at or near "SEPARATOR" LINE 1: ..._CONCAT("app_model_relatedModel"."relatedModel_id" SEPARATOR ... Any clues as to why this is happening? I'm never directly executing sql in the app, it's all done through the ORM. -
Django Using multiple (two) user types extending AbstractUser
For our project, we have two user types: Donor and Hospital. So we use the User model, which extends the AbstractUser model. The Donor and Hospital models both have OneToOneField relationship with the User and it uses the default user authentication. Almost everything works fine. The Donor and Hospital creation works well, the instances are added to the database and we can log in. However, we need the Donor object and its fields in the view and in the template. We have the user contained in the request and the id of the user. donor = Donor.objects.get(pk=request.user.id) Or donor = Donor.objects.filter(donor=request.user).first() Should return the donor object, but it returns None. It works for Hospital. If we do Donor.objects.all() the newly created Donor is not in the list. However, created hospital is present in the list. We cannot figure out what is the problem, the ids for donor and user do not match. Thank you very much for your help! These are our models: class User(AbstractUser): is_donor = models.BooleanField(default=False) is_hospital = models.BooleanField(default=False) class Donor(models.Model): # username, pword, first+last name, email donor = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # donor_id = models.IntegerField(auto_created=True, unique=True, null=False, primary_key=True) nickname = models.CharField(max_length=40, unique=True) phone = models.CharField(max_length=10) address = …