Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django RestFramework : how to get API data using OOP concept?
As per below mentioned, To get the API data i used django ORM and generic class based views and also i used serializers to convert from raw-data to json-data. How to get same json data using Python OOP-concept method. Any help would be much appreciated. models.py : class Category(models.Model): category_name = models.CharField(max_length=200) serializers.py : class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" views.py : class CategoryListAPIView(generics.ListAPIView): model = Category queryset = Category.objects.all() serializer_class = CategorySerializer Api data : { "id": 1, "category_name": "category-01", } -
CSS Loading Local Background Image
This is so simple, but nothing is working for me. I am trying to have a background of a local picture I own. I have read a bunch of other sites, and no one is consistent. I have tried every combo of ../ or ./ or file/// or someone even said web/port_back. Half include "" within the () and half don't. Tried every combo with that. Cleared my cache data constantly just in case that has affected it. My Image is located /Portfolio/port_back.JPG and My css is located /Portfolio/static/index_app/index.css CSS: body{ background-image: url("../../port_back.jpg"); /* background-repeat: no-repeat; */ background-size: cover; } -
getting data from oracle database to postgresql in django
I am making a microservice. To tell the truth I could not find satisfactory answer. More precisely, there is a big oracle database. In my microservice has PostgreSQL I want to bring only first_name, last_name and phone number data to PostgreSQL unfortunately there is no API for this. My Question is how can I import specific table data to PostgreSQL? If question is unclear please let me know! Thanks in advance! -
How to view django bulk_update/bulk_create query?
We can get any django query by putting .query in the end, like this: print(MyModel.objects.all().query) It print the resulting query, without querying the database. Is there a way to get the query for bulk_create or bulk_update, without actually querying the database? Additional question: Is it possible to guess, if a bulk query may throw the below error or not (by comparing the bulk query size with max allowed query packet size)? (1153, "Got a packet bigger than 'max_allowed_packet' bytes") -
How to store a very large object in PostgreSQL using Django
I have a very large(>1Gb) object in Django which I need to store in the PostgreSQL Database. I'm using Django's ORM for all the database operations. I'm always getting an error of the following form - django.db.utils.InternalError: invalid memory alloc request size 1073741824 This is my existing code - large_data = get_large_data() self.objects.create( part_a=large_data["part_a"] ) Is there a better way to pass this data to the DB. -
Django Error message displays behind text box
I have a custom error validation displayed, however, the message is displayed behind the next input box. How can I change the error message to either be a popup, or the message display inside the text box, or some other way that I can see the text? This is my forms.py class ProductForm(ModelForm): prod_code = forms.CharField(label=False,error_messages={'unique': 'This is unique'}) prod_descr = forms.CharField(label=False) supplier = forms.ChoiceField(choices=suppliers, label=False, required=False) list_price = forms.DecimalField(label=False, required=False) serialsed_item = forms.ChoiceField(choices=YesNo, label=False, required=False) category = forms.ChoiceField(choices=categories, label=False, required=False) class Meta: model = Product fields = '__all__' helper = FormHelper() helper.layout = Layout(Field('text_input', css_class='form-control-lg'),) def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False This is my template : {% extends 'base.html' %} {% load crispy_forms_tags %} {% block page_head %}Add Product{% endblock %} {% block navbar %} <navbar class="mr-auto"> <div class="container-fluid"> <ul class="nav navbar-expand"> <li> <button type="submit" form="p-form" class="btn btn-outline-secondary">Add Product</button> <button class="btn btn-outline-secondary" onclick="document.location='{% url 'prodlist' %}'">Close Without Saving</button> </li> </ul> </div> </navbar> {% endblock %} {% block content %} <form id="p-form" action="{% url 'newproduct' %}" method="post"> <!-- {{form.prod_code|as_crispy_field}} {{form.prod_descr|as_crispy_field}} {{form.supplier|as_crispy_field}} {{form.list_price|as_crispy_field}} {{form.category|as_crispy_field}} --> {% csrf_token %} <div class="container-fluid "> <div class="row"> <div class="col-6 "> <div class="row"> <div class="col-3">Product Code</div> <div class="col-8" >{{form.prod_code|as_crispy_field}}</div> … -
Running into problems not sure what's going on
TypeError at /create decoding to str: need a bytes-like object, NoneType found Request Method: GET Request URL: http://127.0.0.1:8000/create Django Version: 3.1 Exception Type: TypeError Exception Value: decoding to str: need a bytes-like object, NoneType found -
Django operator.or_ not working as expected
I have a model with the tags field which contains tags separated by space. class MyModel(models.Model): user = models.ForeignKey(User) tags = models.TextField() The tags will be separated by a comma static, assets, anuj In order to filter using AND operator. For example, when user search by static and anuj, it will return only the objects whose tags contains both the fields. import operator from functools import reduce from django.db.models import Q qr = MyModel.objects.filter( reduce(operator.and_, ( Q(tags__icontains=x) for x in q) ) ) Above code works fine for AND operator, But now I want to filter using OR operator, where if user search for static, another-tag then it will give the objects which contain any of the tag(s). For this, I changed the above query to qr = MyModel.objects.filter( reduce(operator.or_, ( Q(tags__icontains=x) for x in q) ) ) But it is not working as expected. -
No changes detected in app 'learning_logs'
I ran the code settings.py and went to INSTALLED APPS and added learning_logs: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs', Then in the terminal I ran 'python manage.py makemigrations learning_logs' However it results in 'No changes detected in app 'learning_logs' Note that I read some other articles and got no good answer Also note that the end bracket is supposed to be in the dictionary -
POST http://locahlhost:8000/register net::ERR_NAME_NOT_RESOLVED
Currently I'm trying to use Vuejs with Django Rest Framework and I ran into an issue. I want to create a register and login authentication with vuejs and DRF using Vuex and SimpleJWT. For some reasons I can't make the POST request and I don't know what I did wrong here. I'm learning to use Vuejs with Django and also I'm new to Vuejs and Vuex. urls.py urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path( 'api-token/', TokenObtainPairView.as_view(), name='token-obtain' ), path( 'api-token-refresh/', TokenRefreshView.as_view(), name='token-refresh' ), path( 'api-token-verify', TokenVerifyView.as_view(), name='token-verify' ), ] settings.py # SimpleJWT REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } # Cors-header CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", ] # allow all requests containing any of the default headers(as in django docs) or content-type header CORS_ALLOW_HEADERS = default_headers + ( 'contenttype', ) Frontend axios-base.js import axios from "axios"; import store from "../store/index"; // API URL const ApiUrl = "http://locahlhost:8000"; const axiosBase = axios.create({ baseURL: ApiUrl, headers: { ContentType: "application/json" }, }); const getAPI = axios.create({ baseURL: ApiUrl, }); getAPI.interceptors.response.use(undefined, function(err) { // if error response status is 401, it means the request was // invalid due to expired access token. if (err.config && err.response && … -
Axios POST request is not working properly for django-allauth social login?
MY PROBLEM I have two endpoints /api/google/login and /api/ms/login both are using django allauth social login. when I try to give a POST request to both of the endpoints using Axios it gives me 401 Unauthorized. I am using react-google-login to get the access-token. Here is the code - axios.post('/api/google/login', {access_token: 'my_access_token'}) .then(res => {here_my_response_block_is_handlled}) .catch(err = {here_my_error_block_is_handlled}) But when I directly use my link from browser and copy-paste the same access_token here and post it successfully process the request and return back me token. Here is the direct API URL access view of Django endpoint What I Have Done I have checked the request from the browsers's network tab when I give POST request from frontend and it is sending the request payload correctly with the same key pair of access_token. I am getting the access_token correctly from react-google-login because I console.log it and use the same access_token when I am sending the request from direct API link showed in the image above. -
In django orm get all post wheren comment have greater than 20 record
I am beginner in Django. I want know the Django ORM query which get all post where comment have atleast 20 record in comment table. Please help me. -
How to count number of visiorts to django website?
I am working on Django web application and i need to count number of visitors to my page here is my code which count every visit to home page as new visit despite of session. models.py from django.db import models class PageView(models.Model): hits=models.IntegerField(default=0) views.py from django.shortcuts import render from django.views.generic.base import TemplateView from datetime import datetime from .models import PageView def index(request): if (PageView.objects.count() <= 0): x = PageView.objects.create() x.save() else: x = PageView.objects.all()[0] x.hits = x.hits + 1 x.save() context = {'page': x.hits} return render(request, 'pages/index.html', context=context) html You are {{page}}th visitor -
How to display Foreign key Data in Django view page?
i have relation between Project and ProjectFloorPlan, and i want to display ProjectFloorPlan data in my template. Please let me know how i can display the ForeignKey data in my template. Here is my models.py file... class Project(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(null=True, unique=True) def __str__(self): return self.name class ProjectFloorPlan(models.Model): project=models.ForeignKey('Project', related_name='projectfloorplan', on_delete=models.CASCADE, default=None) floorplan_image=models.ImageField(upload_to='floorplan_image') bhk=models.CharField(max_length=100) bed=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.project.name here is my project.html file where i am trying o display ProjectFloorPlan data...but it's displaying nothing {% fot i in project.projectfloorplan_set.all %} <tr> <td>{{i.bhk}}</td> <td>{{i.bed}}</td> </tr> {% endfor %} -
optimization on multiple queryset in django
newbie here on django and django-rest-framework. Asking a question if it is possible to optimize multiple querysets? I found that using select_related() helps to optimize your SQL queries but if you request another queryset for example adding a filter(), select_related() is not taking an effect. See sample code below. code: pass_rate = None total_student_activities = 0 pass_count = 0 student_list = [] graded_class_activity_list = [] pass_list = [] student_activities = bootcamper.studentactivity_set.all() for student in student_activities: if student.bootcamper_id not in student_list: student_list.append(student.bootcamper_id) student_activities = student_activities.select_related('class_activity') for graded_class_activity in student_activities.filter(score__isnull=False): if graded_class_activity.class_activity_id not in graded_class_activity_list: graded_class_activity_list.append(graded_class_activity.class_activity_id) for pass_grade in student_activities.filter(Q(score=PASS) | Q(score=SUPERB)): pass_list.append(pass_grade.id) total_student_activities = len(graded_class_activity_list) * len(student_list) pass_count = len(pass_list) if total_student_activities: pass_rate = round(pass_count / total_student_activities * 100, 2) return pass_rate upon checking on django-debug-toolbar found that there are mutitple similar queries for line 'for pass_grade in student_activities.filter(Q(score=PASS) | Q(score=SUPERB)):' which means select_related didn't take effect. Is there another way around to achieve something like this that doesn't have to hit db? Thank you in advance. -
Adding items to Wishlist | Django
I've got this system where I want to add in a favoriting feature where when someone clicks on the like button on a card it gets saved and displayed at port/wishlist.html but not able to go about and solve it, here is my Github Repository and some main codes. homepage_pic: https://i.stack.imgur.com/WLUyp.png models.py from django.db import models from django.contrib.auth.models import User import datetime YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): song = models.CharField(max_length=50, blank=False) pic = models.ImageField(blank=False, null=True) published_year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) description = models.CharField(max_length=80) def __str__(self): return self.song class Wishlist(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE,null=True) music_id = models.ForeignKey(Music, on_delete=models.DO_NOTHING) views.py @login_required def liked(request): if request.method == "POST": if user.is_authenticated: # takes in the specific card id that is been liked and saves it and displays on Port/wishlist.html music_id.save() else: return HttpResponse("Your card is Invalid") return HttpResponse("Your request is Invalid") like.js $(document).ready(function(){ $(".like").click(function(){ $(this).toggleClass("heart"); }); }); -
How to add space between jumbotron when in mobile device size
So im building this website which looks like this in pc web size: and when i resize the window to make it into mobile-sized window (phone), the jumbotrons turn into like this: My question is that is there a way where i can add a space between the jumbotrons when it is in mobile-size? i do not want the jumbotrons to stick together just like in the picture i attached above. my code so fo far, html: <div class="container col-12"> <div class="row"> <div class="col-md-6"> <div class="jumbotron jumbotron-fluid" id="bg-card-1"> <h1>Cardholder #1</h1> <p>Unique. Outstanding.</p> </div> </div> <div class="col-md-6"> <div class="jumbotron jumbotron-fluid" id="bg-card-2"> <h1>Cardholder #2</h1> <p>Stunning. Modern.</p> </div> </div> </div> <br> <div class="row"> <div class="col-md-6"> <div class="jumbotron jumbotron-fluid" id="bg-card-3"> <h1>Product</h1> <p>Description</p> </div> </div> <div class="col-md-6"> <div class="jumbotron jumbotron-fluid" id="bg-card-4"> <h1>Product</h1> <p>Description</p> </div> </div> </div> </div> and css file: #bg-card-1 { background: url("https://i.postimg.cc/0y2F6Gpp/3.jpg") no-repeat center center; background-size: cover; color:white; text-align: center; height: 100%; } #bg-card-2 { background: url("https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg") no-repeat center; background-size: cover; color:white; text-align: center; height: 100%; } #bg-card-3 { background: url("https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg") no-repeat center; background-size: cover; color:white; text-align: center; height: 100%; } #bg-card-4 { background: url("https://i.postimg.cc/0y2F6Gpp/3.jpg") no-repeat center; background-size: cover; color:white; text-align: center; height: 100%; } -
Counting unique (or distinct) values of model field instances with python/django
Trying to display a count of unique instances of fields that exist in my database. In the model below, the 'uid' is a user id #, and a user can create multiple records on the database under the same 'uid'. So if i count the number of 'uid's I will simply get the number of ALL records created in the database, but i am trying to get the number of unique 'uid's that exist in the database. I have been messing around with .count(), Count, and .distinct() with no luck. I am also quite confused with the distinct=True option. This is in an effort to provide data to an analytics dashboard, so I want to calculate the number of distinct users exist in the database. models.py class Session(models.Model): uid = models.CharField(max_length=50, blank=True) cid = models.CharField(max_length=50, blank=True) # switched from eid client = models.CharField(max_length=50, blank=True) views.py class DashboardListView(LoginRequiredMixin, ListView): model = Session template_name = 'blog/dashboard.html' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Session.objects.filter(client=user).order_by('-session_date') def get_context_data(self, **kwargs): user = get_object_or_404(User, username=self.kwargs.get('username')) context = super().get_context_data(**kwargs) context['total_records'] = Session.objects.filter(client=user).count() # count function return context html tags {{ total_records }} example of sqlite database records from model Sessions uid | cid | client 001 | … -
DJango: Passing the value of a select field to another web page to use in a query filter
I am looking to perform an inventory query based on the result of a Select/drop down. The dropdown value is part of a set of dependent drop down values on the homepage; 'Make' and 'Model' of cars. I want to use the value of 'Model' to open up the available inventory on another webpage 'search_results'. I am basically posting the value of the dropdown 'modelddl' from the 'index' page and looking to get the value on the 'search_results' page. This should then allow the query set to be filtered so that a table can be filled out. No matter what I do I do not seem to be picking up the 'Model' value in the dropdown so the table is rendering without any values. Any help is much appreciated! Key Models class MotorMakes(models.Model): MotorMakeName = models.CharField(max_length=50, unique=True, default=False) def __str__(self): return self.MotorMakeName or '' def __unicode__(self): return u'%s' % (self.MotorMakeName) or '' class MotorModelsV2(models.Model): MotorMakeName = models.CharField(max_length=50, default=False,) MotorModelName = models.CharField(max_length=50, default=False,) Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False) Mlid = models.IntegerField(default=False, unique=True) MotorImage = models.ImageField(upload_to='Car_Pics', default=False,blank=True) def __str__(self): return self.MotorModelName or '' def __unicode__(self): return u'%s' % (self.MotorModelName) or '' class Meta: ordering = ('MotorMakeName',) class GarageInventory(models.Model): MotorDetailRef = models.ForeignKey(MotorDetail, on_delete=models.CASCADE, null=True) … -
How do ı delete a row from database in django
I have remnants of old data ids in my database. So ı get an error in frontend. How do ı clear the empty rows? -
Cannot log in to django admin
Im currently a student and im building my project using gitpod. Ive been using this to create a django based project. For some reason, workspaces after 14 days get deleted on gitpod. I was able to get my code back as everything was saved on gitpod. All i had to do was download the apps again. The issue im having now is that my django accounts that i had created do not work anymore and trying to log in to Django Admin does not work either. Im thinking that all the accounts may got deleted. Is there anyway i could revert this. Im willing to provide any more detail if needed as i know i have not provided a lot. -
Django Annotate Worked with Postgres but now not working with Microsoft SQL Server
I was forced to switch databases from PgAdmin to Microsfot SQL Server. Now the following piece of code is not working and I can't figure what's wrong with it and why it doesn't work with Microsoft SQL Server. def total_queryset(item, selection): bill_amount = Labor.objects.values_list('item__name','selection__name') \ .filter(item__name=item, selection-_name=selection) I'm able to get the bill_amount but when I try to make the annotations it breaks. calculation= bill_amount.annotate(total_regular_amount=Round(Sum('total_bill_amount',filter=Q(paytype__id=1) | Q(paytype__id=2) | Q(paytype__id=5)))) print(calculation) File "D:\Users****\env\lib\site-packages\sql_server\pyodbc\base.py", line 553, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '::'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") Why did my code work with pgAdmin and breaks with Microsoft SQL server? How can I make it work again? -
Django django-tables2 - Changing column ordering into descending
my goal is to reverse a column ordering from the default behavior. I would like to order table with the "number" column then reverse the order (newest->oldest). https://django-tables2.readthedocs.io/en/latest/pages/ordering.html After reading this documentation I tried using the below snippet in my tables.py class, nothing changed. name = tables.Column(order_by=("-number")) Main code. Snippet commented out. # models.py class Arrest(models.Model): number = models.IntegerField() charge = models.CharField(max_length=64) # views.py class ArrestListView(ExportMixin, tables.SingleTableView): table_class = ArrestTable model = Arrest template_name = 'data/view2.html' # tables.py class ArrestTable(tables.Table): # name = tables.Column(order_by=("-number")) export_formats = ['csv', 'xlsx'] class Meta: model = Arrest template_name = "django_tables2/bootstrap4.html" fields = ('number','charge',) -
Django - submitting form field dependant on permission
I'm looking for a way to control the users ability to submit a form field using permissions. We have 3 fields and the condition is that if any of the fields submitted are not in PERMISSION_KEY_MAP, we must return Permission denied. Note: User_1 has the permission to edit field_1 and field_2 only, via a group. I have tried this myself and i get my desired outcome. My question is should I be using PERMISSION_KEY_MAP to control the mapping of field and permission? Fields field_1 field_2 field_3 Views.py class SampleView(): def _get_permission_to_submit_field(self, field_keys): for field in field_keys: if not self.request.user.has_perm( settings.PERMISSION_KEY_MAP[field], ): return False return True def post(self, request, *args, **kwargs): field_keys = list(self.request.POST.keys()) if not self._get_permission_to_submit_field(field_keys): raise PermissionDenied return super().post(request, *args, **kwargs) PERMISSION_KEY_MAP PERMISSION_KEY_MAP = { 'field_1': 'app.edit_field_1', 'field_2': 'app.edit_field_2', } -
How can I storage data inputted on my localHost page (with Django) in .txt/.json files?
I tried this and Django still working, but the .json files don't appear on my rute. This is models.py (Django script) from django.db import models class Pizza(models.Model): """A pizza in a pizzeria""" text=models.CharField(max_length=250) date_added=models.DateTimeField(auto_now_add=True) filename='C:\\Users\\dayao\\OneDrive\\Escritorio\\PythonCrashCourse_Ex\\Pizzas\\pizzotas\\name.txt' def __str__(self): return self.text with open(filename,'w') as f: f.write(self.text) class Topping(models.Model): """Store n make a hook between Pizza an the toppings""" topic=models.ForeignKey(Pizza, on_delete=models.CASCADE) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) filename="C:\\Users\\dayao\\OneDrive\\Escritorio\\PythonCrashCourse_Ex\\Pizzas\\pizzotas\\pizza_toppings.txt" class Meta: verbose_name_plural ='Toppings' def __str__(self): if len(self.text)>=50: return f"{self.text[:50]}..." else: return self.text with open(filename,'w') as f: f.write(self.text)