Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__str__ returned non-string (type NoneType) django
I'm trying to take input the person table but I'm getting this error. I have connect these two models and I'm returning the string to connect it can anyone tell me solution for this below are my codes this code is from models.py from django.db import models class Person(models.Model): PersonID=models.CharField(max_length=30,null=True) Lastname=models.CharField(max_length=30,null=True) Middlename=models.CharField(max_length=30,null=True) Firstname=models.CharField(max_length=30,null=True) Initials=models.CharField(max_length=10,null=True) Title=models.CharField(max_length=10,null=True) Gender=models.CharField(max_length=10,null=True) Birthdate=models.DateField(default=None,null=True) def __str__(self): return self.PersonID class Function(models.Model): FunctionCode=models.CharField(max_length=30,null=True) FunctionName=models.CharField(max_length=30,null=True) MinSalary=models.IntegerField(null=True) MaxSalary=models.IntegerField(null=True) DefaultBillingRate=models.CharField(max_length=30,null=True) def __str__(self): return self.FunctionCode this code is from forms from django.forms import ModelForm from .models import Person class PersonForm(ModelForm): class Meta: model = Person fields = '__all__' this code is from views from django.shortcuts import render from .forms import Person from .models import * def createPerson(request): form = Person() context = {'form':form} return render(request, 'create_person.html', context ) this code is from person.html {% extends 'main.html' %} {% load static %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Submit"> </form> {% endblock %} -
Button auto collapses and re collapses when i click it and I dont know why is there an issue?
<!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" defer></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" defer></script> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none !important; outline: 0px !important; } .login_container { padding: 0 2rem; } .input-group-text { background: #f7ba5b !important; color: white !important; border: 0 !important; border-radius: 0.25rem 0 0 0.25rem !important; } .input_user, .input_pass:focus { box-shadow: none !important; outline: 0px !important; } </style> </head> <body> <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">REGISTER ACCOUNT</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> {% csrf_token … -
How to render data in vertical table?
How to render data in the vertical table in Django. Im stuck, please help me.Since data is huge I cannot use more for loops on template .I tried by sending data on template as following format : context = { "name":["A","B","C","D","E"] "age":[23,23,23,23,23], } so that I can render it in vertical form. But need to use a loop over each field. Is there any other way? Or any other python lib. that can be used? -
Get last record for list of ids Django
I have a Django model with fields 1.id 2.status 3.name I have a list of ids [1,5,7] I want the last record of each id like model.objects.filter(id__in=list)..... -
localhost with SSL - Django
In the Django project, Is any way possible to enable SSL(HTTPS) in the localhost environment? For example, the application should run https://localhost:8000 instead of http://localhost:8000 -
Django ORM difference() not working correctly with querysets with ArrayAgg
I'm trying to get the difference between two querysets which have been grouped by using ArrayAgg. My queries look like this: yesterday_feeds = ( Summary.objects.filter(started_at__date=yesterday) .values("client_feed__xml_url") .annotate( found_pms=ArrayAgg("found_property_managers", distinct=True, filter=Q( found_property_managers__isnull=False)) ) ) And the result: [{'client_feed__xml_url': 'someurl_1', 'found_pms': [7, 10, 11]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': [380]}] The other query: today_feeds = ( Summary.objects.filter(started_at__date=today) .values("client_feed__xml_url") .annotate( found_pms=ArrayAgg("found_property_managers", distinct=True, filter=Q( found_property_managers__isnull=False)) ) ) And it's result: [{'client_feed__xml_url': 'someurl_1', 'found_pms': [7, 10]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': []}] I'd like to get the values for a given xml_url which are present in yesterday_feeds but not in today_feeds: >>> yesterday_feeds.difference(today_feeds) [[{'client_feed__xml_url': 'someurl_1', 'found_pms': [11]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': [380]}]] But what I get is just yesterday_feeds queryset: [{'client_feed__xml_url': 'someurl_1', 'found_pms': [7, 10, 11]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': [380]}] Any idea what am I doing wrong? -
django tests cannot modify session
In my test I have the following code. import uuid from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase class ExampleTestCase(APITestCase): def test_set_session(self): machine_id = str(uuid.uuid4()) session = self.client.session session['machine_id'] = machine_id session.save() response = self.client.delete(reverse('current-user')) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) And then in my view, I do this. def current_user(request): print(request.session.get('machine_id')) However the session key is missing apparently. Why is this happening? Is this a bug in django? -
i want to display individual view for a product using slug, but i cannot encounter the positional argument error?
I want to display my each product objects into templates using slug, but i am facing an positional argument error. Please help me get with it as I am new to django here is my url path path('link_view/<int:id>', views.link_view, name='link_view'), here is the view #Display individual product def link_view(request, id): results = AffProduct.objects.get(id=id) return render(request, 'product_view.html', {"results":results}) Following is the error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /affiliation/link/ Exception Value: link_view() missing 1 required positional argument: 'id' -
Django Blog - Comment System
I am new to Django, and I am wondering how I can intelligently link the system of comments and posts using class-based views. Here's my 'models.py' file in the 'blog' app: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['date_posted'] def __str__(self): return '{} - {}'.format(self.author, self.date_posted) There's my 'post_detail.html' template that shows the specific post and here I just want to show all comments under the post: {% extends 'blog/base.html' %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}"> {{ object.author }} </a> <small class="text-muted">{{ object.date_posted | date:"F d, Y" }}</small> {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 … -
How to add an image tag to radio button in django form
Below is what I have written so far and it doesn't do what I want to achieve. I have finished writing the font-end coding of my website and I am trying to use Django for my back-end which I don't know much of. Models.py class Asset(models.Model): ASSET_TYPE = (('Motor Vehicle','Motor Vehicle')) asset = models.CharField(max_length=200,choices=ASSET_TYPE,null=TRUE) forms.py asset = forms.ChoiceField(choices=ASSET_TYPE, initial=0, widget=forms.RadioSelect(attrs={'class':'form-check-inline', 'id':'asset'})) HTML template <div class="container asset"> <div class="row"> <div class="col"> <div class="item"> {{ form.asset.0 }} <label for="asset_0"><img src="{% static 'Asset/Motor Vehicle.png' %}" alt=""><strong>Motor Vehicle</strong></label> </div> </div> </div> </div> With the code above, I get this outcome which is not what I want. current outcome I want an image to be included within the label tag like in this photo: Wanted outcome Any help will be highly appreciated. -
django save custom value in automatic primary key auto_increment
I have a django model with a default primary key which is autoincrementing. My situation is that I want to create an instance having a custom id, see the example below : let's say we had the following instances represented by their respective ids : instance_a(id=1), instance_b(id=2), instance_c(id=3), instance_d(id=4), instance_e(id=5) let's say instance_c has been deleted so the list becomes : instance_a(id=1), instance_b(id=2), instance_d(id=4), instance_e(id=5) And now I want to create instance_f with id=3 which is the id of the previously deleted instace. So the list should become : instance_a(id=1), instance_b(id=2), instance_f(id=3), instance_d(id=4), instance_e(id=5) I tried setting the id in the request but it always gives an automatic autoincrement id. Please do you know a way to achieve this. I hope my explanation was clear. -
How to store the file in the input field even after the form is submitted?
Form Image My idea is to get the text from uploaded docx file and process the file to get misspelled words and replace with the user entered words. I got stuck on how to save the file temporarily(not saving in database). so that I can use the file after user select the specific words. Form: Takes and process the docx file. Once the form returns list of words, user selects the words from the list of words and when submitted it should replace the selected words in the same file. I'm totally new to python. can anyone suggest me better way of achieving it? Thank you in advance -
generic export module based on models meta data: retrun an integer for foreignKey instead of model class (using values_list)
I try to implement a generic export module based on models meta data. It works except values_list return integer instead of model class for a foreignKey # Patient (1, False, 'CI-S1-0001', 5, 'admin', datetime.datetime(2021, 5, 31, 7, 26, 20, 393305, tzinfo=<UTC>)) # Inclusion (1, False, 1, datetime.date(2021, 5, 23)) the third value is an integer (1) but I would like to get access to an instance of Patient class to write pat field ('CI-S1-0001') I do not find any solution using values, serializer, etc... models.py class Patient(models.Model): ... ide = models.AutoField(primary_key=True) ver = models.BooleanField("Fiche verrouillée", null=True, blank=True, default=False) pat = models.CharField("Patient",max_length=11, unique=True, null=True, blank=True, error_messages={'unique':'Un patient avec ce code existe déjà'}) pat_sit = models.ForeignKey('parameters.Site',on_delete = models.CASCADE, related_name='patient_site', db_column='pat_sit') ... class Meta: db_table = 'crf_pat' verbose_name_plural = 'Patients' ... def __str__(self): return f"{self.ide} - {self.pat}" class Inclusion(models.Model): ... pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat') ... log = HistoricalRecords() ... ... app_models = apps.get_app_config('ecrf').get_models() for model in app_models: columns = [str(field_name).split('.')[-1] for field_name in model._meta.concrete_fields] results = model.objects.all().values_list(*columns) q = Q() if model._meta.model.__name__ == 'Patient': for site in sites: q = q | Q(pat__icontains=site) else: for site in sites: # sites is a list q = q | Q(pat__pat__icontains=site) for row … -
Django LDAP - Unable to BIND Successful Connection
I am trying to establish LDAP Authentication on my Django Project. I am extremely new to all these things, and unable to find any documentation or helpful video or answers anything related to this. After making the below changes in my settings.py I am trying to login to Django admin panel and it says that I am providing invalid credentials. However I am still able to login via my credentials of mariadb. which is root/root. And while I provide my LDAP credentials, the console throws this error: result(5) raised OPERATIONS_ERROR({'msgtype': 101, 'msgid': 5, 'result': 1, 'desc': 'Operations error', 'ctrls': [], 'info': '000004DC: LdapErr: DSID-0C09075A, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1'},) search_s('OU=%ou%, DC=%dc% , DC=%dc%', 2, '(sAMAccountName=%(user)s)') returned 0 objects: Authentication failed for %myusername%@%domain%.com: failed to map the username to a DN. I have the following LDAP configuration settings provided by my administrator peoples. This is stored in a file and they do point to it for all the LDAP configs: AuthType Basic AuthBasicProvider ldap AuthzLDAPAuthoritative off AuthLDAPURL "ldap://%domain.abc.lan%/OU=%ou%,OU=%ou%,OU=%ou%,DC=%dc%,DC=%dc%?sAMAccountName?sub" AuthLDAPBindDN "CN=%cn% ,OU=%ou%,OU=%ou%,OU=%ou%,OU=%ou%,DC=%dc%,DC=%dc%" AuthLDAPBindPassword "%password%" AuthLDAPGroupAttribute %attribute% AuthLDAPGroupAttributeIsDN off Now, I am extremely confused on how can I make … -
Django - update inline formset not updating
I'm trying to create an update view which has a few inline formset's in it but for some reason I'm seeing 'id: This field is required.' & none of the inline formset values being set when I click the update button. The fields themselves actually have values in them in the template so I'm not sure why the inline formsets would be empty when trying to save. Models.py class ProjectUpdateForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'details') Views.py class ProjectUpdateView(LoginRequiredMixin, UpdateView): model = Project template_name = 'home/project/project_update.html' context_object_name = "project" form_class = ProjectUpdateForm def get_context_data(self, **kwargs): ReviewChildFormset = inlineformset_factory( Project, AdoptedBudgetReview, fields=('project', 'review'), can_delete=False, extra=0 ) itemNames = [{'item': item} for item in ['Concept & Feasibility', 'Planning & Design', 'Procurement', 'Delivery & Construction', 'Finalisation']] EstimatedBudgetChildFormset = inlineformset_factory( Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, formset=EstimatedInlineFormset, extra=0, widgets={'item': forms.Select(attrs={'disabled': True})}, ) FutureExpenditureFormset = inlineformset_factory( Project, FutureExpenditure, fields=('project', 'byear', 'internalFunding', 'externalFundingSource', 'externalFunding'), can_delete=False, extra=0, ) PreviousExpenditureFormset = inlineformset_factory( Project, PreviousExpenditure, fields=('project', 'byear', 'internalFunding', 'externalFunding'), can_delete=False, extra=0, ) initial = [{'priority': priority} for priority in Priority.objects.all()] PriorityChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=0, widgets={'priority': forms.Select(attrs={'disabled': True})}, ) context = super().get_context_data(**kwargs) if self.request.POST: context['adoptedreviews'] = ReviewChildFormset(self.request.POST, instance=self.object) context['estimatedbudget'] = … -
getting h10 error while deploying fastapi in heroku
I have deployed fastapi application in heroku and the deployment was successful but while starting the app. My browser was showing this message.(screenshot below) enter image description here I have checked the logs and it was showing this below error 2021-05-31T09:31:47.954921+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=newsscrapperdemo.herokuapp.com request_id=a4f73b48-f728-4515-afef-38c64e10f0cd fwd="157.45.236.3" dyno= connect= service= status=503 bytes= protocol=https 2021-05-31T09:31:49.012665+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=newsscrapperdemo.herokuapp.com request_id=da7409af-fac0-4e67-99a0-5a9b11a9a697 fwd="157.45.236.3" dyno= connect= service= status=503 bytes= protocol=https my proc file looks like this web: uvicorn environment.main:app --host 0.0.0.0 --port $PORT --workers 2 -
After uploading image is not displaying in production server
In my project after depl;oying into production server When i have uploaded images it saves into media folder but not displaying image in template. As well as when we go to the admin site and to display an image when I click on the url of the image it is throwing an error like. url not found. But in the media folder the image is saved and when I double click on that image is opened. and when i upload an image from the admin site, the image is displayed in a template. Actually in development server uploading displaying images is working good. After deploying into the production server I have this issue. Please help me to solve this issue. settings.py # managing media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Project urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thanks -
django.core.exceptions.FieldError: Unknown field(s) (dateofbirth) specified for User
Hi im trying to add a DOB field to my django project but I keep getting this error but i cant find where to find it File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\urls.py", line 2, in <module> from . import views File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\views.py", line 13, in <module> from .forms import CreateUserForm File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\forms.py", line 9, in <module> class CreateUserForm(UserCreationForm): File "C:\Users\Ugur\Anaconda3\envs\ECS639U\lib\site-packages\django\forms\models.py", line 276, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (dateofbirth) specified for User My Forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'dateofbirth'] My views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required # Create your views here. from .models import * from .forms import CreateUserForm def registerPage(request): if request.user.is_authenticated: return redirect('/home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('/login') context = {'form':form} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('/home') else: if request.method == 'POST': username = … -
POST method sends no data to Django function based views
I have been trying to write a function based delete view: urls.py from django.urls import path from ttt import views urlpatterns = [ path('', views.home, name='home'), path('delete_task/<str:pk>/', views.delete_task, name='delete_task'), ] views.py def delete_task(request, pk): task_details = Task.objects.get(id=pk) if request.method == 'POST': task_details.delete() return redirect('/') context={ 'task_details' : task_details } return render(request, 'ttt/delete_task.html', context) delete_task.html <form action = "#" method="POST"> {% csrf_token%} <input type="submit" name="Confirm Delete"></input> <a href="{% url 'home' %}" >Cancel</a> </form> When I submit the delete form, I am redirected to an error page. In python shell, I can see the POST data is empty when I select 'Confirm Delete'(this should be passing the id of the task I want to delete). The error I am gett ing is : NoReverseMatch at / Reverse for 'view_task' with arguments '('',)' not found. 1 pattern(s) tried: ['view_task/(?P<pk>[0-9]+)/$'] Also, my models.py : from django.db import models # Create your models here. class Member(models.Model): DESIGNATION = [ ('Developer', 'Developer'), ('Tester', 'Tester'), ('Support', 'Support'), ] name = models.CharField(max_length=200, null=True) role = models.CharField(max_length=100, null=True, choices=DESIGNATION) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Task(models.Model): CATEGORY = [ ( 'Low', 'Low'), ('Medium', 'Medium'), ('Urgent', 'Urgent'), ] STATUS = [ ('Not Started', … -
How to put 2 context_object_name for listView Django
I have developed a context within a context. here's my views.py: class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView): template_name = "agents/agent_client_list.html" context_object_name = "clients" def get_queryset(self): queryset = Client.objects.filter(agent_id=self.kwargs['pk'], agent__isnull=False).order_by('company_name') return queryset however I need to add another context_object_name: "agent" what would I do? thank you in advance -
How to combine and sort multiple OrderedDict in Django?
The below data's are from from three different Django Serializer outputs post=[{"title" :"abc", "date" : "10-03-2021"}, {"title" :"xyz", "date" : "28-01-2021"}, ......] comments=[{"comment_text" :"heloo", "date" : "31-05-2021"}, {"comment_text" :"heloo", "date" : "20-04-2021"}, ......] friends=[{"friend" :"abc", "date" : "12-03-2021"}, {"friend" :"xyz", "date" : "10-05-2021"}, ......] Now I want to combine all three in to single output element and sorted it by date. it is possible?? -
I uploaded the image using SQL query in the blob format. can I use that to display the image Django template?
I am using MySQL workbench as a database and actually, I have not created any model, I uploaded the image using SQL query in the blob format. can I use that to display the image Django template? main.html===>{{ para_image }} we are using to display the image <div class="parallax1" style="text-align:center ; background-image: url('{{ para_image }}')"> <p style=" color: black; font-weight: bold; font-size: 20px; display: flex; align-items: center; justify-content: center; padding: 30px; "> {{ para_text|safe }} </p> </div> views.py===(para_image) is the variable which holds the image def main(request): try: mycursor = mydb.cursor() mycursor.execute("SELECT * FROM counts") myresult = mycursor.fetchall() mycursor1 = mydb.cursor() mycursor1.execute("SELECT * FROM parallax") myresult1 = mycursor.fetchall() mycursor1.execute("SELECT * FROM footer_content") myresult2 = mycursor.fetchall() mycursor3 = mydb.cursor() mycursor3.execute("SELECT * FROM about_us") myresult3 = mycursor.fetchall() print("##########00001111111100000##########") if(1): context={ 'students':myresult[0][2], 'teachers':myresult[0][3], 'workers': myresult[0][4], 'para_text':myresult1[0][2], """image""" 'para_image':myresult1[0][1], 'ftext':myresult2[0][1], 'flink':myresult2[0][2], 'tlink':myresult2[0][3], 'ilink':myresult2[0][4], 'about_us':myresult3[0][2] } return render(request, 'main.html', context) else: context={} return render(request, 'main.html', context) except: context = {} return render(request, 'main.html', context) thank you -
How to rename and upload the files to Google drive, which are uploaded to Django admin page through FileField in models.py
When a File is Uploaded to Django admin database, it gets saved into the database and the "media_url" path mentioned. I want to rename the file with the username of the user appended by timestamp and upload this renamed file to a specific folder in google drive. Thank you in Advance. -
How can I join two tables in order to get records based on some conditions in django?
I need to get those payments whose payment has not been transferred. I have tried something but its not that efficient so I was thinking if I could join the tables in order to accomplish the task but don't know how just started learning django. models.py class Orders(models.Model): payment_gateway_code = models.CharField(max_length=20,choices=[('PAYTM','PAYTM')]) is_active = models.BooleanField(default=True) class Payments(models.Model): id = models.AutoField(primary_key=True) orders = models.ForeignKey(Orders, on_delete=models.CASCADE) direction = models.CharField(max_length=20,choices=[('COLLECTION','COLLECTION'), ('TRANSFER','TRANSFER')]) settlement_status = models.CharField(max_length=50,blank=True, null=True,choices=[('YES','YES'), ('NO','NO')]) is_active = models.BooleanField(default=True) I have tried : # getting all payments whose direction is COLLECTION and settlement_status is YES collection_payments = Payments.objects.filter(Q(direction='COLLECTION') & Q(settlement_status='YES')).select_related('orders').filter(payment_gateway_code='CASHFREE') for collection_payment in collection_payments: order_id = collection_payment.orders_id #order corresponding to one payment order = Orders.objects.get(id=order_id,payment_gateway_code='PAYTM') #payments corresponding to one order payments = Payments.objects.filter(orders=order_id) # check weather transfer initiated if Payments.objects.filter(orders=order_id).filter(direction='TRANSFER').count()==0: initiate transfer Please suggest if there is a better way to do this by joining the tables. -
Django 2.2 cannot serialize default malues once migration has been done
I have a model which is refered to as a foreignkey with on_delete set to SET_DEFAULT. Because of that, I need to provide this model with a default item. I created a static method which does just that. class ScheduleChoice(models.Model): """ This model allows users to define crontab schedules. """ label = models.CharField(max_length=256, verbose_name="Label", unique=True) job_schedule = models.CharField( max_length=256, default="0 0 * * *", verbose_name="Crontab" ) @staticmethod def get_default_schedule_choice(): """ Because some models rely on ScheduleChoice and need a default value, we need to give them a default ScheduleChoice. """ try: choice = ScheduleChoice.objects.get_or_create( label="Every minute", job_schedule="* * * * *" ) except ProgrammingError: choice = None return choice @classmethod def get_choice_count(cls): """ Returns how many schedule choices have been defined. """ return len(cls.objects.all()) class Meta: verbose_name = "schedule choice" verbose_name_plural = "schedule choices" def __str__(self): return self.label class MyOtherModel(models.Model): """ Model using ScheduleChoices. """ job_schedule = models.ForeignKey( "ScheduleChoice", on_delete=models.SET_DEFAULT, default=ScheduleChoice.get_default_schedule_choice(), verbose_name="Schedule" ) activated = models.BooleanField(default=False, verbose_name="activated") I am able to run makemigrations and migrate without issue. My problem starts when I modifiy my models and try to use makemigrations again in order to update the migrations files. I get the error : ValueError: Cannot serialize: <ScheduleChoice: Every minute> There …