Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fixing a typo in models.py and migration for django python project
I'm working on my first django project following along with a youtube tutorial. In models.py while following along I made a typo... crated_at = models.DateTimeField(default=datetime.now) "crated_at" should be "created_at". The typo is reflected in my migrations. I tried changing both models.py and the migrations py file but it leads to an error so I changed it back to "crated". I think the problem is that the database saves the information as "crated_at". I don't want to delete the migration and redo the migrations because from what I read the database is already labeled and it won't fix the problem. Also, I don't mind if it's left as "crated_at" in models.py and the migrations, but at least I would like it to see "created at" when I'm signed in as admin. I want to move on but when I sign in as admin "crated at" is staring me in the face. I feel like this is a good learning moment. Thank you. -
Python DJango avoid assigning variables
def myview(request): category="" brand="" series = "" model="" resolution="" ram="" #some process return render(request ,'mypage.html',{'category':category,'brand':brand,'series':series 'model':model,'resolution':resolution,'ram':ram} Sometimes in my Django projects I have to assign these variables first in my views because of the returning template tags. But doing this way is kinda ugly. Can I avoid assigning these variables in my views? -
Django - Storing user-defined querying logic in a model
I'm making a school app with DRF. Teachers are able to create Exercises and associate them with Tags. An Exercise is thus in m2m relationship with Tag: class Exercise(models.Model): MULTIPLE_CHOICE_SINGLE_POSSIBLE = 0 MULTIPLE_CHOICE_MULTIPLE_POSSIBLE = 1 OPEN_ANSWER = 2 JS = 3 C = 4 EXERCISE_TYPES = ( # ... ) DRAFT = 0 PRIVATE = 1 PUBLIC = 2 EXERCISE_STATES = ( # ... ) exercise_type = models.PositiveSmallIntegerField(choices=EXERCISE_TYPES) state = models.PositiveSmallIntegerField(choices=EXERCISE_STATES, default=DRAFT) text = models.TextField(blank=True) tags = models.ManyToManyField(Tag, blank=True) class Tag(models.Model): name = models.TextField() Teachers can use tags to create quizzes that randomly select exercises with certain tags. In order to do this, there's a Rule model, to which one or more Clauses are related. A Clause is in a m2m relationship with Tag. Let's say a Rule has two Clauses associated; the first clause is associated to tag t1 and t2, and the second clause is associated to t3 and t4. The Rule logic will pick an exercise that has these tags: (t1 OR t2) AND (t3 or t4) class EventTemplateRule(models.Model): pass class EventTemplateRuleClause(models.Model): rule = models.ForeignKey( EventTemplateRule, related_name="clauses", on_delete=models.CASCADE, ) tags = models.ManyToManyField(Tag, blank=True) The actual query is constructed at runtime using repated filter applications and Q objects. … -
Django django-otp non-admin
The following is an excellent article to implement django-otp for admin pages. I tried and it works like a charm. Adding the following two lines in project urls.py seems to do the trick for admin pages: from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite OTP for admin I am using django-volt-dashboard. What changes are needed for a similar functionality to access non-admin pages with a regular user? -
Filter object and order by number of filters matched
I have the objects >>> Post.objects.create(name='First post', tags=['tutorial', 'django', 'example']) >>> Post.objects.create(name='Second post', tags=['thoughts']) >>> Post.objects.create(name='Third post', tags=['thoughts', 'django', 'example']) I want to filter the Post objects to match a series of tags: >>> filtered = Post.objects.filter(tags__in=['thoughts', 'django', 'example']) Is there a way to order these results by the number of filters they matched? Wanted result: >>> filtered[0] <Post: Third post> >>> filtered[1] <Post: First post> >>> filtered[2] <Post: Second post> Actual result: >>> filtered[0] <Post: First post> >>> filtered[1] <Post: Second post> >>> filtered[2] <Post: Third post> I'm using Django 3.2.14 -
Django ORM query on fk set
I have a problem with lookup that looks for a value in related set. class Room(models.Model): name = models.Charfield(max_lentgh=64) class Availability(models.Model): date = models.DateField() closed = models.BooleanField(default=False) room = models.ForeignKey(Room) Considering that there is one availability for every date in a year. How can use ORM query to find whether room withing given daterange (i.e. 7 days) has: availability exist for every day within given daterange none of the availabilities has closed=True I was unable to find any orm examples that check whether all objects within daterange exist -
Reverse for 'profileEditor' with no arguments not found. 1 pattern(s) tried: ['regisApp/(?P<pk>[0-9]+)/profileEditor/\\Z']
Hello every one like a lot of people I'm having this ( Reverse for 'profileEditor' with no arguments not found. 1 pattern(s) tried: ['regisApp/(?P[0-9]+)/profileEditor/\Z'] ) I've been trying some of the solution given to other people but with no luck. This is what I'm trying to pass in my home.html menu, is a page were the user can edit their profile <li><a href="{% url 'profileEditor' %}">Edit Profile</a></li> in my url.py I have this path path('<int:pk>/profile_Editor/', editProfilePage.as_view(), name="profileEditor"), And this is my views.py class class editProfilePage(generic.UpdateView): model = Profile template_name = "registration/profileEditor.html" fields = [ 'bio', 'profile_pic', 'website_url', 'facebook_url', 'instagram_url', 'github_url' ] success_url = reverse_lazy('home') I don't get it cuz I did the same process for some of the other pages and they are working fine -
Is there a way to get a function from a user in python with different python functions(ie. if with personalized format)
I'm making a django model that takes a string from the user and that string would be something like '(some var)+15+IF((condition),(passed),(not passed))' and I want it to solve all of this and probably add other personalized functions in the future so mainly for the if this would initially not work with eval from what I looked at. -
Is there a way to create an on_delete function that uses info from the specific model that holds a foreign key in django?
I'm doing one of the problems in the cs50 web course and I made a model for a listing on an auction site. For the sake of avoiding iterating through all bids on a listing, each listing has a Foreign Key called 'current_bid' that points to the latest bid. If the bid were to be deleted though, I want to be able to set the current bid to be the bid that came before it. I've tried several approaches but the one that felt closest to working was making a function local to the model class that gets the lastest bid and tried to make it work by having on_delete call set(last_bid). def last_bid(self): bids = self.bids last = None for bid in bids: if last is None: last = bid elif bid > last: last = bid return last current_bid = models.ForeignKey('Bid', null=True, blank=True, on_delete=SET(last_bid), related_name="running_bids") It doesn't work because calling last_bid this way doesn't give it the needed 'self' parameter. Is there really no way for me to get a reference to the specific listing when the bid it's holding gets deleted? -
How to fix PostgreSQL encode
I am trying to migrate a database from a local computer(Windows, SQLite3) to a server(Ubuntu 20, PostgreSQL). I created a JSON dump from local SQLite3 base. python manage.py dumpdata > dump.json On the server, I enter into the shell and executed the commands from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() And when i'm try refill database python manage.py loaddata dump.json The console responds with this UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I would be very grateful if you could explain to me how to fix the problem. -
scrollHeight yielding inconsistent results
I came with an idea to use top-bottom pagination. My plan was to use hidden class on the bottom paginator element if ListView fits into the user's viewport. Worked fine but accidentally I found out that once per +/- twenty times it just doesn't work. Using console log I noticed that scrollHeight is yielding inconsistent results, viewportHeight on the other hand works like a charm every time. Django template: <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'styles/elements.css' %}"/> <link rel="stylesheet" href="{% static 'styles/main.css' %}"/> <script defer src="https://unpkg.com/phosphor-icons"></script> <script defer src="{% static 'js/project-list.js' %}"></script> <title>Browse Projects</title> </head> JS file: 'use strict'; const tagFilterForm = document.getElementsByClassName('tag-filter-form')[0]; const paginatorLinks = document.getElementsByClassName('paginator-link'); const paginatorBottom = document.getElementsByClassName('paginator--bottom')[0]; // Prevent from wiping filters during page change: if (tagFilterForm) { for (let i = 0; i < paginatorLinks.length; i++) { paginatorLinks[i].addEventListener('click', function (e) { e.preventDefault() console.log('clicked') const pageNumber = this.dataset.page tagFilterForm.innerHTML += `<input value="${pageNumber}" name="page" hidden>` tagFilterForm.submit() }); } } // Add bottom paginator if doc height > viewport height: const documentHeight = document.documentElement.scrollHeight; const viewportHeight = window.innerHeight; console.log(documentHeight, … -
Django admin panel show ForeignKey data
I'm trying to display more information in a admin panel and can't I have two models with foreign Key I trying show streets list and add to street name City name class Street(models.Model): name = models.CharField(max_length=50, verbose_name='Street') code = models.IntegerField() city = models.ForeignKey('City', on_delete=models.PROTECT, null=True) class Meta: managed = True db_table = 'street' def __str__(self): return self.name + f'({self.city.name})' class City(models.Model): name = models.CharField(max_length=50, verbose_name='City') code = models.IntegerField() class Meta: managed = True db_table = 'city' def __str__(self): return self.name+ f' ({self.code})' -
django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve. How to solve this issue?
Can some body help me solve this issue. Why am i getting this error? I have db in .env host and links, network in docker-compose file too. I am not being to figure out where the issue is being raised. Here is my docker-compose file. version: "3.9" volumes: dbdata: networks: django: driver: bridge services: web: build: context: . volumes: - .:/home/django ports: - "8000:8000" command: gunicorn Django.wsgi:application --bind 0.0.0.0:8000 container_name: django_web restart: always env_file: .env depends_on: - db links: - db:db networks: - django db: image: postgres volumes: - dbdata:/var/lib/postgresql environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} ports: - 5430:5432 networks: - django container_name: django_db here is my .env with database settings DB_USER=admin DB_NAME=test DB_PASSWORD=admin DB_HOST=db DB_PORT=5432 DB_SCHEMA=public CONN_MAX_AGE=60 -
AssertionError with assertIn; Django SafeString
I'm looking to understand why a string returned from a template's render_to_string method causes inconsistent testing when testing in a manner using self.assertIn() in the below TestCase. All the strings being checked for pass with the exception of "=question_id_1" and "id=question_id_1". There appears to be an issue adding question_id_1 after the equal sign. What explaination is there for this to fail? https://docs.djangoproject.com/en/3.2/topics/templates/#django.template.loader.render_to_string https://docs.djangoproject.com/en/4.0/ref/utils/#django.utils.safestring.SafeString class SafeString A str subclass that has been specifically marked as “safe” (requires no further escaping) for HTML output purposes. class TestUserQuestionProfileTemplate(TestCase): @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="Tag1") tag2 = Tag.objects.create(name="Tag2") user = get_user_model().objects.create_user("ItsNotYou") profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Test Question ZZZ", body="Post content detailing the problem about Test Question ZZZ", profile=profile ) cls.question.tags.add(*[tag1, tag2]) cls.template = render_to_string( "authors/questions.html", {"question": cls.question} ) def test_template_profile_questions_listing(self): self.assertIn("=", self.template) <<< pass self.assertIn("id", self.template) <<< pass self.assertIn("question_id_1", self.template) << pass self.assertIn("id=", self.template) <<< pass self.assertIn("=question_id_1", self.template) << fail self.assertIn("id=question_id_1", self.template) << fail The template authors/questions.html is written as: <div id="question_id_{{ question.id }}"> </div> The output of self.template in the test returns: <div id="question_id_1"> </div> As the test is ran, it returns the following assertion errors: self.assertIn("=question_id_1", self.template) AssertionError: '=question_id_1' not found in '\n<div id="question_id_1">\n\n</div>\n' self.assertIn("id=question_id_1", self.template) AssertionError: 'id=question_id_1' not found … -
Simulate CSRF attack in Django
I'm trying to get an understanding of how CSRF tokens work, currently my goal is to create a situation where the CSRF attack is possible. I'm hosting two Django apps locally on different ports. I access one by localhost:8000, the other by 127.0.0.1:5000 -- that ensures cookies are not shared between apps. There's an API view class ModifyDB(APIView): def post(self,request,format=None): if request.user.is_authenticated: return Response({'db modified'}) else: return Response({'you need to be authenticated'}) which shouldn't be accessed by unauthenticated users. The "malicious" site has a button that's supposed to trigger the attack when a user is logged on the target site: const Modify = () => { const onClick = async e => { e.preventDefault(); const instance = axios.create({ withCredentials: true, baseURL: 'http://localhost:8000', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) const res = await instance.post('/api/modifydb'); return res.data } return ( <button class = 'btn' onClick = {onClick}> send request </button> ) } My authentication settings are as follows: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'my_proj.settings.CsrfExemptSessionAuthentication', ], } where CsrfExemptSessionAuthentication is a custom class that disables csrf protection for my educational purposes: class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return django.middleware.csrf.CsrfViewMiddleware is also disabled. Both CORS_ALLOW_ALL_ORIGINS and CORS_ALLOW_CREDENTIALS are set to true. My first … -
Django prefetch_related nested models
I want to do a 3 lvl prefetch_related but I can't make it work. views.py: queryset = obj.answer.all().prefetch_related(Prefetch('question ', queryset=Question.objects.prefetch_related(Prefetch('orderedquestion', queryset=OrderedQuestion.objects.prefetch_related('select_set'))))) return AnswerSerializer(queryset, many=True).data And on my Serializers.py I call it like that: json['name'] = answer.question.orderedquestion.select_set.get(id=i).name I don't know if this metters but my OrderedQuestion class inherits from Question. How can I fetch select_set on the first query so my serializer stop doing N queries for each object? Thank you so much for the help. -
Django user doesn't inherit its groups permissions
In my Django project my jack user is in a group called 'Personals'. 'Personals' group has a permission named 'personal'. But jack doesn't inherit that permission from its group. How can I fix this problem? >>>jack = User.objects.get(username="jack") >>>jack_permissions = Permission.objects.filter(user=jack) >>>print(jack_permissions) <QuerySet []> #It gives a emty query. >>>jack_group = jack.groups.all() >>>print(jack_group) Personals >>>jacks_group = Group.objects.get(name="Personals") >>>jacks_groups_permissions = jacks_group.permissions.all() >>>print(jacks_groups_permissions) <QuerySet [<Permission: auth | user | The Personals>]> #The Group has the permission The Personals -
Django staticfiles not loading in AWS ec2
I've deployed a django webiste in AWS ec2 with the help of this digitalocean blog but the static files like css and javascripts are not loading after deployment. This is my django static code: STATIC_URL = '/static/' MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] and this is my nginx code: server { listen 80; server_name mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { root /home/sammy/project/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And I'm using AWS S3 to host my static files. -
Build a query to get grouped average of multiples many to one instances
I'm having two models : class Club(models.Model): club_tag = models.CharField(primary_key=True) class Player(models.Model): rating = models.FloatField(default=0) club = models.ForeignKey(Club, ...) My objective is to get the top 10 of clubs with the best average rating players, in decreasing order. In this situation the Club has an average rating (Which is its player's average) and is ranked thanks to it. I'm having a hard time figuring out how to pull this request, can someone give me directions please ? Thanks -
Category API for products django
I have two models: Category, Products. And I want to create a separate url link like http://127.0.0.1:8000/api/categories/sneakers for each category to retrieve products from different APIs. Using foreign key I can separate them but don't really know how to give them a url. Could you help me with this, please? -
Cannot save Celery object in Django migrations
The problem is as follows I am using json to deserialise and populate Celery model with Intervals, Crontabs and vital PeriodicTasks serialisation / deserialisation works totally fine The problem is that if I run the following function from elsewhere in code or from Django shell - everything is working totally fine, but when I put it inside migration - objects are not getting saved, although I see with loggers that all steps are being passed Here is this simple function: for obj in serializers.deserialize("json", json_with_tasks): obj.save() -
In django how to generate a pdf file from django template maintaining the css style?
I have created a pdf file with the Django template. In the template whatever CSS is applied is not showing in generated pdf. Here is the code I have used : from io import BytesIO from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.shortcuts import render def home(request): pdf = render_to_pdf("abc.html") return HttpResponse(pdf, content_type='application/pdf') def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else return None -
Why is the Middleware not processed on 404 page in Django?
So I've set up a path in my URL config: path( "kitten/", views.Kitten.as_view(), name="kitten", ), and a handler for missing URLs to the same view. handler404 = views.Kitten.as_view() I have some middleware which sets some context data: class CookieConsentMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_template_response(self, request, response): response.context_data["hasCookie"] = False return response and the view is very straightforward, class Kitten(TemplateView): template_name = "kitten.html" and the template prints the value of hasCookie. Visiting kitten/ correctly displays the value of hasCookie, but visiting a URL that doesn't exist, displays no value for hasCookie (whilst showing the right template) Adding debugging statements to the middleware, it becomes apparent that whilst process_view, process_template_response and process_exception are called for kitten/, none of these are called for URLs that don't exist, so no code is called to set the value of hasCookie. (__init__ is called regardless at app startup) Why does it not call the middleware when the URL is not found in the URLconf? -
Django query for column value search?
What is the Django query for this? DB data - col1 | Col2 ------------------------- sahil1 | Cat 1.2.3 sahil2 | 1.2.3-XY2 sahil3 | 9.8.7,1.2.3,11.12.13 sahil4 | 1.2.3 sahil5 | 9.8.4,1.2.3-XY2,9.8.7 sahil6 | Cat 1.2.3,9.8.2,1.2.3 I only need record that contain "1.2.3" values not like - ("Cat 1.2.3" or "1.2.3-XY2" or any such value). And pattern "1.2.3" can be anywhere in column where column value can have comma separated values too. Desired Result - col1 | Col2 ------------------------- sahil3 | 9.8.7,1.2.3,11.12.13 sahil4 | 1.2.3 sahil6 | 1.2.3-XY2,9.8.2,1.2.3 When i am performing below Django query - col2_count = TableName.objects.filter(col2__contains="1.2.3") Getting all record but i only need record that contain "1.2.3" values not like - ("Cat 1.2.3" or "1.2.3-XY2" or any such value). How do I implement this in Django? -
decode() function is not working "AttributeError: 'str' object has no attribute 'decode'"
Hi I am trying to fix my test case buy decode function is not working this is my code in test Django ```class RefreshView(APIView): serializer_class = RefreshSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try: active_jwt = Jwt.objects.get( refresh=serializer.validated_data["refresh"]) except Jwt.DoesNotExist: return Response({"error": "refresh token not found"}, status="400") if not Authentication.verify_token(serializer.validated_data["refresh"]): return Response({"error": "Token is invalid or has expired"}) access = get_access_token({"user_id": active_jwt.user.id}) refresh = get_refresh_token() active_jwt.access = access.decode() active_jwt.refresh = refresh.decode() active_jwt.save() return Response({"access": access, "refresh": refresh})``` enter image description here