Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rest API: Why is object doesn't findable in 'create' function?
For example, here is my all data : IMG1 My viewset : class CardCheckViewSet(viewsets.ModelViewSet): serializer_class = CardCheckSerializer queryset = CardCheck.objects.all() def create(self, request): for obj in CardCheck.objects.all(): print(obj) return super().create(request) And here is the data after I post something in it: IMG2 There should be 4 objects but this is what I got printed : CardCheck object (30) CardCheck object (34) CardCheck object (44) There is not the posted data as you see. Why is that data doesnt appears in here? What can I do about it? -
Django give a field default value = pk
I'm trying to give a field in Django a default value = value of pk, is this possible ? I've found an old question about giving a field default = value of another field but it doesn't really help when working with pk value : How do I set default field value to value of other field in a Django model? Basicly is something like this possible using pk instead of "name" variable ? : class MyModel(models.Model): name = models.CharField(max_length=50) fullname = models.CharField(max_length=100,default=name) def clean(self): self.fullname=name Thanks. -
What comes first OOA and OOD or Database design in Django? Would the answer change if
My first question, so please let me know if I'm doing something wrong. I'm studying OOA and OOD, GoF patterns, even reading some examples of Fowler OO "patterns"... But I was missing database design, and many other questions came up with the perssistence topic: schema, would it normalize, would it scale? If I'm going to develop an app that manages and Inventory of products, What should be the propper way to start with it in terms of design? OOD first or Dabase design first? Would the answer change if I'm using Django or Flask? I know maybe I've been failing at doing things properly in the past for so long that I've developed reflexes to answer to myself questions like this ones. I usually developed the database schema first and then relied on ORM. But I made many mistakes that way, some related to bad OOD and solid principles. In the other hand, I'm worried that if I use the OOA and OOD approach first, I could end up making wrong choices in the schema, like for example bad use of EAV (Entity-Attribue-Value model). The answer to some other similar questions like mine were just to do what fits best … -
Pass an object into Ajax
This is a two part question. The first part is being able to send an array of objects within an object into ajax to send to python(django framework). let object = { "value1": 1, "value2": 2, "arrOfObject": [ { "value3": 3, "value4": 4, }, { "value3": 5, "value4": 6 }] } let formData = $("form").serialize(); data = formData + '&' + jQuery.param(object) $.ajax({ url: "someurl", method: 'post', data: data }) The second question is the passing where arrOfObject is actually coming for django to begin with. Passing along the data before the template was rendered and being sent to another function. Of course the way that I have it right now is using the template tags to build the array of objects but was wondering if I can take the data passed in without any other iteration of the data. I would like to avoid something like let arrOfObjects = [] {% for data in object %} let data_object = { "value3": '{{ data.value3 }}', "value4": '{{ data.value4 }}' } arrOfObjects,push(data_object); {% endfor %} -
Django Rest Framework combine field and non field errors
I have a model serializer for changing the email and password. class ChangeEmailSerializer(ModelSerializer): class Meta: model = CustomUser fields = ['email', 'password'] def update(self, instance, validated_data): instance.email = validated_data.get('email') return super().save_instance(instance) How do I combine the a field error from EmailField with a non field error from the validate function used to check the user password? -
How to disable and modify password validation in Django
I want the end-user to set the password like a numeric pin of min & max length to 6 characters while registration. e,g: 234123 Yes, this can be insecure but the project needs to do it with 6 digit pin. As AUTH_PASSWORD_VALIDATORS doesn't allow to do it. AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] So how to disable and modify password validation in Django. Without changing the AUTHENTICATION_BACKENDS If we have to change the AUTHENTICATION_BACKENDS, then how to achieve it. -
How do I fix Permission Error (errno 13) Permission Denied
When I try to open the website using http://localhost:8000/admin/ i get the Permission denied error. This is what i get: [Errno 13] Permission denied: 'C:\\Users\\gvast\\OneDrive\\Documents\\learning_log\\learning_logs\\templates\\learning_logs\\index.html' Exception Location: C:\Users\gvast\OneDrive\Documents\learning_log\ll_env\lib\site-packages\django\template\loaders\filesystem.py, line 23, in get_contents -
Filter Query with Django-Filter but Return Custom JSON
I want to be able to pass a query via an endpoint (such as /api/generate-team/?rarity=Gold), have that filter a queryset and then return custom JSON based on some calculations that occur. Essentially, the query will contain filtered data from the PlayerProfile model. Data from the PlayerProfile's is then calculated and a custom JSON response is returned. I already have a FilterSet built for another view that contains that exact same filters we need, so I'd like to reuse it. Here is a condensed version of the filter (this filter works great with the other view I'm using it for): class PlayerProfileFilter(django_filters.FilterSet): rarity = CharInFilter(field_name='rarity', lookup_expr='in') card_id = CharInFilter(field_name='card_id', lookup_expr='in') max_overall = django_filters.CharFilter(field_name='overall', lookup_expr='lte') ... class Meta: model = PlayerProfile This is what I'm trying to do with the view: class GenerateRosterView(some-kinda-viewset): queryset = PlayerProfile.objects.all() filter_backends = (django_filters.DjangoFilterBackend, filters.SearchFilter,) filterset_class = PlayerProfileFilter def do_some_calculations_to_filtered_query_set(): doSomething(queryset) return {"calculations": 1} I'm having issues passing a filtered query to a function and returning a custom JSON response. -
None instead of empty Object instance?
I'm trying to create Secret Santa web site using Python Django. Issue I have is when there's odd number of participants. I'm using Django's built in User model and pairing its instances as matches for the game. In case of odd number, there will be a participant without match. Is there any way to store None in case of empty instance without raising ValueError? Here's my code: models.py class Participants (models.Model): giver = models.OneToOneField(User, on_delete=models.CASCADE, null = True, blank = True, related_name = "giver") receiver = models.OneToOneField(User, on_delete=models.CASCADE, null = True, blank = True, related_name = "receiver") def __str__(self): return self.receiver.username views.py def matchPairs(request): participants = User.objects.all().exclude(is_superuser=True) participants_names = [p.id for p in participants] i = 0 Givers = [] Receivers = [] if request.method == "POST": [givers, receivers] = pairs_generator.generate_match(participants_names) while i < len(receivers): if givers[i] == None: Givers.append(None) else: Givers.append(User.objects.filter(pk = givers[i])) Receivers.append(User.objects.filter(pk = receivers[i])) Participants.objects.create(giver = Givers[i], receiver = Receivers[i]) messages.success(request, "Matching successful! Here's the list.") return redirect('participants') else: messages.error(request, "Woops. Something went wrong. Please try again.") return redirect('participants') generate_match.py def generate_match(participants_names): givers = [] receivers = [] flag = None random.shuffle(participants_names) i = 0 while i < len(participants_names): if (is_even(participants_names)): print(f'{participants_names[i]} exchanges gifts with {participants_names[i + … -
Django Hyperlinks
How can I make a hyperlink go back to /articles/testing rather than staying as /categoryview/demo/articles/testing. The code I am using to create the hyperlink is View /categoryview/demo is the path of the current page. Thanks for your help. -
django - filter problem for self compare of model
in django via python 3, i want my drivers can join to a live request of customer that radius of cover defined by our customer. i have these code: pnt = GEOSGeometry('SRID=4326;POINT(%s %s)' % (supply.data['gpsCoordinate']['coordinates'][0], supply.data['gpsCoordinate']['coordinates'][1])) demands = DemandModel.objects.annotate( distance=Distance('gpsCoordinate', pnt), ).filter(distance__lte=D(km=DemandModel.allowedDistance), locationType = location.locationType, demandType = location.supplyType ).exclude(userProfile = location.userProfile) i need driver location checked by user allowedDistance and if lower than rage, added. so my problem is in km=DemandModel.allowedDistance. that not work and get these error: float() argument must be a string or a number, not 'DeferredAttribute' anyone can guide me? -
DRF - Custom serializer - prefill data by request.user
I have a model: class Income(...): user = ForeignKey(User....) # not null type = ... amount = ... And a special non-model serializer that should (besides other things) create Income objects for this user. class WelcomeWizardSerializer(serializers.Serializer): applicant = serializers.HiddenField(default=serializers.CurrentUserDefault()) applicant_incomes = IncomeSerializer(many=True, required=True) Obviously, I need to tell IncomeSerializer to use applicant as user. Otherwise WelcomeWizardSerializer returns errors: {'applicant_incomes': [{'user': [ErrorDetail(string='Toto pole je povinné.', code='required')]}, {'user': [ErrorDetail(string='Toto pole je povinné.', code='required')]}]} How can I do that? @action(['POST'], detail=False, url_path='from-welcome-wizard') def from_welcome_wizard(self, request, pk=None): serializer = WelcomeWizardSerializer(context={'request':request}, data=request.data) if serializer.is_valid(): # not valid serializer.save() I know I should get applicant (as I don't want to use CurrentUserDefault in IncomeSerializer) and add it to the data['incomes'] objects but I don't know where/when is the right place/time. -
MultiValueDictKeyError in Django REST APIView POST request
I am trying to write a POST request for a game API and am passing some data from the GET request and some through this POST request. However, I keep getting the following error: MultiValueDictKeyError 'gameround' What am I doing wrong here? def post(self, request, *args, **kwargs): if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk gameround = request.GET['gameround'] random_resource = request.GET['resource'] created = datetime.now() score = 0 origin = '' name = request.POST['name'] language = request.POST['language'] user_input_tag = Tag.objects.create(name=name, language=language) tag_serializer = TagSerializer(user_input_tag) if Tagging.objects.all().filter(tag=user_input_tag).exists(): # if tagging like this exists, save tagging anyway and leave tag unchanged score += 5 user_input_tagging = Tagging.objects.create(user_id=current_user_id, gameround=gameround, resource=random_resource, tag=user_input_tag, created=created, score=score, origin=origin) tagging_serializer = TaggingSerializer(user_input_tagging) return Response({'tag and ': tag_serializer.data}, {'tagging': tagging_serializer.data}) elif not Tagging.objects.all().filter(tag=user_input_tag).exists(): # save tagging otherwise and del tag? user_input_tagging = Tagging.objects.create(user_id=current_user_id, gameround=gameround, resource=random_resource, tag=user_input_tag, created=created, score=score, origin=origin) user_input_tagging.save() tagging_serializer = TaggingSerializer(user_input_tagging) return Response({'tagging only': tagging_serializer.data}) -
cant get the tag of a post displayed django
I've built a blog kinda app and there is a location section. I can add a location for a post when I create it (with django taggit) and when I search for it let's say Paris http://127.0.0.1:8000/tag/paris/ it shows me all the posts that have that tag. the thing i couldn't add is that on my homepage right next to the username I want to show the location that post has and when I click it I want to see the other posts that have that tag, so if post1 has the tag of Paris i'll click on it and it'll show me http://127.0.0.1:8000/tag/paris/ I've tried this just to show the tag the post has location:<strong> {{post.tags}} </strong></a>--> but it says location: blog.Post.None btw http://127.0.0.1:8000/tag/paris/ and all other tags work. I can see all the posts that have that tag when I search this in the search bar. I just can't seem to put the link to it anywhere. i'll try to put just the relevant parts of the code. home.html {% for post in posts %} <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> location:<strong> {{post.tags}} </strong></a>--> {% endfor %} views.py class TagIndexView(ListView): model = Post paginate_by = … -
Redirect back to detailview
I have a detail view which displays details from one model. But on the detail view I also have a button which leads to a create view, which creates an object in another model. I want to redirect back the user to the detail view they was on before they created the object after they have created their object. I have tried this piece of code in the create view. def get_success_url(self): return reverse_lazy('article-detail', kwargs={'pk': self.object.pk})' The problem however, is that this does not find the right primary key of a specific article. -
JavaScript console.error redirect to file in Daphne Django application
I am using systemd (on Debian) to launch a shell script (as me as a user): startup.sh: #/bin/bash daphne -b '0.0.0.0' -p 8000 cartsProject.asgi:application 2> /tmp/log.out In my Python (Django) application I need to output to stdout and have it show up on the screen (tty1), which is working fine. The problem is that the JavaScript console.error() messages are also showing up on the screen even though I am redirecting stderr when launching Daphne. Is there an easy way to have the JavaScript stderr also redirect to a file? (could be the same or a different file than /tmp/log.out) -
Django poetry cannot find version of desired pylib
I am working on a Django application (python 3.8.12, Django 3.1) that is set up with poetry. The application is Dockerized. In my pyproject.toml file, I add a pylib (It happens with any lib, for example with django-mirage-field) django-mirage-field = "^1.3.0" And I get the error "... which doesn't match any versions, version solving failed". I can successfully install the specified version with pip install .... Any ideas? For the record, I don't have much Django experience so this might something very trivial, but I have not been able to resolve this yet :) -
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(): # …