Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: nginx + gunicorn: request.build_absolute_uri() function not accounting for the port
I have the following code running in production The Nginx config is as follows: # first we declare our upstream server, which is our Gunicorn application upstream hello_server { # docker will automatically resolve this to the correct address # because we use the same name as the service: "djangoapp" server webapp:8888; } # now we declare our main server server { listen 8558; server_name localhost; location / { # everything is passed to Gunicorn proxy_pass http://hello_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Nginx server has port forwarding: 8555:8558 And the gunicorn command running is gunicorn --bind :8888 basic_django.wsgi:application Now in my browser i open this url: http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email Now my code in one of my views is prev_url = request.META['HTTP_REFERER'] # EG: prev_url = http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email # we want to get the url from namespace . We use reverse. But this give relative url not the full url with domain login_form_email_url_reverse = reverse("login_register_password_namespace:user_login_via_otp_form_email") # EG: login_form_email_url_reverse = "/login_register_password/user_login_via_otp_form_email" # to get the full url we have to use do the below login_form_email_url_reverse_full = request.build_absolute_uri(login_form_email_url_reverse) # EG: login_form_email_url_reverse_full = "http://127.0.0.1/login_register_password/user_login_via_otp_form_email" I am execpting prev_url and login_form_email_url_reverse_full to be same but it differs prev_url domain is http://127.0.0.1:8555 whereas login_form_email_url_reverse_full … -
changing navbar icons to active with django-Javascript
I have made a navbar with bootstrap4 and I want to toggle the icon of current page to active. Currently, I am using <li class="nav-item"><a href="/" id="A" {% if request.path == "/" %} class="nav-link active" {% else %} class="nav-link" {% endif %}>Home</a></li> <li class="nav-item"><a href="/blog" id="B" {% if request.path == "/blog/" %} class="nav-link active" {% else %} class="nav-link" {% endif %}>Blog</a></li> what I would like is a simpler way with use of url names that could activate a script like this: {% if request.path == '/' %} <script> document.getElementById("#A").classList.add('active'); if ( document.getElementById("#A").classList.contains('active') ) document.getElementById("#A").classList.toggle('active'); </script> {% elif request.path == '/blog/' %} <script> document.getElementById("#B").classList.add('active'); if ( document.getElementById("#B").classList.contains('active') ) document.getElementById("#B").classList.toggle('active'); </script> {% endif %} Could there be an easier way? Please suggest to highlight the active page icon on navbar to toggle styles. Thank you -
i want to move to my index page from anywhere in the app but got struck in the detailed generic view in Django
i am new to django and covered all the nooks and corners of it but i was struck at internal URL routing. i am completely succeeded in transforming my existing application into Django everything works fine but the issue is whenever i click on the logo i want to go back to my index page but that is not happening the path /index.html is adding in the last of my existing path what may be the reason. here is my URL.py file path('',views.home,name='home'), path('index.html',views.home,name='home'), path('easy.html',views.Easy.as_view(),name='title'), path('medium.html',views.Medium.as_view(),name='medium'), path('hard.html',views.Hard.as_view(),name='hard'), path('contribute.html',views.contribute,name='contribute'), path('contact.html',views.contact,name='contact'), path('about.html',views.about,name='about'), path('problems',views.problems,name='problems'), path('action',views.action,name='action'), path('detail.html',views.detail,name='detail'), path('detail.html/<slug:pk>/',views.DetailView.as_view(),name='detail') i can get back to any location in my when when i was on the navbar and normal application but the only problem arises when i entered into a detailed view which is a generic view. http://127.0.0.1:8000/detail.html/2/ this is how i entered a generic view which will display all the fields of record with PK=2. it's working fine. but now i want to get back index file by clicking on my logo then the link changes as follows. http://127.0.0.1:8000/detail.html/2/index.html i know my url.py file cannot identify this hence raising the 404 error. how to get rid of this? please help. by the way ,the below code … -
Using subdomain to set variable and display localized version of Django apps/sites
I have installed Django-modeltranslation, which creates additional fields to translate into additional language from a base field. The default language shown is base on the LANGUAGE_CODE in settings.py For example: LANGUAGE_CODE = 'de' will show the German version of the site. I want to use subdomain to set the variable for LANGUAGE_CODE and display to users to the appropriate language version of the site. For example: de.site.com subdomain 'de' will set the LANGUAGE_CODE to 'de' and show the website in German. vs. www.site.com subdomain 'www' will set the LANGUAGE_CODE to 'en_us' and show the website in American English. How do you do this? Is there a better implementation to get to the same point? -
CSS button won't change color
I'm trying to edit a template I've downloaded on the internet, by changing some colors. However, when I change the color in the css file, it doesn't change it on the website: HTML: <div class="user-panel"> <a href="https://example.com" target="_blank">Link</a> </div> CSS: .user-panel { float: right; font-weight: 500; background: #ffb320; padding: 8px 28px; border-radius: 30px; } This is how I import the .css file: <link rel="stylesheet" href="{% static 'css/style.css' %}"/> So what I did was changing #ffb320 to #cc0000 to have red instead of yellow, saved the file, and reloaded the page, but the color didn't change. Same goes for font size, etc... The only thing that did work was using style='font-size:20px' for the font size. What am I doing wrong here? -
Best way to increase post view count
I need to implement a way to increase view count for my posts when the post is viewed on the client side. For now, I won't be handling removing duplicate views by refreshing. If PATCH or PUT is sent to the server with the viewcount + 1 on client side, viewcount will be overridden if multiple users use my service. Is creating a new endpoint only for increasing the view count the best practice? If so, what would be the correct URI staying RESTful? (POST /post/count ?) -
How do I solve the problem in I mean them
enter image description here CrispyError at /accounts/login/ |as_crispy_field got passed an invalid or inexistent field -
Authorize user by sessionid axios
I am creating my e-commerce app(django-oscar api) and I would like to pass sessionid in my requests to authorize user. Everytime when i refresh my page i get a new user with no products in basket instead of adding products to my actual basket. Even withCredentials dont help. const session = axios.create({ withCredentials: true }); useEffect(() => { const data = { url: "http://127.0.0.1:8000/api/products/2/", quantity: 1, } console.log(data) session.post('http://127.0.0.1:8000/api/basket/add-product/', data) .then(res=>{ console.log(res.data) }) .catch(err=>{ console.log(err) }) }, []); In Postman everything works fine and products are added to correct basket [ { "url": "http://127.0.0.1:8000/api/baskets/77/lines/26/", "product": "http://127.0.0.1:8000/api/products/2/", "quantity": 3, "attributes": [], "price_currency": "PLN", "price_excl_tax": "417.00", "price_incl_tax": "417.00", "price_incl_tax_excl_discounts": "417.00", "price_excl_tax_excl_discounts": "417.00", "is_tax_known": true, "warning": null, "basket": "http://127.0.0.1:8000/api/baskets/77/", "stockrecord": "http://127.0.0.1:8000/api/products/2/stockrecords/1/", "date_created": "2020-05-07T12:00:00.190733Z" } ] -
how to have database relationship with the active data. in django
i have some active and non active data's in EVENT models and active data has the VISITORS form to fill ..so far i have tried OnetoOne relationship but it didn't succeed ..i am getting both active and non active field in VISITORs model..thank you for your time. here is models.py class Event(models.Model): event_id = models.AutoField Event_Name = models.CharField(max_length=50) description = RichTextField() date_And_time = models.DateTimeField() location=models.CharField(max_length=50) slugs = models.SlugField(max_length= 200,default="") picture = models.ImageField(upload_to='wildlife/picture', default="") active = models.BooleanField(default=False) class Meta: ordering = ["date_And_time"] def __str__(self): return self.Event_Name class Eventvisitor(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, related_name="eventvistor",default="") name = models.CharField(max_length=50) email = models.CharField(max_length=70, default="") phone = models.CharField(max_length=20,default="") date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date'] def __str__(self): return self.email -
Django manager in lookup fields
I have a SoftDeletableModel named Offer: class Offer(SoftDeletableModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='offers') order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='offers') price = models.PositiveIntegerField() I am using below query to get all Orders that current user has an offer in it. Order.objects.filter(offers__user=request.user) but it counts deleted offers in lookup query. for example, if a user delete his offer from an order, this query returns that order too. an other example is something like this: Order.objects.filter(offers=48). offer 48 is removed but i get result from this query too. does django use default manger for lookup fields? -
How to disable "HTML" tab in DRF Browsable API but keep "Raw" tab available
When using more complicated representation schemas (e.g. nested objects and lists), the "HTML" form part of the Browsable API in Django REST Framework becomes mostly unusable. How can I disable it while still keeping the rest of the Browsable API available, including the ability to POST/PUT/PATCH data using the other "Raw" tab? -
how to pass a QuerySet instance to serializer?
I'm using raw sql (using orm is working) for fetching products and i'm getting this error Got AttributeError when attempting to get a value for field `name` on serializer `ProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `tuple` instance. Original exception text was: 'tuple' object has no attribute 'name'. This is the get function: def get(self, request, store_id, format=None): with connection.cursor() as cursor: user = request.user check_auth = get_object_or_404( Store, id=store_id, owner_id=user.id) if check_auth != None: connection.cursor() cursor.execute('SELECT * FROM products') products = cursor.fetchall() serializer = ProductSerializer(products, many=True) return Response(serializer.data) raise Http404 and here's the serializer class: class ProductSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) category = CategorySerializer() class Meta: model = Product fields = ['id', 'store_id', 'name', 'summary', 'description', 'category', 'main_image', 'price', 'offer_price', 'cost', 'available_quantity'] -
Google Cloud PubSub - How to send multiple arguments to the Cloud Function
I have been using Google Cloud PubSub to trigger Google Cloud Functions. Until this point I have been using a single argument "uuid", now I need to send also development/production flag. Here below is the publisher in Google App Engine/Django: publisher = pubsub_v1.PublisherClient() topic_name = 'projects/project/topics/cloudfunction_topic' message_to_publish = video.uuid publisher.publish(topic_name, data=message_to_publish.encode('utf-8'), spam='') Here below is the subscriber section in GCF: if os.getenv('GCF', None): uuid = base64.b64decode(event['data']).decode('utf-8') How should I change this so there can be multiple arguments (video.uuid, production/development) in the message ? -
Django url pattern data
If inside of urls.py I had a url pattern that depended on input sent to it from a template, what data would be sent to the url, and what data to the view? For example, urls.py:path('post/<int:post_id>/<str:post_title>', views.view_post, name='view_post'), blogposts.html template: <a href="{% url 'blogs:view_post' post.id post.title%}">Read More</a> views.py: def view_post(request, post_id, post_title):. What if I wanted only the post id to be sent to the view, but for the url to look the same? -
I am creating a project in Pycharm, I am working on django, whenever I am installing OpenCv and trying to use it I am getting following error
Traceback (most recent call last): File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy__init__.py", line 142, in from . import core File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core__init__.py", line 24, in from . import multiarray File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\multiarray.py", line 14, in from . import overrides File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\overrides.py", line 16, in add_docstring( RuntimeError: implement_array_function method already has a docstring Traceback (most recent call last): File "C:/Users/Dell/Desktop/pp/test2/templates/ex.py", line 1, in import cv2 File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\cv2__init__.py", line 5, in from .cv2 import * ImportError: numpy.core.multiarray failed to import -
How to store multiple values on a django model field
I have a model where I store the recurring sessions on my gym. DAYS_OF_WEEK = ( (0, _("Monday")), (1, _("Tuesday")), (2, _("Wednesday")), (3, _("Thursday")), (4, _("Friday")), (5, _("Saturday")), (6, _("Sunday")), ) class RecurringSession(models.Model): session = models.ForeignKey(SessionType, db_index=True, on_delete=models.CASCADE) dayofweek = models.PositiveSmallIntegerField(choices=DAYS_OF_WEEK) time = models.TimeField() However some classes happen more than once a week. Whats the best way to store multiple values (between 1 to 7) on that modelfield? I'm using Django Mysql 8.0, and from what I understand it supports JSON field but from the django docs it seems that is only supported by Postgres so far. I was inclined to So I'm inclined to change the dayofweek model field to a JsonModel Is there a specific django way to do this? Maybe storing a charfield with comma-separated values? I wont need to search by that field. Using Django 3.0.6, Python 3.8.2, and MySQL 8.0.20. thanks -
How to make Django Admin TabularInline sortable by custom field?
In Django Admin, it's easy to create a custom field on the model list page, e.g.: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('id', 'field1', 'field2', 'custom_field3') def custom_field3(self, obj): return obj.get_custom_field3_display() custom_field3.short_description = 'Custom Field 3' custom_field3.admin_order_field = 'field3' # makes column header sortable MyModel.field3 will be used to sort the now clickable "Custom Field 3" column header on the model list page. How can I achieve the same on an inline model? I can easily define a custom field in the same way, but the admin_order_field line doesn't achieve the same result: class MyModelInline(admin.TabularInline): model = MyModel fields = ('id', 'field1', 'field2', 'custom_field3') def custom_field3(self, obj): return obj.get_custom_field3_display() custom_field3.short_description = 'Custom Field 3' custom_field3.admin_order_field = 'field3' # doesn't seem to have any effect -
filter by count of reverse lookup
I have two models, for example, class Student(models.Model): name = models.CharField(max_length=160) teams = models.ManyToManyField("Team", related_name="student", blank=True) class Team(models.Model): name = models.CharField(max_length=160) I want to retrieve all the teams which is not assigned to any student , ie all teams where students.count() is 0. How can i query this? I have tried Team.objects.filter(student=None) -
How to save user input data from multiple forms (in a single template/web page) to the sqlite database in django?
I have multiple ModelForms to be displayed in a single web page with one submit button and i want all the user input data to be stored in the db. forms.save() doesn't seem to be working if there are more than 1 forms. How do i write views for this? -
Javascript: Map Container is already initialized in django-leaflet
While trying to load geojson of point data from database in django-leaflet and djeojson i get an error. Uncaught Error: Map container is already initialized. I have used another script in base.html to initialize the map, I understand , but how do I solve it so that I can render the points from database to the template? base.html: <script type="text/javascript"> function map_init_basic (map, options) { L.marker([8.9806,38.7578]).addTo(map); } </script> index.html: <body> <h1>Django-Leaflet</h1> {% leaflet_map "map" callback="main_map_init" %} <script type="text/javascript"> function main_map_init (map, options) { var dataurl = '{% url "rent_app:data" %}'; // Download GeoJSON via Ajax $.getJSON(dataurl, function (data) { // Add GeoJSON layer L.geoJson(data).addTo(map); }); } </script> </body> -
Authentication without a passwrod Django
As the title states I'm trying to authenticate a user without a password. I've already used this: django authentication without a password to solve my problem with on of my apps (on Django 2.0), but I want to do the same thing in another app but It's on Django 2.1. When I do the same implementation my custom authenticate fuction is never called. Thus it doesn't work. Current setup in auth_backend.py: from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class PasswordlessAuthBackend(ModelBackend): """Log in to Django without providing a password. """ def authenticate(self, username=None): try: return User.objects.get(username=username) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None setup in settings.py: AUTHENTICATION_BACKENDS = [ # auth_backend.py implementing Class YourAuth inside yourapp folder 'yourapp.auth_backend.YourAuth', # Default authentication of Django 'django.contrib.auth.backends.ModelBackend', ] but when I try in my views user = authenticate(username=user.username) It never hits my custom authentication method. Any and all help is appreciated! -
I have a bug in Django
======================= File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax created a project launched it and gives such an error what is the problem? -
how do I change default font of Summernote in Django?
So I'm using django-summernote (I'm using Django ver 3.x), and trying to change the default font in the editor. Here's my code. (part of) forms.py: from .models import MyModel class MyInputForm(forms.ModelForm): contents = SummernoteTextFormField() class Meta: model=MyModel fields=['contents'] widgets = { 'contents': SummernoteInplaceWidget() } (part of) my template : <form method="post" class="form-group"> {% csrf_token %} <div class="row"> <div class="col col-8"> {{form.contents|as_crispy_field}} </div> </div> </form> And in case you need to take a look, (part of) my settings.py SUMMERNOTE_CONFIG = { 'iframe': True, 'lang' : 'ko-KR', 'summernote': { 'width': '100%', 'height': '400px', 'toolbar': [ ['style', ['style',]], ['font', ['fontname', 'fontsize', 'bold', 'italic', 'strikethrough', 'clear',]], ['color', ['forecolor', 'backcolor', ]], ['para', ['ul', 'ol', 'height']], ['insert', ['link']], ['misc', ['picture', 'fullscreen', 'codeview', 'print', 'help', ]], ], }, 'js': ( '/static/summernote-ext-print.js', ), 'js_for_inplace': ( '/static/summernote-ext-print.js', ), 'css': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', ), 'css_for_inplace': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', ), 'codemirror': { 'theme': 'base16-dark', 'mode': 'htmlmixed', 'lineNumbers': 'true', }, 'lazy': False, } SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' I have no idea on how or where to write my code for changing the default font. I would really appreciate your help. Thanks. :) -
TemplateDoesNotExist Heroku issue
I know there is already a lot of posts dealing with this problem however i don't find any solution.. I developped a Django website in local and know i would like to host it thanks to Heroku. I configured everything but when I launch the website i get this error : "TemplateDoesNotExist at /index.html" There is my configuration : my settings files my prod_settingsFiles my variable BASEDIR And finally : The organisation of my project -
Adding Items to cart Bug
I'm facing a problem with the code, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Red and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Large), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? Can anyone please help me out? Thanks in advance! My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) item_variations = models.ManyToManyField(ItemVariation) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20) ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add= True) ordered_date = models.DateTimeField() My views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) variations = request.POST.getlist('variations', []) print(variations) print(request.POST) minimum_variation_count = …