Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django EMAIL_CONFIG
when the password contains forward slash "/" this function bring error EMAIL_CONFIG = env.email_url('DD_EMAIL_URL', default='smtp://username:xseebds/wdsdff@email-smtp.eu-central-1.amazonaws.com:25') it brings this error ValueError: invalid literal for int() with base 10: 'B******3' ERROR: Service 'nginx' failed to build: The command '/bin/sh -c env DD_SECRET_KEY='.' python3 manage.py collectstatic --noinput && true' returned a non-zero code: 1 I edited in settings.dist.py EMAIL_CONFIG = env.email_url( 'DD_EMAIL_URL', default='smtp://AC@:B3/x***************+9**G@email-smtp.eu-central-1.amazonaws.com:25') -
Reverse for 'new_entry' with arguments '(1,)' not found. 1 pattern(s) tried: ['new_entry/<int:post_id/$']
I am currently working on a tutorial in the "Python Crash course" Book. The tutorial is about creating a "blog" Webapp with Django. The idea is create an app called blogs in the project and a model called BlogPost. The model should have fields like post, text and date_added. Create a superuser for the project, and use the admin site to make a couple of short posts. Make a home page that shows all posts in chronological order. Create a form for making new posts and another for editing existing posts. Fill in your forms to make sure they work. I am currently stuck at editing an existing Entry form and receive an Error, when I run http://127.0.0.1:8000/posts/1/ I have read the answers for questions similar to mine, but the solutions they propose have already been reviewed and it still gives me an error. I do not understand why. If anyone can help me I would really appreciate it. views.py from django.shortcuts import render, redirect from .models import BlogPost, Entry from .forms import BlogPostForm, EntryForm def index(request): """The home page for blog.""" return render(request, 'blogs/index.html') def posts(request): """Show all posts.""" posts = BlogPost.objects.order_by('date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', … -
Why translations do not work in ModelChoiceField?
I am using Django and I have that code : from django.utils.translation import ugettext_lazy as _ from django import forms auth_d = forms.ModelChoiceField( label=_('Water'), ) I wrote the translations in the django.po file and then I typed that compilesmessages and I have not the translation. Could you help me please ? Thank you very much ! -
Possible design schema to avoid concatenating joined query results
I have a permission model in which I have Users, Groups, Resources and Entities. Each user belongs to one or many groups, and each group can access a specific set of resources and entities. To simplify, I chose to deal with resources and actions as a single string, like resourceA.create and resourceB.delete. So I came up with: class User: id = db.Column(db.Integer) name = db.Column(db.String) class Groups: id = db.Column(db.Integer) name = db.Column(db.String) class UserGroups: id = db.Column(db.Integer) group_id = db.Column(db.Integer) user_id = db.Column(db.Integer) class Permissions: id = db.Column(db.Integer) group_id = db.Column(db.Integer) resources = db.Column(JSONB) # List of strings in the format of "resource.action" entities = db.Column(JSONB) # List of strings in the format of "entity" # The permission table would be something like: "master" | ["*"] | ["*"] "admin" | ["resourceA.create", "resourceA.read", "resourceA.delete", "resourceA.update"] | ["entityC", "entityD"] "member" | ["resourceB.create", "resourceB.read", "resourceB.delete"] | ["entityA", "entityB"] This would be pretty straighforward if I had a simple relationship between users and groups, but gets messy if users <> groups is a many-to-many relationships (one user can be a part of many groups). I guess could solve this with a fairly complex query, joins users, roles, permissions, but than I would have … -
Django - Not sure why my form isn't working
I have multiple forms with large numbers of inputs. I'm not seeing any errors but nothing is showing up in my database either. I also don't really understand the whole URL path thing. This is the relevant part of my models.py file: class example_model(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) datetime = models.DateTimeField(default=timezone.now) boolean = models.BooleanField(default=True, blank=False) dec = models.DecimalField(max_digits = 100, decimal_places = 5, default=1) dec_unit = models.TextChoices('dec_unit', 'cm inches') views file: def submit_form(request): if request.method == 'POST': if request.POST.get('boolean')\ and request.POST.get('dec')\ and request.POST.get('dec_unit')\: data=example_model() data.boolean= request.POST.get('boolean') data.dec= request.POST.get('dec') data.dec_unit= request.POST.get('dec_unit') data.save() context = { 'context': example_model.objects.all() } return render(request, 'MyAppName/page.html', context) urls: urlpatterns = [ path('', views.home, name='MyAppName-home'), path('form/', views.about, name='MyAppName-about'), path('form/submit_form', views.submit_form, name='submit_form') ] Part of the form: <form action="{% url 'MyAppName:submit_form' %}" method="POST" id="main_form" name="main_form"> The name and id of each input in the rest of the html form are all accurate. My Questions: Why is nothing showing up in my sqlite database under example_model? Running example_model.objects.all() in the Django shell returns an empty QuerySet. Why do I need to redirect with the submit_form url extension to submit the form? I would prefer the user could just stay on the same page. Why does my context not … -
i'm trying to convert a .tex file to pdf using python and django anyone can help me with this and django-tex giving error while creating temp folder
enter image description here Please help me i'm stuck badly in this part. -
Django nested url different views
I have two views CollectionView and CatalogView which are both APIView. In my urls I have: urlpatterns = [ url(r'diwata-2-smi', CatalogView.as_view()), path('diwata-2-smi/collection/', StacCollectionView.as_view()), ] However I cannot access diwata-2-smi/collection/, it is pointing me to CatalogView. How can I achieve so that I have the endpoint for CollectionView? -
Having issue in handling multipart form data in django rest framework
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays. But I got the following error. Category field is required The data is sent like this name: Soap category[0]: 7 category[1]: 23 brand: 7 collection: 11 availability: in_stock warranty: no_warranty service: cash_on_delivery rating: 3 best_seller: true top_rated: true featured: true main_product_image: (binary) merchant: 2 variants[0][product_id]: fgfdg variants[0][price]: 127 variants[0][quantity]: 1 variants[0][color]: red variants[0][size]: M variants[0][variant_availability]: not_available variants[0][variant_image]: (binary) variants[1][product_id]: fgfdg variants[1][price]: 127 variants[1][quantity]: 1 variants[1][color]: red variants[1][size]: M variants[1][variant_availability]: not_available variants[1][variant_image]: (binary) The same issue is with the variants. My models: class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True,null=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" def __str__(self): return self.product_id #Product Model class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? … -
I am not able to pass the url argument to views.py
My urls.py is from django.urls import path from . import views urlpatterns = [ path('registration', views.teacher_registration, name='teacher-registration'), path('list', views.teacher_list, name='teacher-list'), path('profile/<UploadedDetails_FirstName>/', views.teacher_profile, name='teacher-profile'), path('load-upazilla', views.load_upazilla, name='load-upazilla'), ] Views.py is def teacher_profile(request, UploadedDetails_FirstName): UploadedDetails = UploadedPersonalDetails.objects.get(FirstName=UploadedDetails_FirstName) context = { 'UploadedDetails': UploadedDetails } return render(request, 'teacher/teacher-profile.html', context) models.py is class UploadedPersonalDetails(models.Model): FirstName = models.CharField(max_length=45) LastName = models.CharField(max_length=45) PhoneNumber = models.CharField(max_length=11) EmailAddress = models.CharField(max_length=255, unique=True) RoomNumber = models.CharField(max_length=5) SubjectsTaught =models.CharField(max_length=205) def __str__(self): return f'FirstName:{self.FirstName}' And my .html codeis The error i am facing is NoReverseMatch at /teacher/list Reverse for 'teacher-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['teacher/profile/(?P<UploadedDetails_FirstName>[^/]+)/$'] -
How to handle two different forms in one page?
I have multiple forms in my template. When I submit my first form, the second form is also submitted because it does not need a required input field. I want to submit my second form (with id = lead_form ) when user click it's submit button. How can I do that? approval_page.html // The first form <form method="POST" enctype="multipart/form-data"> <!-- Very Important csrf Token --> {% csrf_token %} {{ form.media }} {{ form|crispy }} <input type="hidden" name="form" value="risk" /> <input type="submit" class="btn btn-primary btn-lg" value="Approve"> </form> // The second form <form method="POST" enctype="multipart/form-data" class="lead_form" id="lead_form" > <!-- Very Important csrf Token --> {% csrf_token %} {{ form_approval.media }} {{ form_approval|crispy }} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> <button type="submit" class="btn btn-success btn-xs"> Submit </button> </form> views.py def approval_page(request, id): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) pdf = get_object_or_404(Pdf, id=id) .... if request.method == 'POST' and request.POST.get('form') == 'risk': form = PdfRiskForm(request.POST, request.FILES, instance=pdf) if form.is_valid(): this_pdf = form.save() this_pdf.save() else: form = PdfRiskForm() ... form_approval = LeadApprovalForm(request.POST) if request.method == 'POST': if form_approval.is_valid(): lead_approval = form_approval.save() lead_approval.user = request.user lead_approval.approval_id = approval lead_approval.rank = request.POST.get('rank_name', None) lead_approval.save() else: form_approval = LeadApprovalForm() context = { 'form': form, 'form_approval': form_approval .... … -
Can a django application be a client and a provider to different apps?
I have build 2 application using Django and one of them is a client app (in order to login with github credentials using oauth2), and its also the provider for my other django application. Is that gonna create any issues ? I am using OAuth toolkit for provider and python social for client. -
Why do I get "ModuleNotFoundError: No module named 'mysite'", while I have no mysite module at all?
** My wsgi configuration page** import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'finalproject.settings') ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: application = get_wsgi_application() ###### or, for older Django <=1.4 import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() My env and packages myenv) 11:40 ~/test (main)$ ls README.md db.sqlite3 finalproject main manage.py media requirements.txt static I don't know what went wrong, because I did everything following documentation. -
How to Select Multiple data from drop down in django form(Field has M2M relation in database)?
I have one many to many field in my model.py class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer = models.ManyToManyField(developer) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) def developer_assigned(self): return ",".join([str(p) for p in self.Developer.all()]) here's my admin.py @admin.register(jira) # class ImpExp(ImportExportModelAdmin): # pass class JiraAdmin(admin.ModelAdmin): list_display = ('id', 'Jira_ID' ,'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Sandbox', 'developer_assigned') here's my form.py class jiraReg(forms.ModelForm): class Meta: model = jira fields = ['Jira_ID', 'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Developer','Sandbox'] widgets = { 'Jira_ID':forms.TextInput(attrs={'class':'form-control','id':'Jira_ID','readonly':'readonly'}), 'Jira_Story':forms.TextInput(attrs={'class':'form-control','id':'Jira_Story','readonly':'readonly'}), 'Short_Description':forms.TextInput(attrs={'class':'form-control', 'id':'Short_Description','readonly':'readonly'}), 'Story_Points':forms.TextInput(attrs={'class':'form-control', 'id':'Story_Points','readonly':'readonly'}), 'Sprint':forms.TextInput(attrs={'class':'form-control', 'id':'Sprint','readonly':'readonly'}), 'DX4C_Object':forms.TextInput(attrs={'class':'form-control', 'id':'DX4C_Object','readonly':'readonly'}), 'Developer':forms.Select(attrs={'class':'form-control', 'id':'Developer'}), 'Sandbox':forms.Select(attrs={'class':'form-control', 'id':'Sandbox'}), # 'Sandbox':forms.ModelMultipleChoiceField(queryset=jira.objects.all()), # 'Sandbox': SelectMultiple(attrs={'class': 'form-control-sm form-control js-multiple-select', 'multiple':'multiple'}) } here's my view page for edit data using form # update dependency management def update_jiradata(Request,id): if Request.method == 'POST': pi = jira.objects.get(pk=id) fm = jiraReg(Request.POST, instance=pi) if fm.is_valid(): fm.save() fm.save.m2m() fm = jiraReg() return HttpResponseRedirect('/DependencyManagement') else: pi = jira.objects.get(pk=id) fm = jiraReg(instance=pi) jira_story = jira.objects.all() return render(Request, 'hello/EditManagement.html', {'jiraform': fm, 'JIRA': jira_story}) here in my form the developer field i want to select multiple data and update that in table. some one plese help to achieve that? -
import json not working with shell and manage.py Django
I am writing some python scripts for my Django project. And I am running it using manage.py and shell. import json is not working if I am running it with manage.py and sell. But it is working if I try without shell and manage.py I don't know why this is happening. With manage.py and shell: (Not working) python3 manage.py shell < custom_scripts/imports.py Error: NameError: name 'json' is not defined Without manage.py and shell: (Works) python3 custom_scripts/imports.py Code inside the script: import json print(json.loads("{}")) Any thoughts? -
Django Rest Framework data display
I have a model that contains a ManyToManyField like for instance: class User(AbstractBaseUser, PermissionsMixin): login = models.CharField(unique=True) employee = models.ForeignKey( Employee, on_delete=models.CASCADE, null=True, blank=True, ) rooms = models.ManyToManyField( Room ) Now, I built a serializer that displays this data, but how can I change how the data looks like? Right now it looks like this: { "employee_id": 25, "rooms": [ { "location": "Berlin", "number": "25" }, { "location": "Berlin", "number": "12" } ] } and I would like it to look like this: { "employee_id": 25, "Berlin": ["25", "12"] } Any idea how could I achieve this? -
difference between django.shortcuts and rest_framework.generics
what is difference between two The following sentence from django.shortcuts import get_object_or_404 and from rest_framework.generics import get_object_or_404 -
Return Base64 code from Django ImageField Model in Django rest framework
I want to return a response of image field as base64 code in rest framework -
Error in python3 django while running sudo dpkg --configure -a command on ubuntu 18.04.4
I tried to run this command $ sudo dpkg --configure -a got this below error Setting up python3-django (1:1.11.11-1ubuntu1) ... File "/usr/lib/python3/dist-packages/django/contrib/admin/widgets.py", line 152 '%s=%s' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator expression must be parenthesized dpkg: error processing package python3-django (--configure): installed python3-django package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: python3-django Then I tried upgrading django but exception occured. What to do? -
Validation error 422 on the login page in fastapi login page
I am working on this code. I am getting validation error 422 on this code and am not able to figure it out the issue **main.py** @app.post("/loginsuccess/", response_class=HTMLResponse) async def login_success(request: Request, username: str = Form(...), password: str = Form(...)): p = await User_Pydantic.from_tortoise_orm(await User.get(username=username, password=password)) json_compatible_item_data = jsonable_encoder(p) if json_compatible_item_data is not None: logger.info("Logged in Successfully") return templates.TemplateResponse("homepage.html", {"request": request, "username":username}) else: status_code:int status_code = 500 logger.error("Invalid Credentials") return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code}) The error i have given the screenshot below enter image description here -
Djano include foreign field to query only if exists
I have 2 tables (Product and CustomerPrice) CustomerPrice is the intermediate table between Customer and Product. It assigns customer specific pricing to certain products. Product table id name price 1 orange 1.5 2 apple 2.2 3 kiwi 3.5 CustomerProduct table id customer_id product_id price 1 233 1 1.2 2 233 2 2.0 I want to query the product with CustomerProduct.price if exists. The expected data in such format (example in json but want queryset): [ { id: 1 name: "orange" price: 1.2 // The price adjusted according to customer price } { id: 2 name: "apple" price: 2.0 // The price adjusted according to customer price } { id: 3 name: "kiwi" price: 3.5 // Price remain original because CustomerProduct not exists. } ] I totally have no idea how to accomplish this in Django. How to do that? -
Unable to load a new server in Django
I am currently working on two Django project at the meantime. However, I am not able to switch my server from one to another. When I am running the server of http://127.0.0.1:8000/, it keeps showing the old website but not able to access the new one. I have searched for a number of solutions and I found this python package "django-livereload-server" https://github.com/tjwalch/django-livereload-server I followed this method strictly but it doesn't work. The following error message was shown when I run python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace System check identified 1 issue (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): f lights. Run 'python manage.py migrate' to apply them. June 16, 2021 - 19:11:02 Django version 3.2.4, using settings 'airline.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Is it the problem of my code or what're the problems -
How to Get All Posts with post_status django rest api?
In my project, How can I get all posts with post_status like- publish, pending, draft, spam. I want to query with post_status. Post Model ` class Post(models.Model): title = models.CharField(max_length=255) slug = models.CharField(max_length=255, unique= True, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) subtitle = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(max_length=5555, null=True, blank=True) image = models.ImageField(blank=True, upload_to=post_image_path) image_caption = models.CharField(max_length=255, blank=True) post_status = models.CharField(max_length=255) comment_status = models.CharField(max_length=255) post_type = models.CharField(max_length=50) comment_count = models.IntegerField(null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) tags = models.ManyToManyField(Tag, blank=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title ` Serializer.py from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' read_only_fields = ['author'] How to implement in view? -
entrypoint.prod.sh file not found (Docker python buster image)
I'm getting this issue with my entrypoint.prod.sh file that it doesn't exist even though I have echoed "ls" command and it shows me that the file is present in the right location with the right permissions but still docker isn't able to find it. I have tried many solutions but none are working. Any suggestion/help would be much appreciated. Let me know if you guys need any extra information from me. so this is my main docker-compose.staging.yml file: - version: '3' services: django: build: context: ./ dockerfile: docker-compose/django/Dockerfile.prod expose: - 8000 volumes: - ./backend:/app - static_volume:/app/django/staticfiles environment: CHOKIDAR_USEPOLLING: "true" depends_on: - postgresql stdin_open: true tty: true env_file: - ./.env.staging postgresql: image: postgres:13.1 environment: - POSTGRES_USER=sparrowteams - POSTGRES_PASSWORD=sparrowteams - POSTGRES_DB=sparrowteams ports: - 5432:5432 volumes: - .:/data nginx-proxy: container_name: nginx-proxy build: nginx restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/app/django/staticfiles - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - django nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy volumes: static_volume: certs: html: vhost: Then I have my Dockerfile.prod: - ########### # BUILDER # ########### # pull official base image FROM python:3.9.1-buster as builder # set work directory WORKDIR /app … -
Django PDF Render, aggregate template tag shows up with code included
In views.py, I have the following function to render a PDF view: def agent_render_pdf(request, *args, **kwargs): pk = kwargs.get('pk') agent = get_object_or_404(Agents, pk=pk) invoices = Invoice.objects.filter(agent=agent) invoice_total = invoices.aggregate(Sum('invoice_amount')) template_path = 'agents/statement.html' context = {'agent': agent, 'invoices':invoices, 'invoice_total': invoice_total,} #Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') #if download: #response['Content-Disposition'] = 'attachment'; filename"report.pdf"' #if display: response['Content-Disposition']='filename="report.pdf"' #find the template and render it template = get_template(template_path) html = template.render(context) #create a PDF pisa_status = pisa.CreatePDF( html, dest=response ) if pisa_status.err: return HttpResponse('We had some errors <pre>' +html +'</pre>') return response I am rendering that to 'statements.html' as follows: <body> {{ agent }} <div class="table"> <table> <th>Invoice Number</th> <th>Invoice Date</th> <th>Due Date</th> <th>Invoice Amount</th> <th>Invoice Age</th> {% for i in invoices %} <tr> <td>{{ i.invoice_number }}</td> <td>{{ i.invoice_date }}</td> <td>{{ i.invoice_due_date|date:"m/d/Y" }}</td> <td>{{ i.invoice_amount }}</td> <td>{{ i.InvoiceAge }}</td> </tr> {% endfor %} <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>total:</td> <td>${{ invoice_total }}</td> <td>&nbsp;</td> </tr> </table> </div> My view is basically rendering as expected, accept that the invoice_total is showing up as ${'invoice_amount__sum': Decimal('2500')} instead of just proving the total of invoices as $2,500. I'm clearly getting the information I want, I just don't understand what I'm doing wrong that's causing … -
ModuleNotFoundError: No module named 'home'
ModuleNotFoundError: No module named 'home'