Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create new Django model int field from existing bool fields
I have a model with several bool fields. I'd like to replace them with a single int field where each bit represents one of the old bools. I've added the new int field and run makemigrations. Is there a way I can modify the migrations file and define how I'd like the new int fields' values to be defined? Like I said, I would like them to take the values of the previous bool fields. -
How to let libpng16.so.16 use libz.so.1 in the local directory ? (Another ZLIB_1.2.9 issue)
When I run a django project, I got the following error: ImportError: /lib64/libz.so.1: version `ZLIB_1.2.9' not found (required by /home/ec2-user/anaconda3/lib/./libpng16.so.16) I found that that directory /home/ec2-user/anaconda3/lib/./ already contains a correct version of libz.so.1, libz.so.1 -> libz.so.1.2.11 But it seems that libpng16.so.16 is using libz.so.1 in /usr/lib64. How to let libpng16.so.16 use libz.so.1 in the local directory ? -
Django error: ValueError: Cannot assign "(<Category: Cultural>, True)": "Site.category" must be a "Category" instance
I need to create a database importing data from a csv file. Following the instructions of the exercise, I created the models and a file for the script, but when I run the command python manage.py runscript many_load it gives me the error in the title. Here's the code: - models.py: from django.db import models class Category(models.Model): category = models.CharField(max_length=128) def __str__(self): return self.category class State(models.Model): state = models.CharField(max_length=25) def __str__(self): return self.state class Region(models.Model): region = models.CharField(max_length=25) def __str__(self): return self.region class Iso(models.Model): iso = models.CharField(max_length=5) def __str__(self): return self.iso class Site(models.Model): name = models.CharField(max_length=128) year = models.CharField(max_length=128) area = models.CharField(max_length=128) describe = models.TextField(max_length=500) justify = models.TextField(max_length=500, null=True) longitude = models.TextField(max_length=25, null=True) latitude = models.TextField(max_length=25, null=True) #one to many field category = models.ForeignKey(Category, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) iso = models.ForeignKey(Iso, on_delete=models.CASCADE) def __str__(self): return self.name - many_load.py: import csv from unesco.models import Site, Category, Iso, Region, State def run(): fhand = open('unesco/whc-sites-2018-clean.csv') reader = csv.reader(fhand) next(reader) Category.objects.all().delete() Iso.objects.all().delete() Region.objects.all().delete() State.objects.all().delete() Site.objects.all().delete() for row in reader: # print(row) # print (len(row)) name = row[0] describe = row[1] justification = row[2] year = row[3] longitude = row[4] latitude = row[5] area = row[6] category = Category.objects.get_or_create(category=row[7]) … -
User login verification in nodejs express routes with Django REST API containing the User authentication
I am creating a web application using NodeJS and express on the frontend making api calls to my Django REST api in the backend. I only want logged in users to be able to access the homepage and redirecting them back to a login page if they are not logged in/do not have a JWT. I know this process can be done using a passport in NodeJS however my User Authentication is already done in Django so this cannot be applied to my situation. I am trying to create middleware in my index.js file to check for authenticated users but my app crashes when the code executes. ``` router.get('/', checkAuthenticated(req, res, next) { res.render('index', { title: 'Home'}); }); function checkAuthenticated(req, res, next) { const bearerHeader = req.headers['authorization']; if (typeof bearerHeader !== 'undefined') { res.redirect('/login') } else { next() } } -
Q() in Django view not honoured
I have this model: class Opportunity(models.Model): [...] deadline = models.DateField(default=dateformat.format(timezone.now(), 'Y-m-d')) ongoing = models.BooleanField(default=False) [...] The view: def opportunities_list_view(request): opportunities = Opportunity.objects.filter(Q(ongoing=True) | Q(deadline__gte=datetime.now())) context = { 'opportunities': opportunities, } return render(request, 'opportunities/opportunities_list.html', context) This is the template: {% for opportunity in opportunities %} <tr> <td>{{opportunity.title}}</a></td> [...] urls.py: from myapp import opportunities_list_view, [...] path('opportunities/', opportunities_list_view, name='opportunities_list') [...] The template is displaying only the objects with deadline__gte=datetime.now(). If an object has ongoing=True and deadline in the past then it's not showing up. Isn't what the | in my Q() is supposed to take care of? Is there something I'm missing? -
What is this form argument in formValid() in Django, what does it do?
https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-editing/#django.views.generic.edit.FormView def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) what is form argument in the form_valid function....what does it do? Is there any documentation. -
Show posts when clicking on a tag (django)
I am new to django and I am facing a problem I can't solve. I'm making a blog and I want to be able to click on a tag and go to a new page which will have all posts with this tag. I already made a page which has the selected tag as a slug in the url, but I don't know how to show all the posts with that tag on this page. My models page: class Tag(models.Model): caption = models.CharField(max_length=30) tag_slug = models.SlugField(unique=True, db_index=True, null=True) class Post(models.Model): title = models.CharField(max_length = 150) image_name = models.CharField(max_length=100) slug = models.SlugField(unique=True, db_index=True) tags = models.ManyToManyField(Tag) My urls page: urlpatterns = [ path("", views.starting_page, name = "starting-page"), path("posts", views.posts, name = "posts-page"), path("posts/<slug:slug>", views.post_detail, name = "posts-detail-page"), path("posts/tag/<slug:tags>", views.post_tag, name = "post-tag-page"), ] and the function I created to render this: def post_tag (request, tags): identified_tag = get_object_or_404(Tag, tag_slug=tags) return render (request, "blog/post-tags.html") I use this function to render the page but I do't know how to select (and render) all posts (their images to be precise) which have a specific tag. -
How do I refactor this for loop to be shorter
I am relatively new to Django and have created my first live project. I am currently going through my code to refactor it and know that this logic can be written in a much more concise and clear way. I am working my way through it and was wondering if people have any pointers on simplifying the logic. What the view does is go through a database of cities and see if the attributes of the city (hot climate, expensive, etc) match the specific attributes the user selected in the form. If there is a match, that city is added to a list. views.py # list of each variable's broad category broad_variable_list = ["safety", "affordability", "transit", "language", "attractions", "climate"] # list of attractions attractions_list = ["beaches, mountains, monuments, nightclubs, national park"] # weighting of each variable ranking weight_variable1 = 0.33 weight_variable2 = 0.24 weight_variable3 = 0.17 weight_variable4 = 0.14 weight_variable5 = 0.12 # destination results view def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ranking_form(request.POST) # check whether it's valid: if form.is_valid(): # … -
Python POST request code does not work in django
I'm new to Django and I have a POST request which works perfectly in normal Python CLI. It returns me a webpage, yes a webpage and then I can simple use Regex to extract some part of it and that's it. However I'm having lots of trouble trying to do the same in Django and show the extracted text on a webpage. Below are code snippets from my files. Please keep in mind that I'm new to Django & Web. Here's the urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.output, name='getINFO') ] Here's the home template home.html <body> <script> var link = '{% url "getINFO" %}'; </script> <button onclick="location.href = link">Submit</button><hr> {% if data %} <p>{{data}}</p> {% endif %} </body> Here's the function in views.py def output(request): headers = { 'Connection':'keep-alive', 'Pragma':'no-cache', 'Cache-Control':'no-cache', 'Upgrade-Insecure-Requests':'1', 'Origin':'https://www.xxxxxx.com', 'Content-Type':'application/x-www-form-urlencoded', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Referer':'https://www.xxxxxxx.com', 'Accept-Language':'en-US,en;q=0.9' } payload = { '__VIEWSTATE':'xxx', '__VIEWSTATEGENERATOR':'xxx', '__EVENTVALIDATION':'xxx', 'MIS':'xxxxxxxxxxxxx', 'MISB':'xxxx' } url = 'https://www.xxxxxx.com' res = requests.post(url,headers=headers, data=payload) price = re.search('style="font-size:X-Large;">(.*?)\/-<\/span>',res.text) return render(request,'home.html',{'data':price}) The above request works just fine in normal Python CLI and price does indeed have … -
ApartmentFilterSet resolved field 'geom' with 'exact' lookup to an unrecognized field type PointField
I have a filters.py file that uses django-filter app. But when I try to filter apartments by subcity, it throws an exception ApartmentFilterSet resolved field 'geom' with 'exact' lookup to an unrecognized field type PointField. I used a filterset override, this error won't go away. import django_filters from django.contrib.gis.db import models as geo_models from .models import Apartment class ApartmentFilter(django_filters.FilterSet): ADKT = 'Addis Ketema' AKLT = 'Akaki-Kality' ARDA = 'Arada' BOLE = 'Bole' GLLE = 'Gulele' KLFE = 'Kolfe-Keranio' KIRK = 'Kirkos' LDTA = 'Lideta' YEKA = 'Yeka' NFSL = 'Nefas Silk-Lafto' SUBCITY_CHOICES = [ (ADKT, 'Addis Ketema'), (AKLT, 'Akaki-Kality'), (ARDA, 'Arada'), (BOLE, 'Bole'), (GLLE, 'Gulele'), (KLFE, 'Kolfe-Keranio'), (KIRK, 'Kirkos'), (LDTA, 'Lideta'), (NFSL, 'Nefas Silk-Lafto'), (YEKA, 'Yeka')] class Meta: model = Apartment fields = ['apt_subcity', 'apt_cost','geom'] filter_overrides = { geo_models.PointField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'exact', }, } } ordering = django_filters.ChoiceFilter(label='Ordering',subcity_choices=SUBCITY_CHOICES, method='filter_by_ordering') -
ImportError: Couldn't import Django inside virtual environment?
I created a django project, set up a virtual environment, and added django with poetry add. inside pyproject.toml: [tool.poetry.dependencies] python = "^3.9" psycopg2-binary = "^2.9.3" Django = "^4.0.1" When I run command to create an app: p manage.py startapp users apps/users I get this error: Traceback (most recent call last): File "/graphql/graphenee/manage.py", line 22, in <module> main() File "/graphql/graphenee/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? venv is set, activated, django is installed but I am still getting this error. Inside virtual envrionment I start python shell and i get this error: Python 3.9.7 (default, Sep 16 2021, 13:09:58) [GCC 7.5.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' Django is also globally installed and when I start the python shell in global environment, I can import django: Python 3.9.7 (default, Sep 16 2021, 13:09:58) [GCC 7.5.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>> … -
How to access requested user object from jwt token in django serializers?
After user-registration, user wants to post data into Client model ( OnetoOne relationship with User model ). So, I want to access the requested user object inside the serializer-class to create a new row in Client model associated with the requested user. models.py class Client(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, null=False, blank=False) sex = models.CharField(max_length = 6, blank=False, null=False) location = models.CharField(max_length = 30, null = False, blank = False) views.py class ClientRegister(GenericAPIView): def post(self, request): user = request.user serializer = ClientSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response(status= status.HTTP_201_CREATED) else: return Response(data= 'Invalid Form', status= status.HTTP_400_BAD_REQUEST) serializers.py class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ['sex', 'location'] def create(self, validated_data): sex = validated_data.get('sex') location = validated_data.get('location') user = #------ Want requested user object here ------# if user.is_client: client = Client(user=user, sex=sex, location=location, company=company, experience=experience) client.save() return client I have manually added user oject into the data in serializer = CientSerializer(data=request.data). But, It didn't work. Please, tell me how to pass it from views.py or how to access it in serializers.py. -
Django Make a Left Join with new col or empity field
i need print all items but also i need know if current user request.user have that item in list with SQL is just something like select * from item as i Left JOIN UserItems as ui ON ui.item=i.id left Join user as u ON ui.user=u.id so i just need check if u.id is not null, how i have to do with django for get all item list? class User(AbstractUser): email = models.EmailField(unique=True) birthday = models.DateField(blank=True, null=True) class UserItems(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Item(models.Model): name = models.CharField(max_length=250 ) created = models.DateTimeField(default=timezone.now) obviously UserItems.objects.filter(useritem__user=request.user) dosen't get all items -
Django how hide empty category
I have a hoodie category and two gender divisions male and female. How can I hide a category hoodie for a gender that does not have this product? {% get_genders as genders %} {% for gender in genders %} <li> <!-- First Tier Drop Down --> <label for="drop-2" class="toggle">Категории <span class="fa fa-angle-down" aria-hidden="true"></span> </label> <a href="/">{{ gender }} <span class="fa fa-angle-down" aria-hidden="true"></span></a> <input type="checkbox" id="drop-2"> <ul> {% get_category as categories %} {% for category in categories %} <li><a href="{% url 'category' gender_slug=gender.slug category_slug=category.slug %}">{{category.name}}</a> </li> {% endfor %} </ul> </li> {% endfor %} I'm try make many to many field gender for category, but I don't know how to write in html models.py class Gender(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, unique=True) class Meta: verbose_name = 'Гендер' verbose_name_plural = 'Гендеры' def __str__(self): return self.name def get_absolute_url(self): return reverse('gender', kwargs={'gender_slug': self.slug}) class Category(models.Model): name = models.CharField(max_length=100) gender = models.ManyToManyField(Gender) slug = models.SlugField(max_length=200, unique=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'category_slug': self.slug}) -
Django Aggregation: highest sum in categories
Hy Guys I was wondering how I can get the highest sum of one category. So i have a model with my categories and a model with my costs which contains a cost category. My models.py from django.db import models class CostCat(models.Model): name = models.CharField(max_length=50, default=None, null=True, blank=True) class Cost(models.Model): name = models.CharField(max_length=50, default=None, null=True, blank=True) cost_category = models.ForeignKey(CostCat, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2,null=True, blank=True) The result should be that I can show the category with the highest sum of costs. I have been stuck on that for hours now. The closest i got was with my tests as shown below. I can print out all the sums and its respective category but now I now need to find out how to get the category and the value of the highest sum. And i'm really in a spiral right now. views.py def metrics(request): tests = CostCat.objects.annotate(sum=Sum('cost__amount')) for test in tests: print(test, test.sum) return render(request, 'metrics.html', "topcostcat":test, "topcostcatsum":test.sum ) Much appreciated if you could me a bit out! Thanks in advance -
What is easiest UPDATE ImageField in Django Rest Framework and delete old image?
I want to update my image field and delete the old one using the Django-rest framework. this is my model class GroupPostsModel(models.Model): post_text = models.CharField(max_length=1000) post_type = models.CharField(max_length=20) image = models.ImageField(blank=True, null=True, upload_to='post_images/') document = models.FileField(blank=True,null=True, upload_to='post_documents/') likes = models.IntegerField(default=0) time_stamp = models.DateTimeField(auto_now=True) group = models.ForeignKey(GroupsModel, on_delete=models.CASCADE) user = models.ForeignKey(UserModel, on_delete=models.CASCADE) class Meta: db_table = 'group_posts' My views.py is as follow @api_view(['PATCH']) def save_edited_post_image(request): image = request.data.get('image') print('image == ') print(request.data.get('image')) post_id = request.data.get('post_id') print('post id = '+str(post_id)) try: GroupPostsModel.objects.filter(id=post_id).update(image=image) resp = { 'resp' : 'Post image updated...!' } except Exception as e: print(e) resp = { 'resp': 'Error: Post image update failed...!' } return Response(resp) Code doesn't throw errors but does not work as expected. In the database it stores the value as image_name.jpeg; Expected value to be stored: post_images/1640341471608.jpeg -
In django how to get the all the data from table one with the related data from the table two in a single context
I have two classes in my models.py which are item and batch. I need to get all the data of item also the appropriate batch_id from the class batch. How should I write my views.py to get all the data to a single context class item(models.Model): item_name=models.CharField(max_length=100) item_code=models.IntegerField() min_stock=models.IntegerField() current_stock=models.IntegerField() def __str__(self): return self.item_name class batch(models.Model): batch_id=models.IntegerField() item_name=models.CharField(max_length=100) item_code=models.IntegerField() def __str__(self): return self.item_name -
how to had more 50000 urls in django sitemap
path( 'sitemap.xml', sitemap, { 'sitemaps': sitemaps }, name='django.contrib.sitemaps.views.sitemap' ), this above example is my sitemap config in Project level urls.py from django.contrib.sitemaps import Sitemap from .models import Post class PostSitemap(Sitemap): changefreq = 'always' priority = 0.9 protocol = 'https' limit = 5 def items(self): return Post.aupm.all() def lastmod(self, obj): return obj.updated this above code is for sitemaps.py in application level which generating this code <urlset> <url> <loc> https://localhost:8000/en/kavi/lobaan-ke-5-laabh-aur-upyog-aur-7-mithk-0x76/ </loc> <lastmod>2022-01-28</lastmod> <changefreq>always</changefreq> <priority>0.9</priority> </url> <url> What I want is : what to do if i have much more element in more than 50,000 (fifty thousand) element in that application, If i want to add more element(ie sitemap) from diffrent application -
How do I assign incrementing variable names from form data
I am relatively new to Django and have created my first live project. I am currently going through my code to refactor it and was wondering if there's a way to assign these variables to the form data in a way that uses more lines and is clearer. Since my variable names for the form all start with "specific_variable", I was thinking of having a for loop for the form data that assigns incrementing variable names such as "specific_variable1" and "specific_variable2". Would this work or is the way I currently assign variable names to form data fine? views.py # destination results view def get_ranking(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = RankingForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required specific_variable1 = form.cleaned_data['specific_variable1'] specific_variable2 = form.cleaned_data['specific_variable2'] specific_variable3 = form.cleaned_data['specific_variable3'] specific_variable4 = form.cleaned_data['specific_variable4'] specific_variable5 = form.cleaned_data['specific_variable5'] -
Setting monthly usage limit - Django API
I am going through Django rest framework documentation and other questions here trying to figure if there is a way to customize it for monthly rate limit by user-group. logic: User A - Group 1 User B - Group 2 Group 1 - allowed 10 calls per month to endpoint Group 2 - allowed 100 calls per montg any help is much appreciated, I am new to Django and fascinated by DRF -
How to dynamically import Django settings variables?
I want to import Django settings dynamically. something like this: from django.conf import settings settings.get('TIMEOUT_CONFIG', 10) but this thing doesn't work. I also tried this settings.__dict__.get('TIMEOUT_CONFIG') but this thing also won't work before I call it like this settings.TIMEOUT_CONFIG -
Django group by month with possible zeros
Am creating an chart for data analytics. So i need to group the count by month for the whole year. My model: Class Application: reference, created_at From the above, i need count of applications for each month for the current year. And with the current query i get all the data but i am not getting data for the months which no data is available: My query: queryset = Application.objects.filter(user=user).annotate(month=TruncMonth('created_at')).values('month').annotate(_applications=Count('id')).order_by('month') For example, If i have data for month Jan and Feb the above query gives data of those only but i need the data to contain "0" for all non data available months: If March doesnt have data means, the result should be "0" for that month. How to do this ? -
My images are created in base dirrectory tell me how to display images from this base dirrectory in django
Dear Django developer I need your kind help. I'm new to Django, guide me on how to display images by setting the base directory path. I did not know what to write in views, URLs, HTML page to display an image using Django. or also guide me on how to download PNG, JPG, and PDF images. -
Django query returning empty result
This is my model class MenuItem(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.CharField(max_length=1000, null=True) menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Venue(models.Model): name = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.name}' class VenueMenu(models.Model): venue = models.ForeignKey(Venue, null=False, on_delete=models.CASCADE) menu_item = models.ManyToManyField(MenuItem, null=False) This is my serializer class MenuItemSerializer(serializers.ModelSerializer): menu_category = MenuCategorySerializer() class Meta: model = MenuItem fields = '__all__' class VenueMenuSerializer(serializers.ModelSerializer): menu_item = MenuItemSerializer(many=True) class Meta: model = VenueMenu fields = '__all__' and this is my view @api_view(['GET']) def venue_menu_response_detail(request): if request.GET.get('venue'): venue_menu_list = VenueMenu.objects.filter(venue__name=request.GET.get('venue')) serializer = VenueMenuSerializer(venue_menu_list, many=True) return Response(serializer.data) this is my request http://127.0.0.1:8000/venue_menu_response_list?venue=venu_name I want to get the details of menu items associated with a single venue this query has the response of 200 OK but it is returning empty. When am querying on the basis of venue id am getting the desired result but I want to get the result on the basis of the name -
Django Database Design Problem - Multiple App Single Database
I have two django applications using the same database. These applications have their own models. Since both applications use the same database, I can authorize with common users, I can use User model as foreign key for models. Let's call these two django apps A and B. Because A and B use the same database, a user can be associated with models in both applications. If a user is associated with a model in both applications, the user I deleted from application A cannot be deleted because it is associated with a model in application B. I think I made a wrong design. How can I overcome this problem?