Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Incorrect type. Expected pk value, received list." Error DRF React
Error when attempting post request Many to Many relation via React and Axios Question is how can i post list through axios along with image when I put list in request It shows an error "Incorrect type. Expected pk value, received list." View class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): print(request.data['categories']') file_serializer = serializers.PostSerializer(data=request.data) print(request.data.dict()) if file_serializer.is_valid(): print(request.data) file_serializer.save(owner=self.request.user) return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class PostSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') comments = serializers.PrimaryKeyRelatedField(many=True,queryset=Comment.objects.all()) categories = serializers.PrimaryKeyRelatedField(many=True,queryset=Category.objects.all()) class Meta: model = Post fields = ['id', 'title', 'body','owner','notify_users' ,'comments', 'categories','image'] Axios Request const handleSubmit = (e) => { e.preventDefault(); let form_data = new FormData(); form_data.append("image", postimage.image[0]); form_data.append("title", title); form_data.append("body", body); let catory = categories.map(val=>val.id) console.log(catory) let data = { title:title, body : body, categories:catory, image:postimage.image[0], notify_users : notifyuser } console.log(data.categories) //form_data.append("notify_users", notifyuser); form_data.append("categories",catory) console.log(catory) console.log('error here',form_data.get('categories')) authRequest.post('/posts/',form_data,{ headers: { 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; Github -
Django multi-table inheritance different from Postgres table inheritance
So I'm looking at Django's multitable inheritance, and how it differs from Postgres' table inheritance. Say I have the following models: models.py class Mayor(models.Model): name = models.CharField(max_length=255) class City(models.Model) name = models.CharField(max_length=255) mayor = models.ForeignKey(Mayor, on_delete=models.CASCADE) class Capital(City): embassy = models.BooleanField(default=False) Now, if I build the db from this, I get a table that looks something like: cities: +----------+------------------------+---------------------------------------------------------+ | Column | Type | Modifiers | |----------+------------------------+---------------------------------------------------------| | id | integer | not null default nextval('main_city_id_seq'::regclass) | | name | character varying(255) | not null | | mayor_id | integer | not null | +----------+------------------------+---------------------------------------------------------+ capitals +-------------+---------+-------------+ | Column | Type | Modifiers | |-------------+---------+-------------| | city_ptr_id | integer | not null | | has_embassy | boolean | not null | +-------------+---------+-------------+ This isn't idea, as it means that to get capital cities' mayors, I have to do 2 joins, one from capitals to cities, and then from cities to mayors. In Postgres, we can have: cities: +------------+-------------+------------------------------------------------------+ | Column | Type | Modifiers | |------------+-------------+------------------------------------------------------| | id | integer | not null default nextval('cities_id_seq'::regclass) | | name | text | | | mayor_id | realinteger | | +------------+-------------+------------------------------------------------------+ where the below table is listed as a 'child' capitals: +------------+--------------+------------------------------------------------------+ … -
Djongo Model Error “Select a valid choice. That choice is not one of the available choices.”
I'm using djongo package for a connector backend under django to the mongodb and define my models on it. models.py: class EventModel(BaseModel) name = models.CharField(max_length=20) class CalendarModel(BaseModel): name = models.CharField(max_length=20) color = models.CharField(max_length=20) event = models.ForeignKey(to=EventModel, on_delete=models.SET_NULL, null=True) and admin.py: from django.contrib import admin from .models import CalendarModel, EventModel @admin.register(CalendarModel) class CalendarAdmin(admin.ModelAdmin): exclude = ['_id'] @admin.register(EventModel) class EventAdmin(admin.ModelAdmin): exclude = ['_id'] At first it is ok with like that on sqlite backend and it's work when djongo backend without foreignkey field but send me an error when its on djongo backend and has foreignkey field. It said: error image And I can't create a new object with relation on it. How I can fix it? -
Field 'id' expected a number but got ObjectId
I'm studying djongo and i'm trying to create a platform that automatically assign a random amount (between 1 and 10) bitcoins to all new registered users. My code is following: #views.py def register_page(request): if request.user.is_authenticated: return redirect('order_list') form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,'Account successfully created, welcome '+ username) newUserProfile(username) #<------ this is the function to generate the profile with random BTC return redirect('login') context = {'form':form} return render(request, 'api/register.html', context) #models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) BTC = models.FloatField() balance = models.FloatField() pending_balance = models.FloatField() pending_BTC = models.FloatField() #utils.py def newUserProfile(username): user = User.objects.get(username=username) id = user.id BTC = round(random.uniform(1,10),2) profile = UserProfile.objects.create(id=id, user=user, BTC=BTC, balance = 0, pending_balance = 0, pending_BTC = 0) profile.save() When i push the register button on my webpage i get: Exception Type: TypeError Exception Value: Field 'id' expected a number but got ObjectId('606d892cb5d1f464cb7d2050'). but when i go in the database the new profile is regularly recorded: # userprofile tab {"_id":{"$oid":"606d892cb5d1f464cb7d2050"}, "id":49, "user_id":49, "BTC":3.26, "balance":0, "pending_balance":0, "pending_BTC":0} # auth_user tab {"_id":{"$oid":"606d892cb5d1f464cb7d204f"}, "id":49, "password":"pbkdf2_sha256$180000$nNwVYtrtPYj0$/wwjhAJk7zUVSj8dFg+tbTE1C1Hnme+zfUbmtH6V/PE=", "last_login":null, "is_superuser":false, "username":"Aokami", "first_name":"", "last_name":"", "email":"Aokami@gmail.com", "is_staff":false, "is_active":true, "date_joined":{"$date":"2021-04-07T10:27:56.590Z"}} How to resolve this, or atleast avoid the error page since i obtained anyway what i needed? -
Django orm get other foreign key objects from foreign object
I'm puzzled with this probably easy problem. My Models: class DiseaseLibrary(models.Model): name = models.CharField(max_length=255) subadults = models.BooleanField(default=False,blank=True) adults = models.BooleanField(default=False, blank=True) def __str__(self): return self.name class BoneChangeBoneProxy(models.Model): anomalies = models.ForeignKey('DiseaseLibrary', on_delete=models.CASCADE, related_name='anomalies') technic = models.ForeignKey('Technic', on_delete=models.CASCADE, related_name='technic_proxy') bone_change = models.ForeignKey('BoneChange', blank=True, null=True, on_delete=models.CASCADE, related_name='bone_change_proxy') bone = TreeManyToManyField('Bone', related_name='bone_proxy') From DiseaseLibrary I'd like to get all Objects that link to it via related_name "anomalies". Namely "technic_proxy", "bone_change_proxy", "bone_proxy" which are ForeignKeys to other models. I would expect to get access by the related name "anomalies" and _set >>> ds = DiseaseLibrary.objects.all().first() >>> ds.name 'Some nice name' >>> ds.anomalies <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x107fa4f10> >>> ds.anomalies_set.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'DiseaseLibrary' object has no attribute 'anomalies_set' >>> How can I access all ForeignKey values in model BoneChangeBoneProxy through model DiseaseLibrary? -
django-plotly-dash, 'Error at Line 0 expected string or bytes-like object' in base.html?
I am working through a tutorial on connecting django-plotly-dash to a Django project. Before I added the Plotly components, I was able to access my templates without issue. Once I set up the various Plotly requirements, I now get this error when I try to go to the main page: error capture I'm not sure where to start figuring out what this is telling me, there are some similar issues on Google (and Stack Overflow) bet I am not seeing finding anything that seems related. Also, I'm basically a noob, so be gentle. -
How to get the value of a specific field in a form in Django view function?
I am trying to achieve a load-up process in my system where the user will input the load amount and add it to a user's current load. How can I get the amount entered in my view function? Here's my function in my views.py def LoadWallet(request, pk): user = get_object_or_404(User, id=request.POST.get('user_id')) user_wallet = user.wallet if request.method == 'POST': form = LoadForm(request.POST) if form.is_valid(): user_wallet = user_wallet+form.instance.load_amount User.objects.filter(id=pk).update(wallet=user_wallet) return HttpResponseRedirect(reverse('user-details', args=[str(pk)])) and the form in my template file <form action="{% url 'load-wallet' user.pk %}" method="POST"> {% csrf_token %} <label for="load_amount">Load amount</label> <input type="text" class="form-control" id="load_amount" onkeyup="replaceNoneNumeric('load_amount')"> <button type="submit" name="user_id" value="{{ user.id }}" class="btn btn-md btn-success" style="float: right; margin: 10px 5px;">Load</button> </form> Right now I tried this but it's returning "name 'LoadForm' is not defined". Should I declare the LoadForm first? Is there a better way to implement this? Thank you! -
django - set verbose_name to object name
How can I set the score charFields verbose_name in GamePlayers to the person.name attribute that it relates to? The Person model has data that is already created & is not empty. class Game(models.Model): name = models.CharField(verbose_name="Game Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) person = models.ManyToManyField( Person, through='GamePlayers', related_name='person' ) class Person(models.Model): name = models.CharField(verbose_name="Name", max_length=250) def __str__(self): return self.title class GamePlayers(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) score = models.CharField(max_length=6, verbose_name=person.name) def __str__(self): return f"game: {self.game.title}" -
Django multi-table inheritance: parent data not saved
I'am using Django multi-table inheritance for the first time. I have 2 child models (Psychosocial 1 and Psychosocial 2) that inherit from one parent model (Invalidite) I am using Class Based Views (Create and Update) and Have developped forms and templates for Psychosocial 1 and Psychosocial 2. All is working well for Psychosocial 1 but not for Psychosocial 2. When I create a instance of Psychosocial 1, an instance of Ivalidite is created and fields from Invalidite are saved. I do the same with Psychosocial 2 but even if an instance Invalidite is created when an instance of Psychosocial is created but fields from Invalidite are not saved. When I debug in form_valid() method of Psychosocial2Create CBV, all fields from Invalidite return None. I do not understand what is the problem? class Invalidite(models.Model): """ A class to create a disability instance. """ hdq_ide = models.AutoField(primary_key=True) hdq_pat = models.CharField('Patient', max_length=4, null=True, blank=True) hdq_num = models.IntegerField('Test HDQ n°', null=True, blank=True) class Meta: db_table = 'crf_hdq' verbose_name_plural = 'Invalidites' ordering = ['hdq_ide'] def __str__(self): return f"{self.hdq_ide} - {self.hdq_pat}" class Psychosocial1(Invalidite): """ A class to create a psychosocial 1 instance. """ ide = models.AutoField(primary_key=True) ver = models.BooleanField("Fiche verrouillée", null=True, blank=True, default=False) ps1_dat = models.DateField('Date … -
Django for loop in template goes crazy
this loop: {% for address in item.customeraddresses_set.all %} {% if address.Is_Default_Billing_address == 1 %} <td> {{ address.Zip }} </td> <td> {{ address.Street }} </td> <td> {{ address.City }} </td> <td> {{ address.Country }} </td> {% else %} <td>---</td> <td>---</td> <td>---</td> <td>---</td> {% endif %} {% empty %} <td>---</td> <td>---</td> <td>---</td> <td>---</td> {% endfor %} goes crazy, I added another address and set it as Billing address, and now it prints empty and the address: xxx xxx WC-1000 +4528832155 xxx@xxx-computer.dk --- --- --- --- 25813 Am Hasselberg 8 Husum Germany 2. april 2021 whats going wrong here? -
adjust the number of rows by rowspan
I want to send the django lists template to html, but I can not sure the number of values in the list. When that have 2 values I can make a beautiful table, but when the values in the list change to less or more than 2, the size of table was not fit. Is any method to let the rowspan changeable and fit the number of value <table class="table table-bordered" id = "table2"> <thead class="thead-light"> <tr> <th rowspan="2" style="width:5%" scope="rowgroup">title</th> {% for name, accuracy in item %} <tr> <th scope="row">{{name}}</th> <th scope="row">{{accuracy}}</th> </tr> {% endfor %} </tr> </thead> </table> -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed in django
i keep on getting the above error on creating a new user model when creating users using postman here is my code. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from wallet.models import Transfer, Payment, Transaction, Wallet class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, name, phone, password,pin_code,confirm_pin,expected_delivery_month,email=None): user = self.model(name=name,phone=phone, email=email,pin_code=pin_code,confirm_pin=confirm_pin, expected_delivery_month=expected_delivery_month ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,name,phone,password,pin_code,expected_delivery_month,email=None, ): user = self.create_user(name,phone,password,email,pin_code,expected_delivery_month) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): name = models.CharField(max_length=120) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format +256706626855. Up to 10 digits allowed.") phone = models.CharField('Phone', validators=[ phone_regex], max_length=17, unique=True, null=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, null=True) is_admin = models.BooleanField(default=False) #now i need to add the pin coz its what am going to base on for the user creattion as the OTP pin_code = models.IntegerField(blank=False,unique=True)#vital here confirm_pin = models.IntegerField(blank=False)#this field here is to help in the confirmation of the pin expected_delivery_month = models.CharField(blank=False,default='january',max_length=20) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['name','pin_code'] def __str__(self): return self.name class Meta: unique_together = ("phone","pin_code")#since i need each phone number to have a unique pin code @property … -
Change Plotly Graph for mobile
I have created a graoh that looks good in the web browser, but looks terrible in mobile. Is there any way with plotly or django to help it look better in mobile? I came across an article showing how to make a mobile view within plotly but it appears they took that option out since the article came out, as I could not find the option anywhere. I'm currently using an iframe to embed it into a blog post. Here is what it looks like on web page And here is what it looks like on mobile: And here is the iframe html im using to embed it into my blog post. <p><iframe height="525" id="igraph" scrolling="no" seamless="seamless" src="https://plotly.com/~JakeSpeers/13.embed?showlink=false" style="border:none;" width="100%"></iframe></p> There has to be a better way to make it look better on mobile. Thanks in advance -
How would I manage to upload al the rows with the django view?
I posted this question here and got a suggestion. I managed to go through it but wasn't able to implement it for the import part[I managed export]. I'm therefore back with the question. Could I have a way to loop through all the rows in the uploaded file and have all the data uploaded. Currently it uploads only one item, one row. def UploadTeachersView(request): message='' if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as tmp: tmp.write(excel_file.read()) book = xlrd.open_workbook(path) sheet = book.sheet_by_index(0) obj=TeacherData( school_id = sheet.cell_value(rowx=1, colx=1), code = sheet.cell_value(rowx=1, colx=2), first_name = sheet.cell_value(rowx=1, colx=3), last_name = sheet.cell_value(rowx=1, colx=4), email = sheet.cell_value(rowx=1, colx=5), phone = sheet.cell_value(rowx=1, colx=6), ) obj.save() finally: os.remove(path) else: message='Invalid Entries' else: form = NewTeachersForm() return render(request,'upload_teacher.html', {'form':form,'message':message}) -
django ajax display nothing in for loop
i have to use for loop inside my ajax request , i used django inlineformset , when admin selects an item it has to return back the price , but it doesnt work in for loop class Item(models.Model): items = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=3)#i have to return this price def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice_no = models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=3)#when selecting an item , the price return back and write in the price field my views.py @login_required def check_price(request): item = request.GET.get('invoice-0-item',None) price = Item.objects.get(id=item).price print(price) data = { 'price':price, } return JsonResponse(data) and i dont know how to iterate through the number of forms to achieve this @login_required def check_price(request): for i in range(length of forms): item = request.GET.get('invoice-'+i+'-item',None) #etc <form method="POST">{% csrf_token %} {{items.management_form}} <div class="p-1 pr-2 pb-1 text-xs border border-black rounded-lg flex flex-wrap" style="direction: rtl;"> <div class="flex w-8/12 lg:w-9/12"> <div class=""> customer name : </div> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.customer | add_class:'bg-transparent w-full text-center focus:outline-none customer' }} {% if form.customer.errors %} <div class="redCOLOR pb-1 my-0 text-center rounded-lg w-full md:w-6/12 mx-auto">{{form.customer.errors}}</div> {% endif %} </div> </div> </div> <!-- … -
Django merge duplicate rows
I have a table like this. id|name |user_id |amount| --|---------------------|------------|------| 1|Name1 |1 | 4| 2|Name1 |1 | 7| 3|Name2 |1 | 5| I want to merge rows that have the same name and user_id and that should look like this: id|name |user_id |amount| --|---------------------|------------|------| 1|Name1 |1 | 11| 2|Name2 |1 | 5| Django ver = 3.1 -
Uncaught TypeError: Cannot read property 'style' of null when using data-SOMETHING attribute to pass parameter to JavaScript function
I'm new to coding and I'm trying to hide a paragraph using JavaScript. This is my HTML {% for post in posts %} <div class="container p-3 my-3"> <div class="card"> <div class="card-block px-1"> <h4 class="card-title"> <a href="{% url 'profile' post.user.id %}">{{ post.user }}</a> </h4> <p class="card-text" id="{{ post.id }}">{{ post.content }}</p> <textarea style="display: none;" id="edit-view">{{ post.content }}</textarea> <p class="card-text" id="time">Posted on: {{ post.timestamp }}</p> {% if post.user == request.user %} <button type="button" class="btn btn-primary" id="edit-btn" data-text="{{ post.id }}">Edit</button> {% endif %} <button type="button" class="btn btn-primary" id="save-btn" style="display:none;">Save</button> <p class="card-footer">{{ post.like }} Likes</p> </div> </div> </div> {% endfor %} Looking at the source code I could verify that the post.id context is correctly displayed in both the data-text attribute and the id of the paragraph I want to hide. This instead is my JavaScript function (which I have in a separate js file): function edit(text) { // hide content document.querySelector(`#${text}`).style.display = 'none'; } I'm calling the function after loading the DOM and applying and event listener to all buttons with id of edit-btn: document.addEventListener('DOMContentLoaded', function() { // Adding event listener document.querySelectorAll('#edit-btn').forEach(function(button) { button.onclick = function() { console.log('Button clicked!') edit(); } }); }); Nevertheless I get the above error, as if the parameter … -
How do I solve this error in my view? Local variable 'result' referenced before assignment
This view complains of the local variable result being referenced before being assigned, please help me arrange well. def UploadTeachersView(request): if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) dataset = Dataset() new_persons = request.FILES['file'] imported_data = dataset.load(new_persons.read(), format='xls') result = ImportTeachersResource().import_data(dataset, dry_run=True) # Test the data import if result.has_errors(): messages.info(request,f"Errors experienced during import.") else: ImportTeachersResource().import_data(dataset, dry_run=False) # Actually import now messages.info(request,'Details uploaded successfully...') else: form = NewTeachersForm() return render(request, 'new_teacher.html',{'form':form, 'result':result}) -
HTTP 403 , running django with Nginx + Passenger + Django + Virtualenv
I just starting to learn how to use Pushion Passenger with nginx on my internal server. First, here is my passenger-memory-stats (penumpang:3.8) debian@debian-mon-lama ~/penumpang sudo /usr/sbin/passenger-memory-stats Version: 6.0.8 Date : 2021-04-07 14:41:42 +0700 ... ---------- Nginx processes ---------- PID PPID VMSize Private Name ------------------------------------- 24731 1 68.0 MB 0.4 MB nginx: master process /usr/sbin/nginx -g daemon on; master_process on; 24736 24731 68.2 MB 0.6 MB nginx: worker process 24737 24731 68.2 MB 0.7 MB nginx: worker process 24738 24731 68.2 MB 0.6 MB nginx: worker process 24739 24731 68.2 MB 0.6 MB nginx: worker process ### Processes: 5 ### Total private dirty RSS: 2.95 MB ----- Passenger processes ------ PID VMSize Private Name -------------------------------- 24717 298.3 MB 2.5 MB Passenger watchdog 24721 1190.6 MB 5.5 MB Passenger core ### Processes: 2 ### Total private dirty RSS: 8.05 MB Looks slight different than https://www.phusionpassenger.com/docs/advanced_guides/install_and_upgrade/nginx/install/oss/buster.html here is my nginx site-enabled (penumpang:3.8) debian@debian-mon-lama ~/penumpang cat /etc/nginx/sites-enabled/penumpang.site #FROM https://www.phusionpassenger.com/library/config/nginx/intro.html server { server_name debian-mon-lama; root /home/debian/penumpang; passenger_enabled on; passenger_python /home/debian/virtualenv/penumpang/3.8/bin/python; } venv created by debian@debian-mon-lama ~/penumpang virtualenv --prompt '(penumpang:3.8)' --python /usr/local/bin/python3.8 --system-site-packages /home/debian/virtualenv/penumpang/3.8/ here is my passenger_wsgi.py debian@debian-mon-lama ~/penumpang cat ./passenger_wsgi.py import sys, os #FROM https://help.dreamhost.com/hc/en-us/articles/360002341572-Creating-a-Django-project INTERP … -
i was creating a website using django and i got an error can anyone help me its a a typeerror
TypeError at /contact contact() got an unexpected keyword argument 'name' Request Method: POST def contact(request): global contact if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') desc = request.POST.get('desc') contact =contact(name=name,email=email,phone=phone,desc=desc,date=datetime.today()) contact.save() return render(request,'contact.html') -
Django postgresql query stuck when searching on negavie condition
I have this class name: Maybe it is the class Follower(models.Model): language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) class Language(models.Model): code_name = models.CharField(max_length=6, null=True, blank=True) def __str__(self): return self.code_name While searching for specific name it return values fast (few sec), (i.g language.code_name = "he"): he lang While adding the check for language.code_name != "ar", it can take few minutes ! Maybe design issue ? -
Ordered list with M2M for different models?
How can I create a List model that has many-to-many relationships with multiple different models in a specific order? E.g. models.py class ItemA(models.Model): ??? class ItemB(models.Model): ??? class List(models.Model): ??? Shell: a1 = ItemA.objects.create() a2 = ItemA.objects.create() b1 = ItemB.objects.create() b2 = ItemB.objects.create() list1 = List.objects.create() list2 = List.objects.create() # ??? Some code here that can associate # a1, a2, b1, b2 (in that order) with list1 and # a1, b1, a2, b2 (in that order) with list2 # so that list1.items can return a1, a2, b1, b2 (in that order) # and list2.items can return a1, b1, a2, b2 (in that order) Is this even possible? -
Django 3.2 AttributeError: 'TextField' object has no attribute 'db_collation'
I've an existing project on Django 3.1 and I upgraded my project to Django 3.2. I created an app called payment on my project. But When I make migrations. It trow an error AttributeError: 'TextField' object has no attribute 'db_collation' from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ # Create your models here. from simple_history.models import HistoricalRecords class TransactionType(models.TextChoices): CASH_IN = 'IN', _('Cash In') CASH_OUT = 'OUT', _('Cash Out') class TransactionMethod(models.TextChoices): STUDENT_TR = 'STT', _('Student Transaction') BANK_TR = 'BKT', _('Bank Transaction') SCHOOL_TR = 'SLT', _('School Transaction') Teacher_TR = 'TRT', _('Teacher Transaction') DONATE_TR = 'DET', _('Donate Transaction') class Payment(models.Model): id = models.AutoField(primary_key=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_by") updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="updated_by") transaction_amount = models.FloatField("Transaction amount") transaction_type = models.CharField(max_length=3, choices=TransactionType.choices, default=TransactionType.CASH_IN,) transaction_method = models.CharField(max_length=3, choices=TransactionMethod.choices, default=TransactionMethod.STUDENT_TR,) transaction_note = models.CharField(null=True, blank=True, max_length=200) is_approved = models.BooleanField(default=False) is_approved_by_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="approved_by", null=True, blank=True) created_at = models.DateTimeField(auto_now=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) history = HistoricalRecords() Full error message File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/asad/PycharmProjects/amarschool/venv/lib/python3.6/site-packages/django/core/management/base.py", … -
How to open and render and Excel file in django?
I am getting an error in Excel say: excel cannot open the file because the file format or file extension is not valid Hi I have a excel file that is being generated each morning. I want the user to be able to download the Excel file. def export_daily_report(request): output = pd.read_excel('crontab_files/daily.xlsx') response = HttpResponse(content_type='application/vnd.ms-excel') # tell the browser what the file is named response['Content-Disposition'] = 'attachment;filename="daiy_export.xlsx"' # put the spreadsheet data into the response response.write(output) # return the response return response I want to open the excel and then render the file so that the user can download it. -
Is there any API for value the vehicles in India [closed]
I'm a self-learning web developer. I'm working on an app that is for sells and buys used vehicles. Now I searching for an A API to value the vehicles as per the vehicle details that the user has given. So please help me for finding one.