Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting keyError while accessing django querySet result
I'm new to django and trying out the following. Have 3 models - model1, model2, model3. Model1: class Model1(models.Model): id = models.CharField(primary_key=True, max_length=-1) Model2: class Model2(models.Model): id = models.CharField(primary_key=True, max_length=-1) Model3: class Model3(models.Model): model1 = models.ForeignKey(Model1) model2 = models.ForeignKey(Model2) Serializer3: class Serializer3(serializers.ModelSerializer) serializer1 = Serializer1(required=True) serializer2 = Serializer2(required=True) Queryset: queryset = Model3.objects.filter(model2__id=param).order_by('someField') result = Serializer3(queryset, many=True) list = [] for item in result.data: list.append(item["id"]) Now coming to the question, list.append(item["id"]) throws KeyError: 'id' as both model1 and model2 have "id" in them. I need to access id of model1. Please help me with the right way to access. -
How to make a toastr notification display on success of jquery ajax In django
So I have an ajax code that takes an Id and sends it to a view and I want display a notification using toastr if the ajax request succeed currently I have an alert() to make an alert box pop up but I want it to be toastr instead -
Create a customer in a Django webshop
I'm working on a Django webshop and want to create a customer as in the title. I've made a login form in HTML and a respond in JSON back to the server. Creating a new user in the database works fine. Then there is the customer part, because if I don't assign a customer for each individual user I get an error: "User has no customer". So I tried using this function to create a new customer in the database and assign it the newly created user. c = Customer(user="Lukas", name="Lukas", email="lukas@lukasalstrup.dk", about="Account has just been created") # Create a new customer and assign the newly created user c.save() # Save the customer in the system When I do that I get an error: Cannot assign "'Lukas'": "Customer.user" must be a "User" instance. although I have a user called Lukas in the system. This will of course be changed later, but I just want to make it work, before I put in a variable. My models.py customer class class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) about = models.CharField(max_length=100, null=True) def __str__(self): return self.name views.py register page: def registerPage(request): if … -
Filter queryset by containing a string
I need to filter all Alert objects whose substring is in the given text. class Alert(..): substring = CharField... class Article(...): text = ... I was trying __in but it doesn't seem to be working. alerts = alerts.filter(Q(substring__isnull=True) | Q(substring='') | Q(substring__in=article.text)) Do you know how to do that? I can't use contains since it's reverse. -
Django TypeError when related model is None
guys. I'm trying to generate a contract in .pdf Not every contract has a 'fiador' (guarantor), so I'm getting this error when I try to generate a contract without one. 'Contrato' (Contract) is a Model. 'Fiador' (guarantor) is another. class Fiador(PersonAttr): contrato = models.ForeignKey('Contrato', on_delete=models.CASCADE, related_name='fiador') I made a function to get the correct article (in portuguese, 'a' is for females and 'o' for males). def artigo_fiador(pk): contrato = get_object_or_404(Contrato, pk=pk) masculino = [] feminino = [] if hasattr(contrato, 'fiador'): [masculino.append(1) for f in contrato.fiador.all() if f.genero == 'Masculino'] [feminino.append(1) for f in contrato.fiador.all() if f.genero == 'Feminino'] if len(contrato.fiador.all()) > 1: if len(masculino) < 1: artigo_fiador = 'as' genero_fiador = 'as' return artigo_fiador, genero_fiador else: artigo_fiador = 'os' genero_fiador = 'es' return artigo_fiador, genero_fiador else: for fiador in contrato.fiador.all(): if fiador.genero == 'Feminino': artigo_fiador = 'a' genero_fiador = 'a' return artigo_fiador, genero_fiador else: artigo_fiador = 'o' genero_fiador = '' return artigo_fiador, genero_fiador And in my views, I'm trying to pass the function like this: from .logic import artigos as at class Contract(view): [...] artigo_fiador, genero_fiador = at.artigo_fiador(pk) data = { 'artigo_fiador': artigo_fiador, 'genero_fiador': genero_fiador, I'm using xhtml2pdf. The error i'm getting is the following: TypeError at /contrato/16/contrato_p cannot unpack … -
Passing values to form when initializing in views django?
forms.py class PermissionForm(forms.Form): def __init__(self, *args, **kwargs): self.rolesChoices = kwargs.pop('rolesChoices') super(PermissionForm, self).__init__(*args, **kwargs) print(self.rolesChoices) self.fields['roles'].queryset = self.rolesChoices print(self.fields['roles'].queryset) roles = forms.ModelChoiceField( queryset=None, widget=forms.CheckboxSelectMultiple, empty_label=None) views.py def privileges(request): rolesChoices = Permission.objects.filter( content_type=ContentType.objects.get_for_model(Group)) for role in rolesChoices: role.name = role.name.replace("group", "role") form = PermissionForm(rolesChoices=rolesChoices) return render(request, 'crm/privileges.html', {'form': form}) I am passing group objects to my form when I am initializing it in views.But I am done a small change, I replaced group with role.So the problem is role get changed with group automatically.I don't know why it's happenging. For example self.roleChoices contains Can add role When I assign self.roleChoices to self.fields['roles'].queryset it changes to Can add group -
How can I make database Mysql accepts numbers in this format (445.795.2 | 301.653.23)
When I try to save my data in database , django shows me an error and I realized that it's about this number format. could not convert string to float: '445.795.2' Even if I set the number in this way... float(445.795.2) -
How do we customise the password fields not matching in Django?
I wanted to know how do we customize the error message that shows up when we enter 2 different passwords in the password1 and password2 fields from the built-in UserCreationForm in Django. I have tried this def __init__(self,*args, **kwargs): super(CreateUserForm,self).__init__(*args, **kwargs) self.fields['password2'].error_messages.update({ 'unique': 'Type smtn here!' }) Am I doing something wrong in this process? In my template, this is the code for the error message. <span id="error">{{form.errors}}</span> Please tell me if there is another way to do this. I am using model forms. class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] def __init__(self,*args, **kwargs): super(CreateUserForm,self).__init__(*args, **kwargs) self.fields['password2'].error_messages.update({ 'unique': 'Type smtn here!' }) -
I can't get authenticatewith my api using django
I am trying to make curl requests to my api server that I have secured by this: I then use the ubuntu app for windows the following way: curl http://127.0.0.1:8000/orbitalelements/ -X POST -H 'Authorization: Token 5894b35af2dde31c2d271a9348901312d3cbe348' -H 'Content-Type:application/json' -d '{"Object":"bs", "Epoch": "49400", "TP":"1", "e":"1 ", "I":"1", "w":"1", "Node":"1", "q":"1", "QL":"1", "P":"1", "MOID":"1", "ref":"bs", "object_name":"bs"}' The token I use here is in the database: However I can't get it to accept the token: Does anyone know why this isn't working? -
How to redirect to another url after sending a POST request to admin:auth_user_password_change in Django?
I'm using the built in django admin site for the application's admin site in a sense that POST requests are built identically to its equivalent admin site, and sent to the same urls. So it's like the application admin site is just a wrapper for the admin site. My problem is, I don't know how to redirect back to url where it was originally posted. Currently it redirects to the Change User admin page. I'd like it to redirect back to the page. Here's my change-password-template.html: <div class="form-group col-sm-12" id="form-item-entry"> <form action="{% url 'admin:auth_user_password_change' user.pk %}" method="post" id="change-password-form" class="text-center border border-light p-5"> {% csrf_token %} # ... here goes the password fields <input type="submit" value="Change password" class="user-form-button"> </div> <input type="hidden" name="next" value="{% url 'change_password' id=user.pk%}"> # my attempt at trying to redirect back to the original webpage </div> </form> </div> So, it does correctly post to admin/auth/user/{{user.pk}}/password/ but instead of redirecting back to the that page it instead redirects to: admin/auth/user/{{user.pk}}/change/. How can I make it do so? -
Why should you not use the MEDIA_ROOT and MEDIA_URL convention in the production level of Django static files?
I'm trying to find the answer for the name of the question that I posted, but I couldn't seem to find the answer. I've been looking at several tutorials in Django and they keep on telling me that you should not use the MEDIA_URL and MEDIA_ROOT type of convention when you're at the production level of Django. But why is that? Is there a specific reason for it? -
Django crispy forms "helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object" when using a Layout Slice
I am getting a helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object error when trying to access a slice of the form. As shown in forms.py below, I would like to access the first Div using a layout slice (https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html), so that I can display ONLY that Div within a tab in my HTML. In ref_detail.html below, I have tried to accomplish this with {% crispy form form_helper.0 %}. I've also tried {% crispy form form_helper[0] %} but that doesn't work either. python version 3.8.3 django version 3.1.2 views.py: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from crispy_forms.utils import render_crispy_form from .models import reference from .forms import ReferenceForm def ref_detail(request, ref_id): try: ref = reference.objects.get(pk=ref_id) except ref.DoesNotExist: raise Http404("Reference does not exist") #If this is a POST request, process the form data if request.method == 'POST': #create a form instance and populate it with data from the request form = ReferenceForm(request.POST) #check whether it's valid if form.is_valid(): #process the data in form.cleaned_data as required (i.e. save to database, etc.) #... print(form.cleaned_data) new_reference = form.save() #save a new reference object to the database, from the form's data #redirect to a … -
failed (13: Permission denied) while connecting to upstream[nginx]
I am working with configuring Django project with Nginx and Gunicorn. I am following this tutorial: https://www.alibabacloud.com/blog/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04_594319 this nginx-error log 2020/11/06 15:09:33 [crit] 13566#13566: *1 connect() to unix:/root/projectdir/automation/nacm.sock failed (13: Permission denied) while connecting to upstream, client: 1xx.1xx.xx.xx, server: xxx.xxx.xxx.xx, request: "GET / HTTP/1.1", upstream: "http://unix:/root/projectdir/automation/nacm.sock:/", host: "xxx.xxx.xxx.xx" and this is my gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/otomasiJaringan/automation ExecStart=/root/otomasiJaringan/env/bin/gunicorn --access-logfile --workers 3 --bind unix:/root/projectdir/automation/nacm.sock nacm.wsgi:application [Install] WantedBy=multi-user.target this site-available/gunicorn server { listen 80; server_name xxx.xxx.xxx.xx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/projectdir/automation/website; } location / { include proxy_params; proxy_pass http://unix:/root/projectdir/automation/nacm.sock; } In the HTML page I am getting 502 Bad Gateway. What mistake am I doing? -
Django tests - a test in classA fail when i run classB (which is subclass of classA)
I have a test suite with multiple classes - ClassA and ClassB. ClassB is a subclass of classA and when I run classA tests, they all pass. However when i run ClassB, a classA test fails. I'm not sure how or why this is happening. class ClassA(TestCase): def test1(self): # run test def test2(self): # run test class ClassB(ClassA): def test3(self): # run test def test4(self): # run test python manage.py test app.tests.test_views.ClassA all pass python manage.py test app.tests.test_views.ClassB FAIL: test1 (app.tests.test_views.ClassA) Test 1 ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/test_views.py", line 1435, in test1 obj.evidence, "This is the evidence entered by user." AssertionError: 'Generic evidence' != 'This is the evidence entered by user.' - Generic evidence + This is the evidence entered by user. This is obviously a simplified example, and I know the best thing would be to not subclass ClassA in ClassB, however in my actual code there are ClassB tests that require some methods of ClassA. I understand this would be better handled with fixtures, but this is how it is set up at the moment and it would be a big revamp to rework this. My understanding is that all ClassA tests are run … -
Making migration in Django
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Am getting this error when making migrations in Postgresql -
How to filter a foreign key field in django?
I'm working on a basic social media project ideally where user gets to join a group and post posts in it. Here's the models i have created: class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through="GroupMember") class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE) class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) This works fine. Problem is when i create an instance of Post. This design lets me post in any/every group. But what i want is, to let the user post only in group(s) which he's/she's a member of. I don't know how to implement this. Help me out guys. -
Validate geometry field before saving in database
models1.py class Model1(models.Model): geometry = models.GeometryCollectionField(null=True) geojson = JSONField() model_2 = models.ForeignKey('other_app.model2', on_delete=models.CASCADE, blank=True) def save(self, *args, **kwargs): if self.geojson is not None: self.geometry = create_geometry(self.geojson) super().save(*args, **kwargs) models2.py class Model2(models.Model): geometry = models.GeometryCollectionField(null=True) 'geometry' field in Model1 is created from geojson sent by user. I have a custom validation func for geometry field in Model1 in validators.py: from django.core.exceptions import ValidationError def validate_geom(model1_geom, model2_geom): if not model1_geom.within(model2_geom): raise ValidationError("Geom1 is not within geom2") In views.py I have: class Model1Create(ListCreateAPIView): model = Model1 serializer_class = Model1Serializer def perform_create(self, serializer): instance = serializer.save() try: validate_jurisdiction(instance.geometry,instance.model2.geometry) except ValidationError as err: return Response(err.message, status=status.HTTP_400_BAD_REQUEST) But it doesn't work, model1 instance is saved in db. When I delete try-except block error is raised but I keep getting server error (500). I'd like that when validation fails (ValidationError is raised) user recieves 'Geom1 is not within geom2' message with 400 status code. -
Python for in loop only returning initial value
I have added this function to my User model in models.py. For some reason, it is not looping through the whole queryset but instead it seems it is going through one iteration cycle and then breaking out of the loop and I'm not quite sure why? This is the function: def get_following_users_posts(self): following_users = self.following.get(user=self).profile.all() for person in following_users: return person.post_set.all() And this is the output: <QuerySet []> I know that it shouldn't be returning an empty set so I added print statements to help debug: def get_following_users_posts(self): following_users = self.following.get(user=self).profile.all() print(following_users) if following_users: for person in following_users: print(person) return person.post_set.all() The output for this is: <QuerySet [<Profile: Moderator>, <Profile: Animator>, <Profile: Curator>]> Moderator <QuerySet []> How can I get it to iterate through the entire following_users QuerySet? -
Django REST How to Hash Password Correctly
I'm using dj_rest_auth to authenticate my users and there is a problem with registration. After I create a user with RegisterView that dj_rest_auth gives, django creates the user without a problem but password hashing is incorrect and thus I can not login with new created user. This is my Register View: registerview.py class UserRegisterAPIView(RegisterView): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # user.set_password(make_password(request.data.get('password'))) Didn't work user = self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(self.get_response_data(user), status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): user = serializer.save(self.request) create_token(self.token_model, user, serializer) complete_signup(self.request._request, user, allauth_settings.EMAIL_VERIFICATION, None) return user -
django.db.models.query_utils.InvalidQuery: Raw query must include the primary key
I have given customized name to id(primary key) and used as String eg custId=models.CharField(primary_key=True,max_length=10) I am using raw queries to execute SQL. But Django gives me an error raise InvalidQuery('Raw query must include the primary key') django.db.models.query_utils.InvalidQuery: Raw query must include the primary key. The Query is cust=Customer.objects.raw("""SELECT "custCity" FROM customer where "custId"= 'Cust101' """) for c in cust: print(c) I have searched for this but didn't get the expected answer. Thank you in advance. -
Render ManyToManyField by model filter - Django: 'ManyRelatedManager' object is not iterable
I am try to use the below code to render ManyToManyFields in Django Template but it's giving an error, saying that 'ManyRelatedManager' object is not iterable. template.html {% for tag in order_data.tags %} {{Tags.tag}} {% endfor %} model.py class Order(models.Model): ... slug = models.SlugField(blank=True, unique=True) view.py def order_post_view(request, customer_username, slug): .... order_data = Order.objects.get(slug=slug) required_dict = { ... 'Order': order_data, } return render(request, "themes/order/order_post_details.html",required_dict) -
In Django how do i get a choice field to update when new records are added?
I have the following form: class EditDiary(forms.ModelForm): class Meta: CHOICES = Customers.objects.all().order_by('Name') USERS = User.objects.all() model = Diary fields = ['Customer_ID', 'Staff_ID', 'Date', 'Time1', 'Time2', 'Details'] widgets = { 'Customer_ID': Select(choices=((x.id, x.Name) for x in CHOICES)), 'Staff_ID': Select(choices=((x.id, x.username) for x in USERS)), } Works great and all my customers appear in the list when i call the form Only problem is, if i add a new customer they don't appear in the choice field How do i refresh the Customer_ID choice field? Thank you -
Django transactions doesn't work with raw SQL queries
Because I'm tired of Django DB driver implicit behaviour I've the following code with a plain Postgres transaction: from django.db import transaction, connection from concurrent.futures.thread import ThreadPoolExecutor def commit_or_rollback(commit: bool): query = "COMMIT" if commit else "ROLLBACK" with connection.cursor() as cursor: cursor.execute(query) def insert(query, parameter): with connection.cursor() as cursor: cursor.execute(query, parameter) def insert_with_threads(): insert_pool = ThreadPoolExecutor(max_workers=4) query = 'INSERT INTO a_table VALUES (%s)' parameters = [...] for parameter in parameters: insert_pool.submit(insert, query, parameter) # "Main" program try: with connection.cursor() as cursor: cursor.execute("BEGIN") insert_with_threads() # Could raise any of the caught exceptions except CustomException1: commit_or_rollback(False) except CustomException2: commit_or_rollback(False) except Exception as e: commit_or_rollback(False) # Some general stuff else: commit_or_rollback(True) But nothing is rolled back, I've tried with transaction.atomic(), set_autocommit(), set_autocommit() and raw BEGIN but nothing. Is threading breaking things? Is a problem with opening multiple cursors? Any kind of help would be really appreciated -
How to print a Django List on react js frontend
I have a list as follows: ["test1","test2","test3","test4"] I have the following serializer class: class ListSerializer(serializers.Serializer): key=serializers.ListField() This is views.py file: class ListView(APIView): def get(self, request,*args, **kwargs): serializer_class = ListSerializer #print("The serializer is:",serializer_class) #print(printList()) return Response({"keywords":printList()}) Under the frontend,I have the following method for API: static listFormUser() { const TOKEN = getItem("accessToken"); return axios({ method: "get", url: `${BASE_URL}/api/listtopics/`, headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Token ${TOKEN}`, }, }).then((res) => res); } } Following is my React class code for displaying the list class printForm extends Component { constructor(props){ super(props); this.state={ items:[], isLoaded:false, key:"", } } componentDidMount(){ this.setState({ isLoding: true }, () => { RestAPI.listForm() .then((response) => { let keywordArray = []; for (let i = 0; i <= response.data.length; i++) { keywordArray.push({ text: response.data[i].key, }); } if (response.data.length === 0) { this.setState({ isData: false, }); } this.setState({ isLoding: false, items: keywordArray, }); }) .catch((error) => { this.setState({ isLoding: false }); handleServerErrors(error, toast.error); }); }); } render(){ return(<ListGroup> <ListGroupItem>Cras justo odio</ListGroupItem> <ListGroupItem>Dapibus ac facilisis in</ListGroupItem> <ListGroupItem>Morbi leo risus</ListGroupItem> <ListGroupItem>Porta ac consectetur ac</ListGroupItem> <ListGroupItem> {items.map(item => { return <li>{items[0]}</li>; })} </ListGroupItem> </ListGroup> ) } The list is not printed.What could be the error here? I have tried many ways but none of … -
How to add styling to the imagefield in django template?
Here i am using bootstrap template but i don't understand how can my form fields work with this template ,Since i have never styled image field before in django , Please tell me how can i upload image by clicking on image icon ? form.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('tag',"title","description","image_data") widgets ={ 'title' : forms.TextInput(attrs={'class':'textinputclass','class':'control-flow'}), 'description':forms.Textarea(attrs={'class':'postcontent'}), } post_form.html <div class="box" > <form method="POST" enctype="multipart/form-data">{% csrf_token %} <textarea class="form-control no-border" rows="3" placeholder="Type something..."></textarea> <div class="box-footer clearfix"> <button class="kafe-btn kafe-btn-mint-small pull-right btn-sm">Upload</button> <ul class="nav nav-pills nav-sm"> <li class="nav-item" ><a class="nav-link" href="#"><i class="fa fa-camera text-muted"></i></a></li> <li class="nav-item"><a class="nav-link" href="#"><i class="fa fa-video text-muted"></i></a></li> </ul> </div> </form> </div>