Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Href with ManyToMany category slug
My Product model has a ManyToManyField Category attribute which I'm having trouble including in my url. I don't know how it will decide which category to use for the category_slug since there are multiple categories or some products. models.py class Product(models.Model): def image_dir(self, filename): modeldir = slugify(self.title) return "models/" + osjoin(modeldir, filename) title = models.CharField(max_length=80) featured_image = models.ImageField(upload_to=image_dir) category = models.ManyToManyField(Category) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Products" def __str__(self): return self.title template.html {% for model in category.product_set.all %} <div class="col-md-3 col-sm-6 d-flex align-items-stretch p-0"> <a href="{% url 'main:model_detail_view' model.category.category_slug model.model_slug %}"> <div class="categories-model-card p-3 m-3 animated fadeIn "> <img src="{{model.featured_image.url}}" class="img-fluid d-block"> <p class="model-name m-0 text-center">{{model.title|truncatechars:35}}</p> <div class="row"> <div class="model-title-spacer mt-2 mb-2"></div> </div> </div> </a> </div> {% endfor %} </div> {% endfor %} -
How to create default django permissions for un-managed models?
I have prepopulated database and un-managed model that looks like this: class Venue(models.Model): name = models.CharField(max_length=255) ... class Meta: managed = False db_table = 'venue' How can I create default permissions for this model (eg change_venue, view_venue, etc)? I tried to use django.contrib.auth.management.create_permissions(self) inside AppConfig.ready but it will only work if default django models (eg ContentType) are already created. Also tried to specify permissions in the Meta class but django throws an error "attempt to override default permissions". I have some thoughts about using migrations, but is it safe to use create_permissions functions (and similar) in migration for un-managed table (I usually write raw sql for them)? -
Django IIS and SQL with NT Authentication
Good morning. I have several Django apps running in my work environment. All are running through Gunicorn on Ubuntu. I have a new app that must run on Windows for ODBC reasons. This new app is running in development mode on a Windows 10 PC. I run the dev server while logged in as a service account, it uses a trusted connection (local credentials as I understand) to query a SQL server and works perfectly. I ported this app (virtualenv and all) to a Windows Server 2012 r2 instance and run the dev server successfully from there using my domain admin credentials (again trusted_connection=yes). I set up IIS on this server to run the app permanently and it appears to run. However, I get a django error page that says the SQL login failed for 'DOMAINNAME\SERVERNAME'. I have tried editing my Application Pool to use the credentials of the working service account (Advanced Settings > Process Model > Identity). With this configuration I no longer see a Django error page, just Service Unavailable HTTP Error 503. I have tried 'recycling' and restarting the IIS service after the change but that has not worked. Unfortunately, I do not have admin access … -
How to get samde data from model twice in html - Django?
i have slider of images with some text ! So basically I want when I click on image to pop up dialog! I have models and from there is that picture.So when it pop up I want same data there like "Name of image" "Desc about it" and so on.I have 7 images ! How can i do that ??? -
Cannot upload data through a foreign keys with Crispy Forms
I display the values of categories and subcategories, getting the value from there and save it as a foreign key in the News entity. models.py class News(models.Model): name = models.CharField(max_length=50) pic = models.ImageField() catid = models.ForeignKey(SubCat, on_delete = models.DO_NOTHING) class Cat(models.Model): name = models.CharField(max_length=50) class SubCat(models.Model): name = models.CharField(max_length=50) catid = models.ForeignKey(Cat, on_delete = models.CASCADE) add_news.html <label class="col-md-1 control-label" for="example-text-input">Text Input</label> <div class="col-md-5"> <input id="newstitle" name="newstitle" type="text" class="form-control" placeholder=".col-md-7"> </div> <select id="newscat" name="newscat" class="select-chosen" data-placeholder="Choose a Category.." style="width: 250px;"> {% for i in subcat %} <option value="{{ i.pk }}">{{ i.catid.name }} | {{ i.name }}</option> {% endfor %} </select> image Then I got all the values using queries and saved them like this: views.py @login_required(login_url='mylogin') def news_add(request): subCat = SubCat.objects.all() catID = request.POST['newscat'] if request.method == 'POST': newstitle = request.POST['newstitle'] newCatID = SubCat.objects.get(pk=catID) pic= request.FILES['picture'] news = News(name=newstitle, catid=newCatID, pic=pic) ... news.save() else: return render(request, 'back/news_add.html', {'subcat' : subCat}) But, now how can I use the crispy forms to display the same list of categories with subcategories and save it in my model PK (catid)? So, I can only display this add_news.html <div class="col-md-5"> {{ form.name|as_crispy_field }} </div> <div class="col-md-5"> {{ form.pic|as_crispy_field }} </div> <div class="col-md-5"> {{ form.catid.name|as_crispy_field }} {{ … -
HyperlinkedIdentityField error when retrieving url
When I try to add an url attribute to my model I get this error: AttributeError: 'collections.OrderedDict' object has no attribute 'pk' These are the codes I use. I tried a lot of things but just get an error with everything I try.. Serializer: class GroupPatchSerializer(serializers.ModelSerializer): linked_sites = serializers.ListField() name = serializers.CharField(required=False) url = serializers.HyperlinkedIdentityField( view_name="group-detail", lookup_url_kwarg="group_pk" ) class Meta: model = Group fields = ("id", "url", "name", "linked_sites") def validate_linked_sites(self, sites): ** code ** return sites # noinspection PyMethodMayBeStatic def validate_name(self, name): ** code ** return name view: def patch(self, request, group_pk): """ Add site to group, change an existing group's name. -id: The group's id """ user = request.user group_id = int(group_pk) group = Group.objects.filter(pk=group_id).first() # Update the group serializer_class = self.get_serializer_class() serializer = serializer_class( data=self.request.data, context={"request": request, "user_pk": user.id, "group_id": group_id}, ) test-class: def test_ok_authorized_access(self): # Login the user self.client.force_login(self.user_1) UserSiteFactory(user=self.user_1, site=self.test_site_3) # Get the url url = reverse("group-detail", kwargs={"group_pk": self.test_group_1.pk}) # New group name new_name = "New group name" sites = [self.test_site_3.pk] # Execute the patch operation response = self.client.patch( url, data={"name": new_name, "linked_sites": sites} ) # Test if there was no error self.assertEqual(response.status_code, status.HTTP_200_OK) # Test if the group was renamed group = Group.objects.all().filter(pk=self.test_group_1.pk).first() self.assertEqual(group.name, … -
Invalid Form Django
In my views, the request method is posted but the form is invalid. In HTML, it already shows the form then when I click submit the request post but I don't know why the form is invalid. please correct me. And it the error appear when I inherit the User model. Here is my source code. models.py class UserAccountManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user( email, password, **extra_fields) def create_superuser(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) def get_by_natural_key(self, email): return self.get(email=email) class User(PermissionsMixin,AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=256, blank=True) last_name = models.CharField(max_length=256, blank=True) # username = models.CharField(max_length=150, blank=True) phone = PhoneNumberField(null=True, blank=True, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=now, editable=False) password = models.CharField(blank=False, null=False, editable=True, max_length=100) description = models.TextField(null=True, blank=True) token = models.UUIDField(default=get_token, editable=False, unique=True) objects = UserAccountManager() USERNAME_FIELD = "email" def save(self, *args, **kwargs): self.password = make_password(self.password) super(User, self).save(*args, … -
Should I use django Signals in this case?
I’m a beginner, I discover many things and sometimes I feel overwhelmed about all the informations and tricks to learn. I try to do a django project for a pizzeria. People can order pizza online, the order is simple : you can choose one or more pizza and optionally add some Extras (adding cheese, ham or whatever…) for each pizza you ordered and it’s added to the cart. My problem is to calculate automatically the price for each pizza. Basically here’s my Model file: class Pizza(models.Model): nom = models.CharField(max_length=30) ingrédients = models.CharField(max_length=500) prix = models.DecimalField(max_digits=4, decimal_places=2) nom means name class Extra(models.Model): sup = models.CharField(max_length=30) prix = models.DecimalField(max_digits=3, decimal_places=2) sup is the name of the extra. class IndividualChoice(models.Model): pizzaChosen = models.ForeignKey(‘Pizza’, default="", null=True, on_delete=models.CASCADE) extraChosen = models.ManyToManyField(‘Extra’, blank=True) panier = models.ForeignKey(‘Cart’, default="", on_delete=models.CASCADE) calzone = models.BooleanField(default=False) prix = models.DecimalField(max_digits=5, decimal_places=2, default=0) IndividualChoice is a bit weird. It’s a model which stores each choice, here “panier” means Cart which has a model but I don’t think it’s useful to make it appear here. I learned a bit about django signals, so I tried to create one: def prix_extra_calcul(sender, instance, action, *args, **kwargs): instance.prix = 0 if action == “post_add” or action == … -
How can I write a Python Program That can Take a String and Provide the Result for the specific string
I want to write a python program which will take data from a FORM INPUT, store the data temporarily(Redis Caching), go to a Specific Website and Look for the Provided String, Mainly the String is a Unique Identification, so The Program Should provide the String in the given search box and view the result,(All this will happen in background) Finally the result is collected and Shown on to the client Side. -
restrict superuser to its specific tenant
i'm trying to build multi tenants application using django and this package. I tried this package same as describe here. Every things works fine but here one user can login into other tenants admin panel. For more info please follow this link. I know if I try this approach, this issue was resolve # Application definition TENANT_MODEL = "tenant.Client" SHARED_APPS = [ "tenant_schemas", "apps.tenant" ] TENANT_APPS = [ ######### Django apps start from here ############ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", "django.contrib.staticfiles", # "django.contrib.humanize", # Handy template tags "django.contrib.admin", ######### Django app ends here ############ ######### Third party apps start from here ############ "rest_framework", 'rest_framework.authtoken', ######### Third party apps end here ############ ######### Local apps start from here ############ "apps.address", "apps.users", ######### Local apps end here ############ ] INSTALLED_APPS = SHARED_APPS + TENANT_APPS But after this i can't able to edit public schema data, when i was logged into other schema. -
Using TMDb API in Django Web Framework to retrieve posters for movies in a database
I'm displaying all of my movies in a list and would like to have the respective poster under each movie. I think I've made a mistake in my view, as I'm trying to make the request in a view class. It would be great if someone could point me in the right direction, for I'm still new to Django, and I've not used many APIs before. I should note that I'm using a Python library specifically for the TMDb API called tmdbv3api: https://pypi.org/project/tmdbv3api/ I can't post a screenshot, but the resulting web page has an empty thumbnail under each movie listed. I can provide the code for the Movie model if needed. Thank you in advance! views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse import csv, io, requests from .models import Movie from django.views.generic import ListView from tmdbv3api import TMDb from . import config my_api_key = '53422b9ff6c08f3c8a3830cf0e2fb0f7' base_url = 'https://api.themoviedb.org/3/' def index(request): return HttpResponse("Hello, world. This is the movie app index.") class movie_list_view(ListView): model = Movie template_name = 'movieapp/movies.html' context_object_name = 'movies' ordering = ['movie_id'] paginate_by = 100 def movie_poster(request, movie_id): url = f'{base_url}movie/{Movie.tmdb}?api_key={my_api_key}&language=en-US&page=1' response = requests.get(url) tmdb_movies = {'movieposter':response.json()} return render(request, 'movies.html', context=tmdb_movies) movies.html {% block content … -
Django LookupError: No installed app with label 'admin'
I'm trying to running the appserver with python manage.py runserver with python 3.8.2 and django 3.0.3. I've setup a mysql database connection and inserted my "myApp.apps.myAppConfig" into INSTALLED_APPS, declared a couple of database-view based models, a form and a view. Nothing that seems too out of the way for the tutorials i've found. When i run the python manage.py runserver command, this is the output: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'admin' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\celli\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) … -
How do I notify users in real time when a new task is added with Django Channels?
I want to keep informed all website users when a new task is added. I use Django channels to do that. Here is my code: routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from api.consumers import TaskConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path('notifications/', TaskConsumer), ]) }) consumers.py from channels.generic.websocket import AsyncJsonWebsocketConsumer class TaskConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("tasks", self.channel_name) async def disconnect(self, close_code): await self.channel_layer.group_discard("tasks", self.channel_name) async def user_tasks(self, event): await self.send_json(event) signals.py from tasks.models import Task from django.db.models.signals import post_save from django.dispatch import receiver from asgiref.sync import async_to_sync from channels.layers import get_channel_layer @receiver(post_save, sender=Task) def announce_new_task(sender, instance, created, **kwargs): if created: message = { "title": instance.title, "description": instance.description, "criticity": instance.criticity.name, "location": instance.location.name, "task_type": instance.type.name, "status": instance.status, } channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "gossip_tasks", { 'type': 'user.tasks', 'text': message } ) index.html (I just want to show the new task in the console for now) <script> document.addEventListener('DOMContentLoaded', function () { const webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect('ws://backend.local:8888/notifications/'); webSocketBridge.listen(function (action, stream) { console.log("RESPONSE:", action); }); document.ws = webSocketBridge; /* for debugging */ }); </script> I don't have any error in the browser console and when I add a new task, nothing happen... I just have this erros in my … -
Can unique_together avoid nulls in Django
I am using django and Sql server as a database. I have a table with a multiple primary key using the unique_together class Attribute_tmp(models.Model): useridtmp = models.ForeignKey(User_tmp, on_delete=models.CASCADE, blank =True, null = True) userid = models.ForeignKey(User, on_delete=models.CASCADE, blank =True, null = True) fk_str = models.ForeignKey(Stream, on_delete=models.CASCADE) class Meta: unique_together = (('userid', 'fk_str'),('useridtmp', 'fk_str')) So when i add objects of this table when the useridtmp is null, it doesn't work because i will have a duplicated key. My Question is how can i avoid the null values. Thank you -
Django visited url stack
We have a Django application underway, which could basically be considered as a CRUD application. In some of the list views, users can perform custom filters, which are processed through GET parameters. We have received numerous suggestions, so that after performing an editing operation or a detailed query of a record, the filters of the previous list view are preserved. If you simply perform a detailed query and return, it would be relatively easy to perform this action, since we could use the HTTP_REFERER parameter. However, as soon as an editing operation is performed from the detail view, we would already lose that parameter. That is why we are evaluating different options and one of them would be to create a stack of visited addresses, which would allow us to go back whithout lose the list view filters. I would like to know if anyone has encountered this development point with a Django application and has implemented a similar issue, since we are not yet clear about the performance impact that it could have on the system, as well as certain actions to plan for resetting the stack when visit a main url, for example, and so on. -
Error during template rendering In templat \ProjectManagementapp\product_retrieve.html, error at line 16
Error in this pdata {% if pdata %} view.py def product_retrieve_view(request): pdata = ProductData.objects.all() return render(request,'ProjectManagementapp/product_retrieve.html',{'pdata':pdata}) -
Django-CMS source code directory in pycharm after installing django cms through terminal?
How to see dajngo CMS all source code of administration page in pycharm . "View published" and "publish changes" button code in django cms adminstation panel in pycharm after installing django cms in pycharm through terminal. -
Django Implement Search by location of google maps
I am trying to implement a search system in my Django apps. For example, I have many service sellers person in a city. When user Search by its location that will google map autosuggest in my form search field. After users/clients click on choose a location, they will get all the salesperson location nearby the location they are expecting. The search system will look like these websites: https://www.foodpanda.com.bd/ https://www.justdial.com/ https://www.hungrynaki.com/ I am not getting should I use GeoDjango or not. I know I need to use google API but I am not getting how to store the location data in my database. I see GeoDjango solves this problem very well, yet I am confused if GeoDjango is a good fit for my project. Your suggestion much appreciated, -
How do i create a table using JSON in my views.py?
How do i create a table using this query that correspond each other? This is my views.py corevalues = CoreValues.objects.all().order_by('Display_Sequence') marking = StudentBehaviorMarking.objects.all() corevaluesdescription = CoreValuesDescription.objects.values('id', 'Description').distinct( 'Description').order_by('Description') period = gradingPeriod.objects.filter(id=coreperiod).order_by('Display_Sequence') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher=teacher).filter( GradeLevel=gradelevel.values_list('Description')) \ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by( 'Students_Enrollment_Records') student = StudentPeriodSummary.objects.filter(Teacher=teacher).filter( GradeLevel__in=gradelevel.values_list('id')) this is i want a result This is my models class CoreValues(models.Model): Description = models.CharField(max_length=500, null=True, blank=True) Display_Sequence = models.IntegerField(null=True, blank=True) . class CoreValuesDescription(models.Model): Core_Values = models.ForeignKey(CoreValues,on_delete=models.CASCADE, null=True) Description = models.TextField(max_length=500, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, on_delete=models.CASCADE) Display_Sequence = models.IntegerField(null=True, blank=True) class StudentBehaviorMarking(models.Model): Marking = models.CharField(max_length=500, null=True, blank=True) Non_numerical_Rating = models.CharField(max_length=500, null=True, blank=True) class StudentPeriodSummary(models.Model): Teacher = models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True, blank=True) Students_Enrollment_Records = models.ForeignKey(StudentSubjectGrade,on_delete=models.CASCADE) is it possible to create table using python right? -
How to access apis that require oauth2 using python?
I’m learning python and I’m trying to build a small web app using the Django framework. I’m Trying to understand how to access some Apis that I’m intending to use ( Adobe Sign) and I can’t figure out how to handle the oauth -
Django: Queryset.filter user.groups.all() within ListView, Show content depending upon which group you belong to but admin sees all
In Django I have a ListView showing a product list. I have two user groups: Company1, Company2. I have 5 users: User1, User11, User2, User22, Admin User1, User11 (both belongs to Group "Company1" User2, User22 (both belongs to Group "Company2") "Admin" belongs to both groups. Desired functionality: when User1 is logged in, they see products created by either User1 or User11 (i.e. created someone within Group: Company1) As Admin, I would like to list all products created by Company1 and Company2 (all Users) In the below attempts, I can make all to work except for Admin that can not see any product. How can I improve my code to let Admin see both group's products? in models.py from django.contrib.auth.models import User class Product(models.Model): author = models.ForeignKey(User, blank=True, on_delete=models.CASCADE) company = models.CharField(max_length=100, null=True, blank=True) def save(self, *args, **kwargs): self.company = list(self.author.groups.all().values_list('name', flat=True)) super(Product, self).save(*args, **kwargs) within views.py class ProductListView(LoginRequiredMixin, ListView): model = Product template_name = 'product_list.html' def get_queryset(self): queryset = super(Product, self).get_queryset() return queryset.filter(company__contains=list(self.request.user.groups.all().values_list('name', flat=True))) -
No name 'config' in module 'decouple'
when i'm trying to import decouple module with code as stated below from decouple import config getting this error " No name 'config' in module 'decouple' " please help!! -
Django value to a HTML TextArea via Javascript
first, I will like to apologize for my english, because it's not my native language :( So... I'm using Django for web development and I've being facing an issue, the thing is that I currently have this model: class Project(models.Model): project_name = models.CharField(max_length=200) project_company = models.CharField(max_length=200) project_notes = models.TextField(default="") And I want to show project_notes data in a HTML TextArea, so for doing this, I have been using Javascript in the following way: <script> var notes = "{{ proyecto.project_notes | safe }}"; document.getElementById("notesTextArea").value = notes; </script> Note that notesTextArea is the id for the textarea tag on my html, and this script is right on the bottom of my html document (before body tag's end) And I'm rendering this template (and also saving changes in case of POST request) with this python function on my views.py: def notas(request, id): project = Project.objects.get(id=id) if request.method == 'GET': return render(request=request, template_name="tasks/notes.html", context={"proyecto": project}) else: new_notes = request.POST["notes"] project.project_notes = new_notes project.save() return redirect('tasks:notas', id=id) The issue is that when I add a newline on the text area (press intro) and save the data, apparently the data is saving (because I checked django admin) but the textarea is no longer showing the data. … -
what's the difference between views.list_rooms() and views.list_rooms?
I'm leargning Django, and I want to know the meaning of empty parentheses, or () follows after def name. urls.py from django.urls import path from . import views app_name = "app_name" urlpatterns = [path("list", views.list_rooms())] #'list_rooms()' did not work urlpatterns = [path("list", views.list_rooms)] #'list_rooms' did work views.py def list_rooms(request): ~~ when it was list_rooms() it raised TypeError TypeError: list_rooms() missing 1 required positional argument: 'request' Thank you. -
How to query specific field in dango JSON field
I have a model, which has JSON field called data. I need to query all models, which have type in this data field, which starts with string gpa. Corresponding query is: select data ->> 'type' from model where data ->> 'type' like 'gpa.%' How can I do this using querysets? All I could find is an exact match, not startswith. I am using django 1.18