Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Max for distinct object in table with Django ORM with Window function
For example we got this EXAMPLE table: obj_num date_insert group_data Obj1 01.01.2020 group1 Obj2 02.01.2020 group1 Obj1 02.01.2020 group1 Obj3 03.01.2020 group2 I need to get result like this obj_num max(date_insert) in each row. For our EXAMPLE table: Obj1 02.01.2020 Obj2 02.01.2020 Obj3 03.01.2020 in raw SQL i can do it with this query: SELECT DISTINCT obj_num, MAX(date_insert) OVER (PARTITION BY obj_num) AS max_date_insert FROM EXAMPLE How can i get same result with Django ORM? I tried to do it this way, but it doesn't work: result = Example.objects.all().annotate( max_date_insert=Window(expression=Max('date_insert'), partition_by=[F('obj_num')])).only('obj_num').distinct() -
How can we access java script variable in Django views.py
I want to access a javascript variable in my views.py of a Django project -
(About Python Migration) An interview question I failed
I conducted an interview last week and need to answer an interview question, but I did not do well. I want to learn and want to get detailed code. The code I completed is as follows. Name: Python test migration Please implement following set of classes in Python. Class Workload that contains following fields: IP string, credentials of type Credentials Storage that contains list of instances of type MountPoint Class Credentials that contains the following fields Username - string Password - string Domain - string Class MountPoint that contains the following fields: Mount point name - string - Example: “c:\” Total size of the mount point - int Add following business constraints to class Workload: Username, password, IP should not be None IP cannot change for the specific workload You cannot have more than one source with the same IP Class MigrationTarget that contains following fields: Cloud Type: aws, azure, vsphere, vcloud - no other types are allowed Cloud Credentials of type Credentials Target Vm object of type Workload Define class Migration that contains the following Selected Mount points: list of MountPoint Source of type WorkloadMigrationTarget of type MigrationTarget Migration state: not started, running, error, success Implement run() method - … -
How to remove all users and reset the primary key of user table in django?
I'm developing a django application with some complicated user interactions and multi user types . So this requires a lot of testing to do . I've observed that even after deleting the user's table completely if I add a new user, the primary key of the newly added user isn't 1 . Is there an easy way to completely delete and reset all the primary key indices of the use table ? Details : Django version = 3.0 Using the default User model provided by django Using dbsqlite3 Thanks -
Django load data to model
So usually in django you have an app let's say common you create and inside it can have a model lets say Site and you can dumpdata from the model like so python manage.py dumpdata common.site > sites.json and it works but this python manage.py loaddata common.site < sites.json doesn't work. I'm curious if this is possible or not, if you know how to please share an example. -
How to use jinja variable inside a variable
<a href="{{ url_for('osupgrade.download_stage_log',url = result.download_url) }}" type="submit" target="_self">Download</a> result.download_url --> This also a variable How can use that? I tried with curly etc, all is failing. -
Django: Admin - order results based on regular expression
I have a problem where I want to order model rows in Django admin based on a number within a string and ignore the letters - like XX0345XX, X0346XXX, XXX0347XX. I'm thinking that I should probably use a regular expression for that. I have an SQL query (PostgreSQL) that returns what I want: select * from mytable order by substring(my_field, '\d+')::int DESC But I'm having trouble applying it to get the same result in the Django admin get_queryset(). I've tried doing something like: def get_queryset(): return Model.objects.raw("select * from mytable order by substring(my_field, '\d+')::int DESC") but the problem is that I'm not returning the right type this way. Model.objects.raw('...') returns RawQuerySet, but get_queryset() should return QuerySet instance not RawQuerySet one, so I can't do it this way. Any suggestions on how to solve this problem? Thanks! -
mysqlclient for django in windows
I hope you are doing great ! I am trying to do application with django framework that bringing the data from mysql database and do reports on it. I have a problems while installing mysqlclient in windows by commands I tried a lot but always the same error can you advice me guys ? -
Is there any alternative to get_queryset() method to capture query parameter in Django ViewSet?
what i am using is : class SomethingViewSet(viewset.ModelviewSet): def get_queryset(self): id=self.request.query_params.get('id') Is there any alternative to capture query params. -
How to add methods to the dynamically created classes in python?
from django.contrib import admin from .filters import DropdownFilter from django.db.models import Q from django.utils.translation import gettext_lazy as _ from .models import User def queryset(self, request, queryset): term = self.value() if term is None: return term = term.lower username = Q() for bit in term.spilt(): username = Q(username, queryset) return queryset.filter(username) class InputFilter(admin.filters.SimpleListFilter): template = 'admin/input_filter.html' def lookups(self, request, model_admin): # Dummy, required to show the filter. return ((),) def choices(self, changelist): # Grab only the "all" option. all_choice = next(super().choices(changelist)) all_choice['query_parts'] = ((k, v)for k, v in changelist.get_filters_params().items() if k != self.parameter_name) yield all_choice class TransactionAdmin(admin.ModelAdmin): list_display = [field.name for field in User._meta.fields] c = type('UserFilter',(InputFilter,),{'title' : _('title'),'parameter_name' : 'search', 'query': queryset}) c.queryset = queryset list_filter = [type('UserFilter',(InputFilter,),{'title' : _(i),'parameter_name' : i, 'query': queryset}) for i in list_display] admin.site.register(User, TransactionAdmin) The code is all about creating custom text input filters to the django admin site, here I want to pass the every field name to the title and I added the queryset function to the dynamically created class but seems like it's not working and I got an error like below NotImplementedError at /admin/epic/user/ subclasses of ListFilter must provide a queryset() method How to solve this problem? -
How to add image in django json
My view: @csrf_exempt def post(request): if request.method == 'POST' and request.user.id: data = json.loads(request.body) title = data['title'] author = data['author'] description = data['description'] image = data['image'] user = request.user.id record = Record(title=title, author=author, description=description, image=image, user_id = user) serializer = RecordSerializer(data=data) serializer.is_valid() serializer.errors # print(serializer.errors) # print(serializer.is_valid()) # print(serializer.validated_data) if not serializer.is_valid(): response = json.dumps(serializer.errors) elif record: record.save() response = json.dumps({ "Message": "Blog added successfully","status_code":"200", "alert_type":"alert-success"}) else: response = json.dumps({ "Message": "Blog could not be added","status_code":"404", "alert_type":"alert-danger"}) return HttpResponse(response) return render(request, 'add_record.html') My model: class Record(models.Model): title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateTimeField(default=timezone.now, blank = True) image = models.ImageField(null=True,upload_to = 'static/images/profile', default = 'images/default_profile.png') user = models.ForeignKey(User, on_delete=models.CASCADE) My Serializer: class RecordSerializer(serializers.Serializer): title = serializers.CharField(max_length = 50, required=True) author = serializers.CharField(max_length = 50, required=True) description = serializers.CharField(required=True) image = serializers.ImageField(required=True) date = serializers.DateTimeField(default=timezone.now) def create(self, validated_data): return Record.objects.create(validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.description = validated_data.get('description', instance.description) instance.image = validated_data.get('image', instance.image) instance.date = validated_data.get('date', instance.date) instance.save() return instance My Error: JSONDecodeError How i solve my image is not adding to database due to jsondecode error. How i add image with json to add image … -
Installed App is not showing in django Admin
Every things is fine but i didn't know why installed apps are not showing in django admin as shown in image all the apps are showing except address app project directory structure admin.py and apps.py from django.apps import AppConfig class AddressConfig(AppConfig): name = 'apps.address' -
Saving a user specific data in django
I am currently working on my maiden django project where an authorised person can save their daily expenses. I have created the login and signup page using UserCeationForm and AuthenticationForm. My code for the same is: def login_view(request): if request.method == 'POST': form= AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) return render (request, 'tasks_notes/index.html') else: form= AuthenticationForm() return render(request, 'registeration/login.html', {'form':form}) def signup_view(request): if request.method == 'POST': form= UserCreationForm(request.POST) if form.is_valid(): user=form.save() login(request,user) return redirect('login') else: form=UserCreationForm() return render(request, 'tasks_notes/signup.html',{'form':form}) I have created a page named index.html where I am giving input to save my daily expenses wfor the appropriate (logged in) user as: <form class="col s12" action='{% url "add item" %}' method='post'> {% csrf_token %} <div class="row"> <div class="container center"> <h3 class='center'>Your total budget is: <span style="color:green;">{{ budget }}</span> dollars</h3> <h3 class='center'>You've spent a total of: <span style="color:red;">{{ expenses }}</span> dollars</h3> <br> <br> <div class="input-field col s3"> <input placeholder="Expense name" name="expense_name" id='expense_name' type='text' class='validate'> <label for='expense_name'>Expense name</label> </div> <div class="input-field col s3"> <input placeholder='Amount' name='cost' id='cost' type='text' class='validate'> <label for='cost'>Amount</label> </div> <div class="input-field col s3"> <input placeholder='Date of Expense' name="expense_date" id="expense_date" type="text" class='datepicker'> <label for="expense_date">Expense Date</label> </div> <button class="btn waves-effect waves-light" type="submit" name="action">Add Expense <i class="material-icons right">add_circle</i> </button> </div> </div> </form> … -
Redirect a URL in Flutter with Post data
I have created two web applications, one in Flutter and another one in Django. I need to redirect my flutter application to my django page on clicking a button in flutter and also send POST data with it. Is there any solution to implement this? I looked url_launcher - a flutter package to redirect but I don't know how to send data in post method with it. -
Writing into files in Google Cloud Functions /tmp folder and uploading to Cloud Storage Bucket using Python
I have one Google Cloud function that gets triggered when there's a new object uploaded in the storage bucket. I actually want to create a list to store blobs in python and render the list to the template(template.html)file to create a new file (index.html) every time there's a new object in the bucket. But I learnt that we can't write into files in Cloud Functions unless the files are in /tmp folder. Please help me! 1. How do I access /tmp folder and create files in it using Python. 2. How can I upload the files in /tmp folder to Cloud Storage Bucket? -
Footer issues with reportlab on Python 3
I am pretty new to the reportlab library in Python. I have been building a PDF with it for a few days now. I tried creating a footer for each page of the document and this seems to work fine, however some pages of the footers appears to be bold and the other pages of the footers appear to be normal. I don't know the reason for this but I have tried to look through to know where the issue is but to avail. class MyDocTemplate(SimpleDocTemplate): def __init__(self, filename, **kw): self.allowSplitting = 0 SimpleDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')]) self.addPageTemplates(template) def afterFlowable(self, flowable): "Registers TOC entries." if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'Heading1': level = 0 elif style == 'Heading2': level = 1 else: return E = [level, text, self.page] #if we have a bookmark name append that to our notify data bn = getattr(flowable,'_bookmarkName',None) if bn is not None: E.append(bn) self.notify('TOCEntry', tuple(E)) page_num = self.canv.getPageNumber() if page_num == 1: self.canv.drawImage("Logo-Business.png",255,100,width=300,height=340,preserveAspectRatio=True,mask='auto') self.canv.setFont('Arial Bold', 30) self.canv.drawString(80*mm, 165*mm, "COURTAGEMODELL POOL") self.canv.drawString(100*mm, 140*mm, "COURTAGELISTE") #design this page yourself self.canv.setFont("arial", 6) text1 = "Seite %s" % page_num self.canv.drawRightString(260*mm, 3*mm, text1) text2 = … -
CORS Header not present despite clearly adding it to response
I have a Django server that I'm trying to implement sessions for. Everything was working fine when suddenly, last week, get requests started being denied due to: Access to fetch at 'http://localhost:8000/ from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. However, before sending the response I explicitly add the header: response = JsonResponse({"success": True}, status=200) response['Access-Control-Allow-Credentials'] = True return response My settings.py seems to be configured correctly, with corsheaders and django.contrib.sessions in INSTALLED_APPS as well as corsheaders.middleware.CorsMiddleware and django.contrib.sessions.middleware.SessionMiddleware in MIDDLEWARE: The request is as follows: ... fetch(query_url, {credentials: 'include'}).then(d => { if( d.status === 200 ) { <do stuff> } }) Am I missing something? I'm using django 2.1, and unfortunately can't upgrade right now. -
django-mailer not sending out emails, no errors either, on server
I'm currently using django-mailer package for email delivery. I've tested locally and everything worked well. Great package btw. But now I deployed the django app on a VPS, when I type on commandline (venv)$ python manage.py send_mail returns: (venv)$ python manage.py send_mail ------------------------------------------------------------ acquiring lock... acquired. releasing lock... released. 0 sent; 0 deferred; done in 0.01 seconds However, there are 4 mails in database messages model/table to be sent. I can see it on django admin site. This is the first django app I deployed. Not sure where got wrong, why it ran perfectly locally but not on server... did I miss anything? -
Django rest framework: How to change error response format globally ? and How to overwrite response returned by APIs.?
I am using Django Oscar Restful APIs and customizing it. I want to overwrite the Response class of the Django rest framework so that the response back responsive dictionary contains a three-parameter message, status, and data. I know that for class-based ModelViewSet, I can override the create method and can return the custom response, but I want to implement it for all the API's so I don't have to overwrite all the API's that Django oscar RESTFUL API provides by default. custom Response that I want to return from all the views: { "status": True "data": [ { "var1": 1, "var2": 2 } ], "message": "This is my success message", } In case of Errors, the default errors shown are in this format: { "email": [ "Enter a valid email address." ] } or { "name": [ "This field may not be blank." ] } I want to change this format and always return the Response in this format: { "status": False #Here i want the errors as handled by Django rest, but not in the list format, i want the error msg same as Given by Django rest, as:" "message": 'name :This field may not be blank.' or "message": … -
How to wait until django background-task is done?
I have a Django project which contains a long running task. I use django-background-tasks for this task. When I press a button, the task should be start and after it has finished, the view should redirect another view however as soon as the button pressed, the view redirects. But I want the view to wait for the task to finish and I want to add the "loading" gif until the task is finished. How can I do that? Thanks. -
Django querysets. Annotate different fields with one query
I wrote 3 queries to the database to get different values. I need to combine those queries to one query. # Counting Total Number of Plans by Day Day.objects.annotate(num_of_plans=Count('plan')) \ .values('num_of_plans', 'date', 'id') # Counting is_completed=True Plans by Day Day.objects \ .filter(plan__is_completed=True) \ .annotate(num_of_completed_plans=Count('plan__is_completed')) \ .values('num_of_completed_plans', 'id', 'date') # Counting status=deferred Plans by Day Day.objects \ .filter(plan__status='deferred') \ .annotate(num_of_deferred_plans=Count('plan__is_completed')) \ .values('num_of_deferred_plans', 'id', 'date') As you can see above there 3 queries. Somehow I need to optimize this code and get values with the help of one query models class Day(models.Model): date = models.DateField(default=datetime.date.today, unique=True) class Plan(models.Model): title = models.CharField(max_length=255) status = models.CharField(max_length=255, choices=PLAN_STATUSES, null=True, default='upcoming') is_completed = models.BooleanField(default=False, null=True) day = models.ForeignKey(Day, CASCADE, null=True) Are there any ways to optimize that 3 queries and get values with one query? -
Dataintegrity error the code is throwing.how to resolve that
views.py def form_upload(request): if request.method == 'GET': return render(request, 'policyportal2020/userupload.html') elif request.method == 'POST': alphabet = string.ascii_letters + string.digits leader_name = request.POST.get('team_cordinator_name').split(' ') leader_fname = leader_name[0] if len(leader_name) > 1: leader_lname = leader_name[1] ppUser = PolicyPortalUser2020.objects.create( fname = leader_fname, lname = leader_lname, email = request.POST.get('team_cordinator_email'), password = ''.join(secrets.choice(alphabet) for i in range(20)), is_PP_user = True, ) teacherObj = Teacher2020.objects.create( name = request.POST.get('teacher_name').split(' ', 1), school = request.POST.get('teacher_name'), mobile_no = request.POST.get('teacher_mobile'), email = request.POST.get('teacher_email'), ) if request.POST.get('org_type') == 'School': max_team_id = Team2020.objects.filter(team_id__contains='2020IRSCPOLICYS').aggregate(Max('team_id')) max_team_id = '2020IRSCPOLICYS' + str(max_team_id) #max_team_id = int(max_team_id[-3:]) + 1 elif request.POST.get('org_type') == 'College': max_team_id = Team2020.objects.exclude(team_id__contains='2020IRSCPOLICYS').aggregate(Max('team_id')) max_team_id = '2020IRSCPOLICY' + str(max_team_id) #max_team_id = int(max_team_id[-3:]) + 1 tObj = Team2020.objects.create( team_id = max_team_id, tname=request.POST.get('team_name'), institute = request.POST.get('institute'), pUser = ppUser, teacher = teacherObj, city = request.POST.get('city'), state = request.POST.get('state'), #is_school = request.POST.get('school'), shall we use these fields to identify #is_college = request.POST.get('college'), ) leaderObj = Interns2020.objects.create( fname=leader_fname, lname= leader_lname, email= request.POST.get('team_cordinator_email'), team= tObj, moblie_no = request.POST.get('intern_mobile'), org_type = request.POST.get('org_type'), is_leader = True, city = request.POST.get('city'), state = request.POST.get('state'), ) member_2_name = request.POST.get('member_2_name').split(' ') mem_2_fname = member_2_name[0] if len(member_2_name) > 1: mem_2_lname = member_2_name[1] Interns2020.objects.create( fname=mem_2_fname, lname=mem_2_lname, email=request.POST.get('member_2_email'), team = tObj, is_leader = False, ) member_3_name = request.POST.get('member_3_name').split(' ') mem_3_fname … -
Django how to avoid hitting database again
Is it possible to avoid hitting database when calling Model's function on template? in my views: class ContractListView(FilterView): model = Contract paginate_by = 100 def get_queryset(self): qs = Contract.objects.prefetch_related('payments') return qs in my template Im calling Contract model's function payment_status. model: class Contract(models.Model): ... @property def payment_status(self): ... payments = self.payments.values_list('payment_date', flat=True) # it is hitting database again return True if first in payments else False When I see sql queries in debug_toolbar prefetch_related is working fine but every row is repeating the query again. How can fix this? -
Django search field select options from model fields list
I have a Django list view with a search field on top of the list. I now want this field to become a select field instead of simple text and the select options should be the field list from the underlying model. Searched around for quite a while, but did not found an appropriate approach for this. Any link or ideas welcome to get this things together. -
Django Request Data contains unnecessary u symbols
I'm trying to do a CSV Export in Django. I already have the exporting running but the data exported contains unnecessary item like u on it. Here's the example of data exported. [u'OBJECTID_1', u'OBJECTID', u'ROADCODE', u'SURFACE', u'LANES', u'LONGNAME', u'SHORTNAME', u'STD_CODE', u'Shape_Leng', u'Shape_Le_1', u'CODE', u'HIE_TYPE'] This is my python code when exporting the data to csv try: dirPath = settings.CSV_EXPORT_PATH # print (json.dumps(request.data['historical_rows'])) historical_rows = np.asarray(request.data['historical_rows']) print (historical_rows) csv_name = dirPath + request.data['csv_name'] property_id = str(request.data['property_id']) np.savetxt(csv_name, historical_rows, fmt=str('"%s"'), delimiter=",") the data came from an array posted to python via ajax "OBJECTID_1", "OBJECTID", "ROADCODE", "SURFACE", "LANES", "LONGNAME", "SHORTNAME", "STD_CODE", "Shape_Leng", "Shape_Le_1 as you can see the data I'm trying to send to server is clean but end up having unnecessary data like u when exported to CSV. Thank you!