Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle 302 in django 2.2?
I have 3 or more items in my order summary page. When I remove one of the items, my code redirects me to the same order summary page. But when I am trying to remove last order from the order summary page, my code redirects me to the home page. I want to stay on the same page while the cart is empty with continue shopping button but when I removed the last item from the cart it redirects me back to home page views.py def remove_from_cart(request, slug): course = get_object_or_404(Course, slug=slug) cart_qs = Cart.objects.filter(item=course, user=request.user) if cart_qs.exists(): # cart = cart_qs[0] # if cart.quantity > 1: # cart.quantity -= 1 # cart.save() # else: cart_qs.delete() order_qs = Order.objects.filter( user=request.user, ordered=False ) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.orderitems.filter(item__slug=course.slug).exists(): order_item = Cart.objects.filter( course=course, user=request.user, )[0] order.orderitems.remove(order_item) messages.info(request, "This item was removed from your cart.") return redirect("cart:order-summary") else: messages.info(request, "This item was not in your cart") return redirect("cart:order-summary") else: messages.info(request, "You do not have an active order") return redirect("cart:order-summary") order-summary.html <tbody> {% if carts %} {% for cart in carts %} <tr> <td> <p>{{ cart.item }}</p> </td> <td> <p>Rs. {{ cart.price … -
How can I define logic to filter state in admin.py
I have registered my model to django admin here is my models.py class Applications(models.Model): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) email_id = models.EmailField() class Country(models.Model): name = models.CharField(max_length=250) phone_code = models.CharField(max_length=250) currency = models.CharField(max_length=250) def __str__(self): return self.name class State(models.Model): name = models.CharField(max_length=250) country = models.ForeignKey(to=Country, on_delete=models.CASCADE) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Applications, Country, State class eAdmin(admin.ModelAdmin): list_display = ('name', 'phone_number', 'email_id', 'country', 'state') list_filter = ('funnel', 'country', 'state') search_fields = ['email_id'] fields = ('country', 'state') admin.site.register(Applications, eAdmin) How can I define logic to filter state when user select Country I know how to use Ajax to filter but for Admin site What logic should I follow to filter state in eAdmin class -
Django: Making additional REST call inside View when handling user's form
What do I have: One Django form with a set of fields users can populate and send. When I handle form fields into View Class one additional Http request should be executed (to external Rest service) to check the user's address and add coordinates. So in plain Python this may be done with import requests requests.get() How this case should be implemented in Django? -
Django : 'tag' is not a registered tag library error
I'm having this error when loading a custom tag in my template. I've visited many topics about this and I made sure to verify that I didn't commit some common errors : The file containing the tags is in the templatetags folder. This templatetags folder contains a __init__.py file. The app actualites is in the INSTALLED_APPS list from the settings. I'm using {% load mes_tags %} at the beginning of my template. Here is the file structure of my app : actualites/ __init__.py SOME FILES templatetags/ __init__.py mes_tags.py mes_tags.py from django import template register = template.Library() @register.simple_tag(takes_context=True) def param_replace(context, **kwargs): d = context['request'].GET.copy() for k, v in kwargs.items(): d[k] = v for k in [k for k, v in d.items() if not v]: del d[k] return d.urlencode() The error I get is the following : TemplateSyntaxError at / 'mes_tags' is not a registered tag library. Must be one of: LIST OF TAGS Can someone tell me what I did wrong ? Thanks in advance ! -
Django+Wordpress+Nginx reverse proxy apache
I have 2 machines one is django (https://orgofoods.com) and another one is wordpress (https://blog.orgofoods.com). Django is running with nginx, gunicorn and the configuration goes like this upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name orgofoods.com; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location /blog { proxy_pass https://blog.orgofoods.com; } location /blog/wp-content { proxy_pass https://blog.orgofoods.com/wp-content; } location /blog/wp-includes { proxy_pass https://blog.orgofoods.com/wp-includes; } location /blog/wp-login.php { proxy_pass https://blog.orgofoods.com/wp-login.php; } location /blog/wp-admin { proxy_pass https://blog.orgofoods.com/wp-admin; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/orgofoods.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/orgofoods.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = orgofoods.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 default_server; listen [::]:80 … -
How to use autocomplete and autopopulate in detail view using ajax for search?
I unable use ajax or jquery to autocomplete and autopopulate in detail view using ajax for search because I am newbie to cbv in django views.py class QuestionListView(ListView): model = Question context_object_name = "question_list" template_name = "collab_app/question_list.html" paginate_by = 2 def get_context_data(self, **kwargs): context = super(QuestionListView, self).get_context_data(**kwargs) if self.request.GET.get("q") != None: query = self.request.GET.get("q") list_exam = Question.objects.filter( Q(question_title__icontains=query) # | Q(author__icontains=query) ) else: list_exam = Question.objects.all() paginator = Paginator(list_exam, self.paginate_by) page = self.request.GET.get("page") try: file_exams = paginator.page(page) except PageNotAnInteger: file_exams = paginator.page(1) except EmptyPage: file_exams = paginator.page(paginator.num_pages) context["list_exams"] = file_exams if self.request.GET.get("q") != None: context["search"] = self.request.GET.get("q") return context form.html <form class="form-inline mt-2 mt-md-0" action="{% url 'collab_app:question-list' %}" method="get"> <input name="q" class="form-control mr-sm-2" id="txtSearch" value="{{ search }}" type="text" placeholder="Search" aria-label="Search"> </form> -
Google Maps Data retrieval
i wanted to ask about the restrictions on data provided by google! I am building a webapp where the data of the user from google is to be retrieved and visualised on the website after users logs in through google. My questions are Is it feasable? How much time does google take to send the users data? Which library is best to help me in this situation! i am using django. I have used python-social-auth already. Thanks! -
Django Project with database settings configured through environment variables - migrations work but when I run server it uses empty database
I've configured on Ubuntu using virtual enviroment. I configured my database settings using settings.py file and specifying environment variables there (os.environ['DATABASE_NAME'] and so on). Interestingly I can now work with migrations using manage.py migrate commands and projects gets deployed on AWS Elastic Beanstalk with these settings and work there (I defined variables with the same values on that side), my problem now is the following: - If I run server locally using manage.py it starts without any errors but looks like it works with empty database and I'm not sure how I check which one - but no data I've added on the live one running on AWS - At the same time if I deploy using eb deploy I see that all works fine and my migrations applied and data is available I just don't understand which database is being used when I run my Django server locally - settings.py only contains variables defining connection to RDS instance and SQLite file deleted. -
Html Parsing from nested <ul> and <li> to a list in Django
I've a string which contains below html code. <ul> <li>Menu 1 <ul><li>Sub Menu - 1</li> <li>Sub Menu - 1</li> </ul> </li> <li>Menu 2</li> <li>Menu 3 <ul><li>Sub-Menu -1</li></ul> </li> </ul> It gives me output like below. This is the screenshot for my current structure So I want a Django function which gives me this string in a list or dictionary format using which i can loop through because I'm creating a completely dynamic Left navigation. -
Reverse Joining in Dajngo
How to reverse joining performed in django class ModelA(models.Model): pass class ModelB(models.Model): a = ForeignKey(ModelA) ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship but its not giving me ModelB Data -
login page creation. SyntaxError: invalid syntax
File "/Users/macmini/DjangoLogin/myloginprojectaa/myloginprojectaa/settings.py", line 55 'DIRS':[os.path.join(BASE_DIR,'templates')], ^ SyntaxError: invalid syntax -
AttributeError at /cart/product-1 'QuerySet' object has no attribute 'items'
I am getting the above error trying to add a selected item to a cart and remove it if its already in cart. Below is my code. Any idea what am missing, thanks. Cart Model: class Cart(models.Model): items = models.ManyToManyField(Item, null=True, blank=True) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return "Card Id: %s" %(self.id) item model: class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) sale_price = models.FloatField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) slug = models.SlugField(unique=True) active = models.BooleanField(default=True) def __unicode__(self): return self.title The View: def UpdateCart(request, slug): cart = Cart.objects.all() try: item = Item.objects.get(slug=slug) except Item.DoesNotExist: pass except: pass if not item in cart.items.all(): cart.items.add(item) else: cart.items.remove(item) return HttpResponseRedirect(reverse("cart")) -
Why is Django adding "/accounts/logout/" to all {% url %} template tag lookups?
I have a very simple POC template, in Django, contains this; <form action="{% url 'formtest' %}" method="post"> {% csrf_token %} {% url 'formtest' %} <input type="submit" value="Vote"> </form> When I render it, the URL template tags makes my target this; /accounts/logout/formtest That isn't right, it should be just '/formtest'. And I can't figure out why it's prepending that /accounts/logout bit. The user is not logged in. And my url.py looks like this; urlpatterns = [ path('', views.index, name='index'), path('create_user/<str:username>', views.create_user, name='create_user'), path('monitor', views.monitor, name='monitor'), path('upload', views.upload_file, name='upload'), path('formtest', views.formtest, name='formtest'), ] My Django version is 2.2.5 and I've tried witling down the example to the almost bare minimum. But I can't find why that template tag is adding that bit. I am almost positive something weird or strange has been done by myself, but I failed to find what and where. -
The current path, didn't match any of these
So I have code below that is in django 1.8 from django.conf.urls import patterns, url from account import views from django.contrib.auth import views as auth_views urlpatterns = patterns('', url(r'^$', views.index, name='profile'), url(r'^api/get_users/(?P<term>.*)', views.get_users), url(r'^leaderboard/(?P<board_type>.*)', views.leaderboard), url(r'^admintools/(?P<action>.*)', views.admintools), ) I modified it to django 2.2 from django.conf.urls import url from . import views from django.urls import re_path,path from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.index, name='profile'), path('api/get_users/(?P<term>.*)', views.get_users), path('leaderboard/(?P<board_type>.*)', views.leaderboard), path('admintools/(?P<action>.*)', views.admintools), ] I get the error The current path account/admintools, didn't match any of these -
Posting the message to the user using django_private_chat integrated in django project?
I am newbie to django and I am working on the django application where user to admin and admin to user messaging is important for that I had integrated the django_private_chat application in my application so I had did all the points that are included in the django_private_chat documentation And I got a front end showing all the users and the message text box and send button but the problem on send the message is not going to the user I am including my html files My dialog.html: {% extends "django_private_chat/base.html" %} {% load static %} {% load i18n %} {% block css %} {{ block.super }} <link href="{% static "django_private_chat/css/django_private_chat.css" %}" rel="stylesheet" type="text/css" media="all"> {% endblock css %} {% block content %} <input id="owner_username" type="hidden" value="{{ request.user.username }}"> <div class="container"> <div class="col-md-3"> <div class="user-list-div"> <ul> {% for dialog in object_list %} <li> {% if dialog.owner == request.user %} {% with dialog.opponent.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a> {% endwith %} {% else %} {% with dialog.owner.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} … -
Django: NOT NULL constraint failed: crf_heu.date_id
I have a very simple models but fail to resolve an error linked to constraint I have 2 models: Jours and Heures linked with a OneToMany relationship (one Jours instance can have multiples Heures instances) I have a form to add records in Heures but have an error I did not understand: NOT NULL constraint failed: crf_heu.date_id models.py class Jours(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE jou_ide = models.AutoField(primary_key=True) jou_dat = models.DateField("Date du pointage", null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'crf_jou' verbose_name_plural = 'Dates' ordering = ['jou_ide'] def __str__(self): return f"{self.jou_dat}" class Heures(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE heu_ide = models.AutoField(primary_key=True) date = models.ForeignKey(Jours, on_delete = models.CASCADE) heu_dat = models.TimeField("Heure du pointage", null=True, blank=True,auto_now_add=True) heu_cod = models.IntegerField("Code employé", null=True, blank=True) heu_com = models.CharField("Commentaires", max_length = 150, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'crf_heu' verbose_name_plural = 'Heures' ordering = ['heu_ide'] def __str__(self): return f"{self.heu_dat}" views.py @login_required def index(request): if request.method == "POST": form = HeuresForm(request, data=request.POST or None) if form.is_valid(): heu_cod = form.cleaned_data['heu_cod'], heu_com = form.cleaned_data['heu_com'], date_id = Jours.objects.get(jou_dat = datetime.date.today()).jou_dat form.save() return redirect('home') else: form = HeuresForm(request) return render(request, 'pointage/index.html', {'form': form}) forms.py class HeuresForm(forms.ModelForm): # surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions # https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data … -
Heroku gunicorn deploy error: NoModuleNameError
possibly a little out my depth here, I've read the heroku docs thoroughly and still don't quite understand how the Procfile should be set up. Trying to deploy heroku ($ heroku open), gives this error log: 2020-01-27T11:39:57.597570+00:00 app[web.1]: backlog: 2048 2020-01-27T11:39:57.597572+00:00 app[web.1]: workers: 1 2020-01-27T11:39:57.597590+00:00 app[web.1]: worker_class: sync 2020-01-27T11:39:57.597592+00:00 app[web.1]: threads: 1 2020-01-27T11:39:57.597594+00:00 app[web.1]: worker_connections: 1000 2020-01-27T11:39:57.597596+00:00 app[web.1]: max_requests: 0 2020-01-27T11:39:57.597598+00:00 app[web.1]: max_requests_jitter: 0 2020-01-27T11:39:57.597600+00:00 app[web.1]: timeout: 30 2020-01-27T11:39:57.597602+00:00 app[web.1]: graceful_timeout: 30 2020-01-27T11:39:57.597604+00:00 app[web.1]: keepalive: 2 2020-01-27T11:39:57.597606+00:00 app[web.1]: limit_request_line: 4094 2020-01-27T11:39:57.597608+00:00 app[web.1]: limit_request_fields: 100 2020-01-27T11:39:57.597610+00:00 app[web.1]: limit_request_field_size: 8190 2020-01-27T11:39:57.597612+00:00 app[web.1]: reload: False 2020-01-27T11:39:57.597614+00:00 app[web.1]: reload_engine: auto 2020-01-27T11:39:57.597615+00:00 app[web.1]: spew: False 2020-01-27T11:39:57.597617+00:00 app[web.1]: check_config: False 2020-01-27T11:39:57.597619+00:00 app[web.1]: preload_app: True 2020-01-27T11:39:57.597621+00:00 app[web.1]: sendfile: None 2020-01-27T11:39:57.597623+00:00 app[web.1]: chdir: /app 2020-01-27T11:39:57.597625+00:00 app[web.1]: daemon: False 2020-01-27T11:39:57.597627+00:00 app[web.1]: raw_env: [] 2020-01-27T11:39:57.597629+00:00 app[web.1]: pidfile: None 2020-01-27T11:39:57.597630+00:00 app[web.1]: worker_tmp_dir: None 2020-01-27T11:39:57.597632+00:00 app[web.1]: user: 52893 2020-01-27T11:39:57.597634+00:00 app[web.1]: group: 52893 2020-01-27T11:39:57.597636+00:00 app[web.1]: umask: 0 2020-01-27T11:39:57.597638+00:00 app[web.1]: initgroups: False 2020-01-27T11:39:57.597640+00:00 app[web.1]: tmp_upload_dir: None 2020-01-27T11:39:57.597642+00:00 app[web.1]: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} 2020-01-27T11:39:57.597645+00:00 app[web.1]: forwarded_allow_ips: ['*'] 2020-01-27T11:39:57.597646+00:00 app[web.1]: accesslog: - 2020-01-27T11:39:57.597648+00:00 app[web.1]: access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" 2020-01-27T11:39:57.597650+00:00 app[web.1]: errorlog: - 2020-01-27T11:39:57.597652+00:00 app[web.1]: loglevel: debug 2020-01-27T11:39:57.597654+00:00 app[web.1]: capture_output: False 2020-01-27T11:39:57.597656+00:00 app[web.1]: logger_class: gunicorn.glogging.Logger 2020-01-27T11:39:57.597658+00:00 app[web.1]: logconfig: … -
How to send initial request.meta variable to another view function in django
I developed an django application and now integrated with sso login. Application is deployed on the apache 2.4. my Service provider return few attributes such as email and uid now i want to use these attributes in whole application. but problem is that when end user access one url say ("/abc/default.html") this url shows a dashboard and request.meta contains all these attributes. now if he/she wants to switch to another tab lets usermaual new view and url triggered but in this view request.meta does not have those variable(email , uid). basically when i render or redirect my initial request.META variable gets updated. how to propagate these variable to another view/url using render or redirect. -
Lat and Lon show on leaflet Django
I want to show lat and lon from DB to leaflet map. how could I do it, please help me. model is here. class Pharmacy(models.Model): name = models.CharField(max_length = 256) contact = models.CharField(max_length = 15) city = models.CharField(max_length = 20) address = models.TextField() lat = models.FloatField() long = models.FloatField() def __str__(self): return self.name I'm working with class base generic view. -
Prettier vscode extension not support Django template tags {% tag %}
Prettier visual studio code extension not support Django template tags {% tag %} now How can I fix this? Do I have to disable Prettier extension for html files or is there another solution؟؟ issues 5581 in github = No Django template tags support -
Tag concatenation for displaying dictionaries dynamically
I Have a dictionary (dict_) returned from my view. inside the template i want to access specific keys. How can i do that? {% for a in applications %} {{ dict_.a.id}} {% endfor %} from view: context = { 'applications': applications, 'dict_': count_dict } return render(request, 'applications/map.html', context) Do i need to concat it? E.g. {{ dict_ }} + {{ a.id }} -
query to fetch x questions which have some tag y
I have 2 models: class Question(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) def __str__(self): return self.name class Tag(models.Model): Tag_id = models.IntegerField() ques_id = models.ForeignKey(Question, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name what will be query to get the 10 ques ids for the input tag ids? Output format should be: { "id": 1, "name": "QUES 1", "tags": [{ "id": 1, "name": "Abcd" }] } -
Crispyforms throws validation error before submitting or filling out forms
I am using crispyforms to customise my forms in django. However, it gives me the validation error "this field is required" before I have written or submitted anything into the field. It should only me an error when submitting without filling the fields out. How can get the validation error to show only after submit if forms are not filled out? Thanks for reading HTML file <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group"> {{ form.name|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group"> {{ form.interest_rating|as_crispy_field }} </div> </div> {{ form.interest|as_crispy_field }} <div class="form-row"> <div class="form-group"> {{ form.clarity_rating|as_crispy_field }} </div> <div class="form-group"> {{ form.clarity|as_crispy_field }} </div> <div class="form-group "> {{ form.brevity_rating|as_crispy_field }} </div> <div class="form-group"> {{ form.brevity|as_crispy_field }} </div> <div class="form-group "> {{ form.not_good|as_crispy_field }} </div> <div class="form-group "> {{ form.general_comments|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Sign in</button> </form> <br/> <br/> </div> </div> </div> My forms.py from django import forms from .models import Review class ReviewForm(forms.ModelForm): name = forms.CharField(widget=forms.Textarea) interest_rating = forms.ChoiceField( choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]) interest = forms.CharField(widget=forms.Textarea) clarity_rating = forms.ChoiceField( choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]) clarity = forms.CharField(widget=forms.Textarea) brevity_rating = forms.ChoiceField( choices=[(1, 1), (2, 2), (3, … -
Cache update in a many 2 many relation
I'm using a combination of Django, GraphQL (graphene-django), VueJS and Apollo Client for my project. Everything is working fine until I tried to manage many2many relations. Usually when I make an update mutation to an object that is already in the cache, it is detected and the data that is displayed is updated. The problem is that in my new case, I'm updating the many2many relation between my two objects and it doesn't update, while it is correctly done in database (and even in cache, when I print it in the console, which is weird). Typically, I'm trying to add/remove users in/from a group. Maybe I've been watching my code for a too long period and I can't see something obvious.. Anyway here is my code : My Django models : class Group(models.Model): def _get_users_count(self): return self.user_ids.count() name = models.CharField(max_length=255) user_ids = models.ManyToManyField(User, related_name="group_ids", db_table="base_group_user") users_count = property(fget=_get_users_count, doc="type: Integer") def __str__(self): return self.name class User(AbstractUser): def _get_full_name(self): return "%s %s" % (self.first_name, self.last_name.upper()) full_name = property(fget=_get_full_name, doc="type: String") def __str__(self): return self.full_name def _has_group(self, group_name): return self.group_ids.filter(name=group_name).exists() My schemas : class GroupType(DjangoObjectType): class Meta: model = Group fields = ('id', 'name', 'user_ids',) users_count = graphene.Int() class UserType(DjangoObjectType): class Meta: … -
Id serialization does not update when I create objects using shell in Django PostgreSQL
I have a module called shell_functions where I have the following function: def add_areas(): for data in some_data: Area.objects.create(id=data['id'], name=data['name']) I run this function from the shell to create objects. After this, I tried creating an Area from the admin panel. However, this time I get an integrity error saying the Area with the id=1 already exists. Obviously, the id serialization counter did not update itself as I explicitly put in the id in the shell function. How to solve this issue? Thanks for any help!