Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
One Large Model or Multiple Model Inheritance for SQL Performance?
I have a website that allow users to post ads for items they want to sell. The items share some fields and differs in others. you might wanna sell a car or a house. You will have a title, created_date, description, ... etc fields that are shared . But you will have fields for car that aren't used for a house and so on. The type of ads is around 12 ad type like house, car or computer. There are two approaches: To use a base model and inherit it by all other 12 types of ads so will have 13 tables in the DB. To use a single model that have all the fields of all the ads types and will end up with one table and around 70 field (column in the table). The second choice seems easy from Django CRUD side specially when querying and searching all the ads at the same time. What choice is better ? If I go with the second choice would I have any performance issues related to sql ? -
How to filter on Django mantomany field in rest api
I have below Media filter in my django rest api. There is a filter on person_id as shown. Person is a manytomany field in Media model. So one media can have multiple persons. I need to add another filter on Media where I need only those Media’s where there is no entry in Person model. Please advice how do I add that filter. How the GET url will look like. Below url is for person_id. http://10.0.0.238:8000/media?person_id=1 class MediaFilter(filters.FilterSet): """Filters for the MediaViewset endpoint /media """ type = django_filters.CharFilter() category = django_filters.ModelMultipleChoiceFilter( queryset=Category.objects.all(), to_field_name="name", conjoined=True, ) person_id = django_filters.CharFilter(field_name="persons__id", lookup_expr="exact") url = django_filters.CharFilter( field_name="url", lookup_expr="exact") class Meta: model = Media fields = ["type", "category", "person_id", "url"] -
Django database queryset Roll up
I would appreciate if someone can guide me through this please. I am new to Django and trying to figure out a way to import raw data from xls file into Django database. My raw data looks like first table below. And second table shows how I want my database to look like. How do I setup my database so this can be made possible. I have currently setup django-import-export, that brings in the data but as shown in first table. Thanks, Shashank race_date track race prog_num post_pos name 2020-08-09 SAR 1 1 1 Mark 2020-08-09 SAR 1 1A 2 Matt 2020-08-09 SAR 1 3 3 Steve 2020-08-09 SAR 1 4 4 John 2020-08-09 SAR 1 5 5 Eric race_date track race prog_num post_pos name 2020-08-09 SAR 1 1, 1A, 3, 4, 5 1, 2, 3, 4, 5 Mark, Matt, Steve, John, Eric -
Django - InternalError caused by RAISE EXCEPTION in a postgres trigger
I'm new with Django and I need some help, I want to restrict the editing of a model instance, if there's a value in the X field and you try to change any field you get a message. Since I'm using postgres, I thought about using a trigger CREATE OR REPLACE FUNCTION checkear_lb() RETURNS TRIGGER LANGUAGE PLPGSQL AS $$ BEGIN --Check IF not (old.linea_base_id is null) THEN RAISE EXCEPTION 'You can't edit this because'; END IF; RETURN NULL; --I also tried with NEW END; $$ create trigger tarea_con_lb before update on "Desarrollo_tarea" for each row execute procedure checkear_lb(); It works, but I get this InternalError at /admin/Desarrollo/tarea/1/change/ You can't edit this because CONTEXT: función PL/pgSQL checkear_lb() en la línea 5 en RAISE Request Method: POST Request URL: http://127.0.0.1:8000/admin/Desarrollo/tarea/1/change/ Django Version: 3.0.3 Exception Type: InternalError Exception Value: You can't edit this because CONTEXT: función PL/pgSQL checkear_lb() en la línea 5 en RAISE Exception Location: C:\Python38\lib\site-packages\django\db\backends\utils.py in _execute, line 86 Python Executable: C:\Python38\python.exe Python Version: 3.8.2 Python Path: This is the model's field if it helps class Tarea(models.Model): .... #linea base linea_base = models.ForeignKey('LineaBase', null=True, blank=True, help_text='Linea Base', on_delete=models.SET_NULL) # , on_delete=models.CASCADE This is obviously caused by the trigger, and I was … -
Ajax: how to load div with id?
At the moment it loads data into every div with class "replies" but I want to load only into particular id. How to do this? ajax $(document).ready(function () { $(".showReplies").click(function () { $.ajax({ url: $(this).attr("data-href"), type: 'get', success: function (data) { console.log(data); $('.replies').html(data); } }) }); }); template <button type="button" id="{{ comment.id }}" class="showReplies" data-href="{% url 'comment_replies' comment.id %}">Show replies</button> <div class="replies" id="{{ comment.id }}"> I want to click on the button with id 1 and get data in div with id 1. -
how to remove from a querySet
I'm having issues removing from a queryset certain objects in a certain range like: courses = Course.objects.all().order_by('number') I'd like to exclude courses with number less than 418101. -
How do fix this Django admin look
How do i fix this django admin page layout? -
Remove/ Edit the field tags in UserCreationForm
I used to create signup forms using UserCreationForm often in my projects, but this one particular time when I did use the code below: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] help_texts = { 'username': None, 'email': None, } Even when EmailField is required True, I am unable to change the tags underlined in red. It is very annoying to see this on my page. Please let me know how to remove or edit the text there. -
Parse date string from CSV in Django using localisation (localization)
I currently parse dates from a CSV file and save the values on a "models.DateField". The CSV file has dates in a localised format "d/m/Y" (I'm in the UK). I do this using a function: def parseDate(text): return datetime.datetime.strptime(text, "%d/%m/%Y").date() How can I use a Django function to parse the date strings using the localised settings instead? I have searched around and not found a satisfactory answer. There must be a function to do this in Django as it uses such a conversion on its DateInput widget: from django import forms from app.models import Bar class DateInput(forms.DateInput): input_type = 'date' class Foo(forms.ModelForm): class Meta: model = Bar fields = ['date_fld'] widgets = {'date_fld': DateInput()} -
Django - parse data into javascript variable
I am working with django and a libary called gridstack.js. For this I got javascript functionality to use the libary. My idea is that the user can change the grid and press save. If he does that the data will be overritten with the new one. Now I created a Model field data = models.TextField(max_length=50000, default='{x: 0, y: 0, width: 2, height: 2}') this I call in the views.py like this: views.py def index(request): data = SaveData.objects.all() return render(request, 'main/index.html', { 'data': data }) Inside the templates javascript tag I want to give this data to a variable like let the_data = '{{ data.get.data }}';. But it dont parse the data into the js variable. I can call {{ data.get.data }} in the template and the correct data is shown. How can I add this? I already tried different variants like var the_data = JSON.parse("{{data|escapejs}}");. -
Nginx Deployed Anguler Frontned Does not Connect to DRF backend
I have deployed drf backend and angular frontend in the same aws instance, i deployed them using Nginx and gunicron for the drf and Nginx for the angular. I tested the drf API using postman it works fine but the angular frontend doesn't connect to the API, the site works but it cannot connect to the backend API.It shows failed net:: ERR_CONNECTION_REFUSED I have whitelisted the frontend address in the python app setting. frontend is hosted at 80 and the backend is at 8080. server block for backend: server { listen 8080; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/Sheradam_backend; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Sheradam_backend/Sheradam_backend.sock; } } server block for frontend server { listen 80; listen [::]:80; server_name Sheradambd.com; root /home/ubuntu/Sheradam_frontend/dist/SheraDam; server_tokens off; index index.html index.htm; location / { # First attempt to server request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ /index.html =404; } } python app setting: STATIC_URL = '/static/' CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8081', 'http://localhost:4200', 'http://localhost', ) -
Parsing JSON Response to Django DB
I am trying to save this Json response for Twilio to my DB but not sure how I parse this into my model in Django. At the moment it is just outputting the Json response to the terminal def validate_order_with_details(request): try: client = Client(twillio_account_sid, twillio_auth_token) message = client.messages.create( from_=twillio_from_no, body=printer, to=twillio_sender_mobile_no ) if message: return JsonResponse({"data": True, "printer": printer}) else: return JsonResponse({"data": True, "printer": "Error! while process twilio msg."}) print("There are an error with your transaction") except Exception as e: return JsonResponse({"data": True, "printer": str(e)}) print("There are an error with your transaction") else: return JsonResponse({"data": False}) Any help is appreciated. -
Can/How I build a user management system in Django from scratch and not be a singleton pattern?
Can/How I build a user management system in Django from scratch and not be a singleton pattern I need to build a user management system to use it in microservices -
how to show the field data of one app model on the other app template?
Well I am creating a user profile where user can see his all posts which he has been uploaded. But I dont understand one thing that how could i possibly grab the fields of Post model from Posts/models.py and show them on the template which i has created in other app(Profiles) templates. The reason i am trying to access them on otherapp is because I want to show them in the userprofile.html template where user can see his own posts list too. Just like face book posts. posts/models.py : class Post(models.Model): username = models.ForeignKey(User, verbose_name=("user name"), on_delete=models.CASCADE) description = models.CharField(('Description'),max_length=250) title = models.CharField(('Content Title'), max_length=250) create_date = models.DateTimeField(default = timezone.now) image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None) def __str__(self): return self.title profiles/views.py from posts.model import Post from django.views.generic import ListView class UserPostListView(ListView): model = Post context_object_name = 'userpost_list' template_name = 'profiles/userprofile.html' def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.object.filter(username = user).order_by('-create_date') profiles/templates/profiles/userprofile.html <div class="jumbotron"> {% for post in userpost_list %} <div class="post"> <h1><a href="">{{ posts.post.title }}</a> <img src="" alt="not found" height="60" width="60" style="float:right ;border-radius: 20px;" ></h1> <div class="date"> <p> <!-- Published on: {{ object.author.post.create_date|date:"D M Y" }} --> </p> </div> </div> {% endfor %} </div> </div> -
How to Use RESTful APIs with Django
I have been trying to integrate a REST API developed using Django-rest framework with another Django web app. But stuck in passing JSON data into the front-end. I would appreciate any help. Here are my respective files. I have tried two different urls on views.py file, one is AWS API Gateway API, when used no errors are thrown but data is not displayed in front-end. AWS API JSON data where object is like {'key': 'value'}. it contains only one object though views.py def ClientList(request): response = requests.get('A URL') client_data = response.json() return render(request, 'clients/client_list.html', context=client_data) When I change the url in views.py for django-rest framework API then I get an error like "the JSON object must be str, bytes or bytearray, not list" [JSON data where objects are like {key: value},{key:value}, .... Table body was changed accordingly. FrontEnd HTML <table class="table data-list-view"> <thead> <tr> <th></th> <th>NAME</th> <th>EMAIL</th> <th>MOBILE</th> <th>ADDRESS</th> <th>ROLE</th> <th>ACTION</th> </tr> </thead> <tbody> {% for client in client_data %} <tr> <td></td> <td class="product-name">{{client.UserId}}</td> <td class="product-category">{{client.Height}}</td> <td class="product-category">{{client.Income}}</td> <td class="product-category">{{client.Age}}</td> <td> <div class="chip chip-success"> <div class="chip-body"> <div class="chip-text">{{client.role}}</div> </div> </div> </td> </tr> {% endfor %} </tbody> </table> -
Overriding innit in forms to filter the id in Django
I have a model called Provider and other called Contact, the issue I am facing is I have a form which displays all the outputs of the objects of ProviderEmail and ProviderCircuit, so I have to do a filter and to do it what I did was to try to override the innit and to pop of kwargs the instance but it shows None. I dont know what I am doing wrong. views: def provider_detail(request, id): provider = Provider.objects.filter(id=id) circuit = ProviderCircuit.objects.filter(id=id) if request.method == "POST": form = ContactForm(data=request.POST, instance=circuit) if 'save' in request.POST: if form.is_valid(): email = form.cleaned_data['email'] emails = [] for i in email: emails.append(i.email) subject = form.cleaned_data['subject'] form.provider = provider form.save() message = render_to_string('hermes/account_activation_email.html', { 'form': 'hello', }) send_email_task(subject, message, emails) return redirect('hermes:provider') else: form = ContactForm() context = { 'provider': provider, 'circuit': circuit, 'form': form, }**strong text** return render(request, 'hermes/providers_detail.html', context) models: class ProviderEmail(models.Model): email = models.EmailField() provider = models.ForeignKey('Provider', on_delete=models.CASCADE) def __str__(self): return self.email class ProviderCircuit(models.Model): circuit_id = models.CharField(max_length=30, blank=True, null=True) provider = models.ForeignKey('Provider', on_delete=models.CASCADE) aldea_id = models.CharField(max_length=255, blank=True, null=True) class Meta: ordering = ['circuit_id'] def __str__(self): return self.circuit_id class Provider(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) def __str__(self): return self.name def get_absolute_url(self): return … -
Exception Type: NameError at / Exception Value: name 'pcgames' is not defined in django
hello i tried to make pagination i have problem when i try to add pagination to my home html page , i tried this in my code but i got error .. i tried do this : views.py : def home_page(request, template='html_file/enterface.html'): contextt = { 'opratingSystems': OpratingSystems.objects.all(), 'androidgames': AndroidGames.objects.all(), 'androidapk': AndroidApks.objects.all(), 'antivirus': Antivirus.objects.all(), 'pcgames': PCgames.objects.all(), 'pcprogram': PCprogram.objects.all(), } app = pcgames.objects.all() page = request.GET.get('Page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: pcgame = paginator.page(page) except PageNotAnInteger: pcgame = paginator.page(1) except EmptyPage: pcgame = paginator.page(paginator.num_pages) return render(request,template,contextt) in HTML page : <div class="container"> <div class='row'> {% for pcgame in pcgames %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href=" {{ pcgame.page_url }} "> <img src="{{ pcgame.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3 class="font_control_for_home_page_pc_games_name"><a href=" {{ pcgame.page_url }} ">{{ pcgame.name }}</a></h3> </div> {% endfor %} </div> {% if pcgame.has_previous %} <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page=1">First</a> <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page={{ pcgame.previous_page_number }}">Previous</a> {% endif %} {% for num in pcgame.paginator.page_range %} {% if pcgame.number == num %} <a class="btn btn-info mb-4" href="?Page={{ num }}">{{ num }}</a> {% elif … -
Date range in javascript
Iam trying to input a chart in my html template, since Javascript and jquery is not my best attribute iam stuck at a problem to set start data and end date for my Graphs. With the below code Iam able to plot the graph and also I set the date time picker for user, how can I set the Start date and end date input by user in my chart. PS: Chart is plotted by "Chart.js" library. <script> $(function() { $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); const xlabels =[]; const ylabels =[]; chartIt(); async function chartIt() { await getData(); const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: xlabels, datasets: [{ label: 'Number of failure orders', data: ylabels, fill: false, backgroundColor: 'rgba(0, 0, 0)', borderColor:'rgba(0, 0, 0)', borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } } ] } } }); } async function getData(){ const response = await fetch('https://raw.githubusercontent.com/ankurparanjpe/khajana/master/khajana/orders.csv'); const data = await response.text(); const table = data.split('\n').slice(1); table.forEach(row => { const columns = row.split(','); const date = … -
Django Rest Framework - 'retrieve' without primary key
I wrote the following code: def retrieve(self, request, pk=None): if(request.user.is_staff): queryset = Profile.objects.filter(pk=pk).order_by('id') else: queryset = Profile.objects.filter(user=request.user).order_by('id') page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) When making a call to /api/profile/ I get the following response: detail "Not found.". How can I avoid getting a 404? -
Access a list of dictionaries inside of a dictionary in Django templates
I'm trying to access a list inside of my Django Html template, but I can't seem to grab the first element of the list the normal way by grabbing it via its index. In my views, I have a function edamam that calls the API endpoint and returns a JSON dictionary named ingredients. Here's the function: @login_required def edamam(request): ingredients = {} if 'ingr' in request.GET: ingr = request.GET['ingr'] app_key = APP_KEY app_id = APP_ID url = f'https://api.edamam.com/api/food-database/v2/parser?ingr={ingr}&app_id={app_id}&app_key={app_key}' response = requests.get(url) ingredients = response.json() print(f'Type: {type(ingredients)}') return render(request, 'todo/edamam.html', {'ingredients': ingredients}) else: return render(request, 'todo/edamam.html', {'error': 'That item does not exist in the database.'}) I printed typeof(ingredients) to be certain I'm returning a dictionary and the printout does verify that in the console: Type: <class 'dict'> In my views edamam.html, I'm grabbing ingredients.parsed (ingredients is just a massive dictionary) because I'm trying to get the list named parsed in order to grab elements from that. <div class="col-md-5"> {% if ingredients %} <p>{{ ingredients.parsed }}</p> {% endif %} {% endblock %} </div> which returns: [{'food': {'foodId': 'food_bnxr4n3b1ld7i6ace2hkqbwm89du', 'label': 'cheeseburger', 'nutrients': {'ENERC_KCAL': 263.0, 'PROCNT': 12.97, 'FAT': 11.79, 'CHOCDF': 27.81, 'FIBTG': 1.1} , 'category': 'Generic foods', 'categoryLabel': 'food'} }] My question is, how … -
alert condition is not working as expected
enter image description here html: {% if messages %} <div class="row"> <div class="col-4"> {% for message in messages %} {% if message == "success" %} <div class="alert alert-success" role="alert"> User created </div> {% else %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% endif %} {% endfor %} </div> </div> {% endif %} instead of success the alert is considering danger. Can some one help me what is wrong in the codition -
how to add sitemap on nginx?
I am trying to add sitemap on my website for SEO purpose. I was given sitemap.xml file by a guy who helps on Search Engine Optimization. so my nginx configuration is :- location /static/ { autoindex on; root /home/user/myweb; } location /media/ { autoindex on; root /home/user/myweb; } location / { include proxy_params; proxy_pass http://unix:/home/user/gunicorn.sock; } location = /sitemap.xml { root /home/user/myweb; } } so now when i try to access :- www.myweb.com/sitemap.xml this will not serve sitemap.xml file instead it will take me to www.myweb.com/home/user/myweb/sitemap.xml which is 404 not found. so how can i configure sitemap.xml file in my site ? -
Django login Error: save() got an unexpected keyword argument 'update_fields', this happens when i try to login
I just got an error when I try to log in. the error happens only when I add the save method in the User model. But when I remove the save method there is no error at all. I want to decrease the quality of the user picture using PIL to load the website faster, that's why I add the save method. THANKS! here is the user model: class User(AbstractUser): is_student = models.BooleanField(default=False) is_lecturer = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) phone = models.CharField(max_length=60, blank=True, null=True) address = models.CharField(max_length=60, blank=True, null=True) picture = models.ImageField(upload_to='profile_pictures/%y/%m/%d/', default='default.png', null=True) email = models.EmailField(blank=True, null=True) username_validator = ASCIIUsernameValidator() def __str__(self): return '{} {}'.format(self.first_name, self.last_name, self.email) @property def get_full_name(self): full_name = self.username if self.first_name and self.last_name: full_name = self.first_name + " " + self.last_name return full_name def get_absolute_url(self): return reverse('profile_single', kwargs={'pk': self.pk}) def save(self): super().save() try: img = Image.open(self.picture.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.picture.path) except: pass def delete(self, *args, **kwargs): if self.picture.url != settings.MEDIA_URL + 'default.png': self.picture.delete() super().delete(*args, **kwargs) The full log of the error is here: Internal Server Error: /accounts/login/ Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 115, … -
Using TinyMCE with filebrowser and grappelli
I've been wanting to set up a blog app with a WYSIWYG editor. I use S3 as the storage backend for image uploads outside of the editor. For that purpose, I use "django-storages". I have deployed this on Heroku and for that purpose, I use django-heroku as well. To enable image upload for TinyMCE i went ahead and installed Grappelli and filebrowser. I added the URLs for the same added the context processor for Grappelli, set the TINYMCE_FILEBROWSER setting to true. I ensured the URLs for filebrowser and grappelli come before the URL for admin When I call collectstatic, I get this messages like this Found another file with the destination path 'admin/js/timeparse.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. When I open up admin and go to the image upload button on the editor, it doesn't show the upload icon. I was wondering if anyone who has had any experience with this can help me out? I am open to setting up some time with them as well :) Here's the rundown on settings.py INSTALLED_APPS = [ 'django.contrib.admin', … -
User registration, Login, Logout, etc... Django
Is there a way to register, login, logout users, etc... in a Django REST APi. I am using DjangoRestFramework. For authentication, I am using djangorestframework-jwt for JSONWebTokenAuthentication. If I want to be able to have users register, login, logout, etc... What are the options? Also is it customizable? what is the most used out there in the industry, in terms of reliability, etc... Thanks.