Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
One difference between node.js that use javascript server side and Django that use Python sever side
Django with python server side can pass just string to javascript client side ! if i start using node.js(javascript anywere) server side , can i pass other type of variables to javascript es. integer, boolean ecc... ? or to use node.js pass the same type of variables as python language ? -
Cannot assign "...'": "..." must be a "User" instance
models.py for assistance class AssistanceQuest (models.Model): Customer = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=False) Status = models.BooleanField(default=False,null=False,blank=False) Date_request = models.DateTimeField(auto_now_add=False) Tipology = models.CharField(max_length=50, null= False) Request = models.TextField(max_length= 1000, blank=False, null=False) models.py for Custom User from django.contrib.auth.models import AbstractUser from .managers import CustomUserManager class User (AbstractUser): is_superuser = None is_staff = None groups = None user_permissions = None objects = CustomUserManager() manager.py for Custom User from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager senza staff o permessi """ def create_user(self, username,email,first_name,last_name,password): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(username = username, email = email, first_name = first_name, last_name = last_name) user.set_password(password) user.save() return user and this is the view.py for the assistances if User.is_authenticated: Message = "Assistance Request From " + str(User.get_full_name(User)) + ": "+ str(User.email) else: Message = "Assistance Request From " + request.POST['message-name-surname']+"\n Email: "+ request.POST['message-email'] Message += "\n City: "+ request.POST['message-city']+"\n Province: "+ request.POST['message-province']+"\n Landline Or Mobile Phone: "+ request.POST['message-phone']+"\n Number Order Or Purchase Period: "+ request.POST['message-number-order']+"\n Product Under Warranty: "+ request.POST['message-warranty']+"\n Request: "+ request.POST['message']+"\n Prefers To Be Contacted: "+ request.POST['message-pref-contact'] if User.is_authenticated: user= settings.AUTH_USER_MODEL Assistance = AssistanceQuest(Customer=user, Status= 'False',Request= Message, Tipology='Tecnica',Date_request=datetime.datetime.now()) Assistance.save() Subject = "Assistance … -
django admin site nav sidebar messed up
I recently added a package to my project and did a pip freeze > requirements.txt afterwards. I then did pip install -r requirements.txt to my local and it added a sidebar. I did a pip install -r requirements.txt to the server as well and it produced a different result. It's sidebar was messed up. I tried removing the sidebar by doing this answer but it did not get removed. .toggle-nav-sidebar { z-index: 20; left: 0; display: flex; align-items: center; justify-content: center; flex: 0 0 23px; width: 23px; border: 0; border-right: 1px solid var(--hairline-color); background-color: var(--body-bg); cursor: pointer; font-size: 20px; color: var(--link-fg); padding: 0; display: none; /*added*/ } #nav-sidebar { z-index: 15; flex: 0 0 275px; left: -276px; margin-left: -276px; border-top: 1px solid transparent; border-right: 1px solid var(--hairline-color); background-color: var(--body-bg); overflow: auto; display: none; /*added*/ } What should I do to remove this? -
Reverse for '' not found. '' is not a valid view function or pattern name ERROR that i cannot see
Django 3 error - Reverse for '' not found. '' is not a valid view function or pattern name. Driving me insane - I have looked at all the other solutions on SO for this type of error and none apply. Can anyone spot what the solution is? part of the base.html <li class="nav-item"> <a class="nav-link" href="{% url 'item-shoppinglist' %}">Shopping List</a> </li> the view class ItemShoppingList(generic.TemplateView): model = Item template_name = 'kitchens/shoppinglist.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['item_list'] = Item.objects.filter(item_shoppinglist=1) return context OP/urls.py from django.contrib import admin from django.urls import path from django.urls import include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('kitchens/', include('kitchens.urls')), ] #Add URL maps to redirect the base URL to our application from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='/kitchens/', permanent=True)), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Kitchens/urls.py - from django.urls import include, path from . import views urlpatterns = [ path('', views.index, name='index'), path('location/', views.LocationListView.as_view(), name='location'), path('location/<int:pk>', views.LocationDetailView.as_view(), name='location-detail'), path('location/create/', views.LocationCreate.as_view(), name='location-create'), path('location/<int:pk>/update/', views.LocationUpdate.as_view(), name='location-update'), path('location/<int:pk>/delete/', views.LocationDelete.as_view(), name='location-delete'), path('shelf/', views.ShelfListView.as_view(), name='shelf'), path('shelf/<int:pk>', views.ShelfDetailView.as_view(), name='shelf-detail'), path('shelf/create/', views.ShelfCreate.as_view(), name='shelf-create'), path('shelf/<int:pk>/update/', views.ShelfUpdate.as_view(), name='shelf-update'), path('shelf/<int:pk>/delete/', views.ShelfDelete.as_view(), name='shelf-delete'), path('ajax/load-shelfs/', views.load_shelfs, name='ajax_load_shelfs'), # <-- this one here path('item/', views.ItemListView.as_view(), name='item'), path('item/<int:pk>', views.ItemDetailView.as_view(), name='item-detail'), path('item/create/', views.ItemCreate.as_view(), name='item-create'), … -
Display profile image of a customuser in django
I am trying to show the uploaded image of a student in student profile but its not working. Below is my code Models.py class Students(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) gender=models.CharField(max_length=255) profile_pic = models.ImageField(null=True,blank=True) address=models.TextField() course_id=models.ForeignKey(Courses,on_delete=models.CASCADE) session_year_id=models.ForeignKey(SessionYearModel,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) fcm_token=models.TextField(default="") objects = models.Manager() Views.py def student_profile(request): user=CustomUser.objects.get(id=request.user.id) student=Students.objects.get(admin=user) return render(request,"student_template/student_profile.html",{"user":user,"student":student}) Template. <img src="{{ request.admin.user.profile_pic.url }}" class="img-circle elevation-2" alt="User Image"> -
How to secure media files in django in poduction?
I am trying to make a project and have some media files which should only be accessed by their owner. In production, media and static files are served by apache (or nginx but I am using apache). I was looking for some solutions and I am not able to apply. On djangosnippets website, I found this code, from mod_python import apache from django.core.handlers.base import BaseHandler from django.core.handlers.modpython import ModPythonRequest class AccessHandler(BaseHandler): def __call__(self, req): from django.conf import settings # set up middleware if self._request_middleware is None: self.load_middleware() # populate the request object request = ModPythonRequest(req) # and apply the middleware to it # actually only session and auth middleware would be needed here for middleware_method in self._request_middleware: middleware_method(request) return request def accesshandler(req): os.environ.update(req.subprocess_env) # check for PythonOptions _str_to_bool = lambda s: s.lower() in ("1", "true", "on", "yes") options = req.get_options() permission_name = options.get("DjangoPermissionName", None) staff_only = _str_to_bool( options.get("DjangoRequireStaffStatus", "on") ) superuser_only = _str_to_bool( options.get("DjangoRequireSuperuserStatus", "off") ) settings_module = options.get("DJANGO_SETTINGS_MODULE", None) if settings_module: os.environ["DJANGO_SETTINGS_MODULE"] = settings_module request = AccessHandler()(req) if request.user.is_authenticated(): if superuser_only and request.user.is_superuser: return apache.OK elif staff_only and request.user.is_staff: return apache.OK elif permission_name and request.user.has_perm( permission_name ): return apache.OK return apache.HTTP_UNAUTHORIZED But I am not able to install mod_python. … -
From Laravel to Django questions
I have been a Laravel developer for the past years, and I made most of my projects using Laravel. But now I'm working on a project that it needs a recommendation system and after looking around the web I found out that there's no Laravel package for this purpose and the best thing to do is to use python, and after doing a lot of research I think the best python framework to develop backend servers for a website or an application is Django. But to move from PHP Laravel to Python Django it's kinda hard to find the answers of the questions since the diffent ecosystem they, have and after doing searches on google I can't find the answers. so I have these questions I hope someone answer it one by one as I wrote it: 1- can I use any python packages with Django? like in Laravel you can use any php package using composer, or you can only use the packages in Django package system? 2- If one day moved to another Python framework like Flask, can I use the packages developed for Django? 3- I know Django does not support Rest API, do I have to … -
I dont know why my project in django return ModuleNotFoundError: No module named -
I have a django project with gunicorn and nginx. Everything was going well, but when I installed decouple for the environment variables, it started to give me the following errors: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.6/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.6/dist-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named '-' What can I do to fix it? Let me know if you need more files. Thanks for your help. -
Want to build a file conversion website using React and Django
Actually, I want to build a website which converts one file format to another. And looking for various resources. But, I could not find appropriate resources to do so. Note:- I can't use some paid APIs. I want to build it based on some 3rd party libraries or some open source APIs. Is there anything i can do to find resources for same? -
How to combine social auth/oauth with django custom user model
I have a custom user model that is based on AbstractBaseUser, PermissionsMixin and I would love to use a package such as django-allauth and/or social-auth-app-django. I have done some research but did not find any tutorials or examples. Can somebody recommend anything? -
Problem in integrating twak.to with django
Hi guys I thought of adding the chatbot twak.to to my website but i'm unable to. I have used the package django-twakto But confused using its readme file Like from where are {% twakto_tags % } {% twakto_ script %} Totally confusing!! And how to add widget code of twak.to even though I added it to my html file it's still not visible.. Any help will be appreciated? -
how to register a tag in HTML django to make a string lowercase?
I have a python list, iterated over to display a bullet point list on a web page. I want to make each entry in the list lower case, but still keep the original case for what get's displayed. I'm getting the following warning via Django below: TemplateSyntaxError at / Invalid block tag on line 12: 'catEntry', expected 'empty' or 'endfor'. Did you forget to register or load this tag? My html: {% extends "cats/layout.html" %} {% block title %} cats {% endblock %} {% block body %} <h1>All cats</h1> <ul> {% for entry in entries %} {% newEntry= entry.lower() %} <li><a href = 'cats/{{newEntry}}.md' </a>{{ entry }}</li> {% endfor %} </ul> {% endblock %} thanks -
i get "internal server error' when i add 'django_social_share' to my installed app
I have a web app running on AWS LIGHTSAIL, everything works fine, but on installation of 'django_social_share', and addition to my installed app, I get internal server error when the page is refreshed. Removing django_social_share from installed app takes everything back to normal. Please I need help plus if there is any other library I can use to share post. Thanks!! -
Why is my information is not shown from the database
i need help with a db issue in my project. The problem is in saving the order with the attached profile into the DB. It doesn't save the user to the order, and as a result, the order is half-empty sometimes, and when you try to display all orders of the user, you get an empty list. Here is my code. def checkout_success(request, order_number): save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) print("Order", order) profile = UserProfile.objects.get(user=request.user) print(profile) # Attach the user's profile to the order order.user_profile = profile order.save() print(order.user_profile) # Save the user's info if save_info: profile_data = { 'default_phone': order.phone, 'default_billingCountry': order.billingCountry, 'default_billingPostcode': order.billingPostcode, 'default_billingCity': order.billingCity, 'default_billingAdress1': order.billingAdress1 } user_profile_form = UserProfileForm(profile_data, instance=profile) print("UPF", user_profile_form) if user_profile_form.is_valid(): print("UPF Valid") user_profile_form.save() messages.success(request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.emailAddress}.') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context) And here is the Order and profie model Model: Order class Order(models.Model): order_number = models.CharField(max_length=35, null=False, editable=False) user_profile = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True, related_name='orders') # noqa:501 billingName = models.CharField(max_length=250, blank=True) emailAddress = models.EmailField(max_length=250, blank=True, verbose_name='Email Adress') # noqa:501 phone = … -
After running "makemigrations" and "migrate", the tables are not being created within PostgreSQL
I am trying to add additional tables to my database for a new app I have integrated in to my Django project. When I run the python3 manage.py makemigrations and python3 manage.py migrate, I can see the models have been created however, the relevant tables aren't being added to my database. The tables for Post, Preference and Comment are being added but the tables for Skill, SwapTags, Tagulous_SwapTags_title and Tagulous_SwapTags_hobbies aren't being added. (I can't see any errors to why their not being added) Here is my migrations file: # Generated by Django 3.2.2 on 2021-05-26 15:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import tagulous.models.fields import tagulous.models.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField(max_length=1000)), ('date_posted', models.DateTimeField(default=django.utils.timezone.now)), ('image', models.ImageField(default='default.png', upload_to='srv_media')), ('likes', models.IntegerField(default=0)), ('dislikes', models.IntegerField(default=0)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Skill', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ('slug', models.SlugField()), ('count', models.IntegerField(default=0, help_text='Internal counter of how many times this tag is in use')), ('protected', models.BooleanField(default=False, help_text='Will not be deleted when the count reaches 0')), ('path', models.TextField()), ('label', models.CharField(help_text='The name of the tag, without ancestors', max_length=255)), ('level', … -
Create a child form and modify parent at same time, Django
I have two models connected with a foreignkey parent and child, i would be able to create a child data and modify at the same time a field present in a parent model. thanks for any help -
convert the mentioned @ users to link in Django
How I can convert the @ + username to link that going to the user profile I by Django Filter My filter Successfully Identifies the users that mentioned @ but it is didn't convert them to link and it should shows @user1 but it shows instead <a href='http://192.123.0.0:8000/user1'>@user1</a> My Filter from django.template.defaultfilters import stringfilter register = template.Library() @stringfilter def open_account(value): res = "" my_list = value.split() for i in my_list: if i[0] == '@': try: stng = i[1:] user = Account.objects.get(username=stng) if user: profile_link = user i = f"<a href='http://192.168.43.246:8000/{profile_link}'>{i}</a>" except Account.DoesNotExist: print("Could not get the data") res = res + i + ' ' return res url_target_blank = register.filter(open_account, is_safe = True) THe filter in html {{ comment.content|open_account }} -
Problem adding user's email in Django admin
I created a custom model extending AbstractUser in order to authenticate users by email instad of by username (but not wanting to drop the username, because it will also be used). This was the first thing I made before running the first migration, everything worked correctly except in the Django admin, when I create a new user, I want these fields to be filled username email password And the admin only ask me for the username and password. How could I add the email too? Here's my codes models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifier for authentication instead of username. """ 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 create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') … -
How to access Active directory data to verify user from django model then return data based on that user in Django
The problem to solve is I need to make a URL i.e "http://172.0.0.1:8001/users_data/" which will be used by different machines in a company XYZ. Then in my views by using Active Directory I have to get user (user data) of that machine then I need to verify the user from Django model. After that I've to return data from different tables filtering/based on that specific user. If someone can share the example (using LDAP or any other library) for this ASAP would be very appreciable. -
How to apply background image in django without using css but only in html?
<pre> .container{ width :80%; max-width : 500px; padding: 20px; box-shadow: 10px 10px #E6E6FA; background-image: url("feed7.jpg"); border-radius : 10px; margin-bottom: 10px; margin-top: 50px;`enter code here` } </pre> how to insert background image in style tag in django. -
How to get current base urls path of django app
I'm making a reusable Django app, let's say its name is Polls. This app is supposed to work properly no matter where it's being configured in the urls.py of its parent app. Consider the following structure just like that in the Django tutorial mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ __init__.py urls.py admin.py apps.py models.py views.py So, the polls app has its own urls.py and its own views.py which can be linked to any other app, such a mysite by adding a line to mysite/mysite/urls.py such as line 5 in this example urls.py: from django.urls import path, include urlpatterns = [ path('polls/', include('polls.urls')) ] In this example, all views of the polls app will have a link like https://somedomain.com/polls/the-relative-page-link However, the polls app should still function correctly even if we edited line 5 in the above code to other base path such as: urlpatterns = [ path('another-path/', include('polls.urls')) ] So that would change the like to https://somedomain.com/another-path/the-relative-page-link My problem is that some of the views of the "polls" app contain custom javascript code that communicate with another view that represents a server-side API. So in order for this communication to work properly regardless of whether polls URLs are … -
Django Pinax-notifications errors
I am trying to work with the django pinax-notifications and do not manage to migrate the database. I have followed every steps of the pinax installation tutorial. Is it something to do with the django Pinax template. I have also several times tried to delete the files in my migrations folder. https://github.com/pinax/pinax-notifications I have the following error: File "C:\portal\dashboard\core\urls.py", line 11, in <module> re_path("app/", include(('app.urls','app'), namespace='app')), File "C:\portal\dashboard\env\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\portal\dashboard\app\urls.py", line 3, in <module> from app import views File "C:\portal\dashboard\app\views.py", line 18, in <module> NoticeType.create( File "C:\portal\dashboard\env\lib\site-packages\pinax\notifications\models.py", line 47, in create notice_type = cls._default_manager.get(label=label) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File … -
how to return nested json using django rest framework
I am trying build a REST API using django. here is my models.py and serializers.py. models.py from django.db import models class Person(models.Model): city = models.CharField(max_length=100) dob = models.DateField(editable=True) personName = models.CharField(max_length=100) class Meta: ordering = ['-dob'] serailizers.py from rest_framework import serializers from .models import Person class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = [ 'id', 'city', 'dob', 'personName'] Here is my api - http://127.0.0.1:8000/api/city/Sidney/. I am trying to fetch data by city name. I am getting the json in below format. [{ "id": 1, "city": "Sidney", "personName": "Giles", "dob": "2011-02-02" }, { "id": 5, "city": "Paulba", "personName": "Sidney", "dob": "2016-07-16" }] But i want the json in below shown format - [ { "id": 123, "city": "Sidney", "personInCity": [ { "id": 1, "city": "Sidney", "personName": "Giles", "dob": "2011-02-02" }, { "id": 5, "city": "Paulba", "personName": "Sidney", "dob": "2016-07-16" } ] } ] i am not getting what change needs to be done in Serializers.py -
django: replace values() with filter() or only() but sum in same row
I got a query currently looking like this: a = InventoryStatus.objects.values("city").annotate(Sum("a")).annotate(Sum("b")) city is a choicefield, which means I need to do get_FOO_display() on it, but I can't as values() returns a non-query set of a list of tuples, so everything’s evaluated there already. If I change values() to filter() or only() it works, but assuming I got 2 db inputs, one adding 500 to a and one adding 500 to b, then it would create two rows in my table in the template, instead of summing both fields in same row. How could I get the value from my choicefield and sum both values in the same row? -
Referencing twice related field for django model query
So I am using Django to construct a Query and I have 3 models as defined: class Book(models.Model): ... class Upload(models.Model): ... book = models.ForeignKey(Book, on_delete=models.CASCADE) class Region(models.Model): ... page = models.ForeignKey(Upload, on_delete=models.CASCADE) Given these 3 models I wanted a query that lists all the books and annotate them with a segmented_pages variable that contains the count of all the Upload that have non-zero number of regions. Basically, counting the number of uploads per book that have atleast one region. I am assuming the basic structure of the query would look like this and mainly the logic inside filter needs to be modified as there is no convenient count lookup. Book.objects.annotate(segmented_pages=Count('upload', filter=Q(upload__region__count__gt=0)) Can someone please help me with the logic of the filter and a simple explanation of how to go about designing these types of queries using django models?