Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to override the MIME type of a user uploaded file?
Users on my web dev forum can upload HTML files as attachments to their posts, to show their code. This is done through a Django FileField. How can I ensure that these uploads are then served with "text/plain" content type, rather than "text/html"? Because the purpose is for other people to look at the source code, not the rendered HTML. -
how to translate each and every row of csv file
some words of the row are getting translated, sometimes and sometimes not. from googletrans import Translator myfile=open("ElectricCarData_Norm.csv") f=myfile.readlines() translator=Translator() with open("Electric.csv", 'w',encoding="utf-8") as op: for line in f: #print(line) translation = translator.translate(line, src='en',dest='hi').text #print(line," ",translation) op.write(translation) op.write('\n') -
My usertype user and doctor is not setting true while registering user
I am a new bie in django, creating doctor appointment project. I have extend the abstractuser and set user type is_patient and is_doctor, user register and doctor register form is different. I want if the user register through user form is_user should set True if user register through doctor form is_doctor should set true. But its not setting true everytime registering. Below is my code. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User # Create your models here. class User(AbstractUser): is_user = models.BooleanField(default=False) is_doctor = models.BooleanField( default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class User_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) User.is_user = True fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=100,blank=False) address = models.TextField(max_length=500,blank=False) gender = models.CharField(max_length=7, blank=False) phone = models.CharField(max_length=12,unique=True,blank=False) Username = models.CharField(max_length=100,blank=False,unique=True) Userpassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname class dr_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) user.is_doctor = True fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) image = models.ImageField() specialisation = models.CharField(max_length=100,blank=False) qualificaton = models.CharField(max_length=100,blank=False) phone = models.CharField(max_length=12,blank=False,unique=True) gender = models.CharField(max_length=7,blank=False) address = models.TextField(max_length=500,blank=False) state = models.CharField(max_length=50,blank=False) city = models.CharField(max_length=50,blank=False) zip = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=50,blank=False) dUsername = models.CharField(max_length=100,blank=False,unique=True) dPassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname views.py def register(request): if request.method == "POST": fname = … -
Django unable to bind uploaded file
Clarification: I'm developing on top of the django admin module. I implemented a csv model upload using a simple FileField form, and read the uploaded text file with a TextIOWrapper without any problems. I am trying to add an intermediate screen warning the user of potential data loss. I'm basing it off the admin delete action confirmation screen. The problem I'm having is passing the in-memory uploaded file to the intermediate screen to access it upon user confirmation. I tried doing this with a bound form but the uploaded data seems to vanish. I am using a very simple form: class CsvImportForm(forms.Form): csv_file = forms.FileField() overwrite = forms.BooleanField() I have no problem when serving the GET view. Now comes the funny part. When processing the same view for a POST request, I try to bind the form as per the documentation, and pass it to the template builder: def import_csv(self, request, form_url="", extra_context=None): ... if request.method == "POST": form = CsvImportForm(request.POST, request.FILES) context.update({'form': form}) ... return TemplateResponse( request, "admin/import_confirm.html", context ) The import_csv method is part of my ModelAdmin subclass, and gets called by overriding the get_urls method. The template builds the form like so: <form action="{{ form_url }}" method="post" … -
How do I use HTTP status code enum as django model field choices?
I would like one of my django models to have a field like this: status = models.ImageField(choices=Status, max_length=20) but instead it would take directly from the HTTPStatus class -
how to bind data from a form vue js with Django using post axios?
I want to develop an interface that uploads a file with Vue js from my backend in django, I can't figure out the problem. but here is the error I got: "POST http://127.0.0.1:8000/upload/ 500 (Internal Server Error)" here the class "upload" in view.py: def upload(request): obj = None dict={} if request.method == 'POST': repo = Repository(username="fedoraAdmin",password="fedora2022") obj = repo.get_object(type=FileObject) obj.file.content = request.FILES['file'] obj.file.mimetype=request.FILES['file'].content_type obj.file.label=request.FILES['file'].name obj.label = request.POST['label'] obj.save() dict=obj.index_data() print(dict) return JsonResponse(dict) my form in forms.py: class UploadForm(forms.Form): label = forms.CharField(max_length=255, # fedora label maxes out at 255 characters help_text='Preliminary title for the new object. 255 characters max.') file = forms.FileField() Finally, my vue js code: <template> <div class="container"> <h1 class="title mb-6">Uploader</h1> <div> <form @submit.prevent="submitFile" enctype="multipart/form-data"> <input type="file" @change="uploadFile" ref="file"> <button>Upload!</button> </form> </div> </div> </template> <script> import axios from 'axios' export default { name: 'archivage', mounted() { document.title = 'Archivage | fedora' } , methods: { uploadFile() { this.file = this.$refs.file.files[0]; this.label=this.$refs.file.files[0].name }, performUpload() { const formData = { label: this.label, file: this.file} axios .post('/upload/',formData) .then(response => { console.log(response.data) ; }) .catch(error => { console.log(error) }) }, submitFile: function(){ this.performUpload() }, } } </script> -
Looping through nested dictionary in Django
I am trying out an implementation. Although I have figured the logic out, I am having issues representing it programatically. I need your help or guidance. Below is the detailed explanation of my code and what i am trying to achieve, please pardon me as it would be a long read. What I want to achieve I want to create an endpoint - /order/tradeadvisor/{{producer_order_id}}, so that if the endpoint is hit, then it should first record the producer_order_id in a variable, then it should go to the Order model and loop through it fetching all order_id, user_id with the user_type=1. After that it should, now produce a a single record where, the user caprice is equal to producer floorprice(where the producer is the logged in user) and then the user needed engery is equal to the producers surplus and then store this record in the Trade table. What i have done User.model: class User(AbstractBaseUser, PermissionsMixin): dso = models.ForeignKey(to=Dso,related_name='dso',null=True,on_delete=models.CASCADE) name = models.CharField(max_length=70) address = models.CharField(max_length=70) roleId = models.IntegerField(default=1) customerId = models.CharField(max_length=70, blank=False, default='') floorPrice = models.DecimalField(max_digits=10, max_length=255, decimal_places=2, null=True) capPrice = models.DecimalField(max_digits=10, max_length=255, decimal_places=2, null=True) tradeStrategy = models.CharField(max_length=255, null=True) username=models.CharField(max_length=255, unique=True, db_index=True) email=models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
Django ORM: slow SQL request using an update with a list of ids
I have some database speed issues when doing an update with Django. My request takes about 15s to be executed, updating ~1000 rows, which is quite slow Here is a simplified version of my code myList = Model.objects.filter( ... )[:nb] myListIds = [] for object in myList: ... myListIds.append(object.pk) Model.objects.filter( pk__in=myListIds ).update( ... ) I tried to look at the SQL request generated by Django, but it didn't teach me anything What am I doing wrong here ? -
Is There a way to store the username in a django model? [closed]
I am trying to store the user who submitted the form in the database model using django from django.db import models # Create your models here. class Message(models.Model): sent_by = #should hold the username msg = models.CharField(max_length=255) -
How to select multiple rows in a table and link them in the database?
I have a large table with different records. I want to be able to select multiple records (radio button) and link them together by clicking on a "link" button. In the background, there is a LinkId column which would be set to some consequent integer. What is the best design decision and which plugin/form/etc should I use? I'm not very familiar with Django. Thanks. -
Formatting ouput table in template from django.model
I am creating a currency exchange rate aggregator app. I have got next models. class Bank(models.Model): bank_name = models.CharField( max_length=30, blank=False, unique=True, ) class ExchangeRate(models.Model): USD_in = 'USD_in' USD_out = 'USD_out' EUR_in = 'EUR_in' EUR_out = 'EUR_out' RUB_in = 'RUB_in' RUB_out = 'RUB_out' USD_EUR_in = 'USD_EUR_in' USD_EUR_out = 'USD_EUR_out' exchange_choise = [ (USD_in, 'USD_in'), (USD_out, 'USD_out'), (EUR_in, 'EUR_in'), (EUR_out, 'EUR_out'), (RUB_in, 'RUB_in'), (RUB_out, 'RUB_out'), (USD_EUR_in, 'USD_EUR_in'), (USD_EUR_out, 'USD_EUR_out'), ] datetime = models.DateTimeField( auto_now_add=True, blank=False, ) exchange_type = models.CharField( max_length=12, choices=exchange_choise, ) rate = models.FloatField() bank_id = models.ForeignKey( Bank, on_delete=models.CASCADE, ) quantity = models.IntegerField( default=1, ) Basically two tables. One stores bank names, another exchanging currencies and their rates. So if I will output data from model as it is I will get next picture: If I would put it in html table, it would look like this. Notice, that each currency exchange rate takes one row (datetime, currency, rate, bank). And I want that each bank would have all its currency exchange rates in one row like in the picture bellow. I wonder, how can I do this? Do I need to perform some join operation or to write code in template to format it like this. View class: class … -
why FileSystemStorage() in django adding % forcefully in url of image
D:/Experiment/todoproject/media/download%202_f9xn1jm.jfif percentage % in url but not showing in name when i check it it is same image it should adjust name but this % sign is not name of image and that's why @shared_task(bind=True) def test_fun(self,url,id1): if not url== None: path_to_image ="D:/Experiment/todoproject"+url print(path_to_image) try: Image.open(path_to_image) not running -
How to save json data in Django database using queryset
I have this json data { 'items_data': [ {'item': 'Datalogger', 'hsn': '123', 'unit_name': 'BAG', 'unit_price': '100', 'quantity': '4', 'tax_code': 'GST 18', 'base_discount': '4', 'discount_value': 16, 'amount': 384, 'state': 'Maharashtra', 'invoice_number': 'TES-0822-97', 'tax_no': '18', 'tax_name': 'GST', 'base_Amount': 400, 'CGST': 36, 'SGST': 36}, {'item': 'Datalogger', 'hsn': '123', 'unit_name': 'BAG', 'unit_price': '100', 'quantity': '4', 'tax_code': 'GST 28', 'base_discount': '4', 'discount_value': 16, 'amount': 384, 'state': 'Maharashtra', 'invoice_number': 'TES-0822-97', 'tax_no': '28', 'tax_name': 'GST', 'base_Amount': 400, 'CGST': 56, 'SGST': 56}], 'invoice_num': 'TES-0822-97', 'gst_data': [ {'tax_no': '18', 'totalGST': 72, 'total_base_amount': 400, 'cgst': 36, 'sgst': 36}, {'tax_no': '28', 'totalGST': 112, 'total_base_amount': 400, 'cgst': 56, 'sgst': 56} ] } Now I want to get items data and store into database by query set. how can I save this by using query set objects? I am doing this code def get_invoice_items(request): json_body = json.loads(request.body) print(json_body) for data in json_body["items_data"]: print(data) items=Items_Details.objects.bulk_create(data) print(items) return JsonResponse({"message" : "Request Handled.."}) but getting error -
How to post/delete data from form into database using Django?
I am using a form to post a record to my database in Django. The form looks something like this: <form> <div>Field 1</div> <input/> <div>Field 2</div> <input/> ... <a id='save'>Save</a> </form> I am using an event listener to let me know when this Save link has been clicked. When it is clicked, I would like to store the fields as a record in the database. Here is my JS: const savebtn = document.querySelector('#save'); savebtn.addEventListener('click', showSelected); function showSelected(e) { // post record to database here window.location.replace("/"); // redirect to home page I am hoping to use some python to post this record like shown below: e = Entry() e.field1 = 1 e.field2 = 2 e.save() But I don't know how I can access a python function within JS. I'm thinking maybe a template tag could work here but can't figure out how to use it. Ideally I wouldn't have to rewrite the form as the formatting is kind of specific, is there a way to make this work? -
How to add nested serializer field
I have a nested serializer which creates the objects like they are supposed to but also return an error. Models: class Trip(models.Model): startTime = models.DateTimeField() endTime = models.DateTimeField() def __str__(self): return str(self.startTime) + " - " + str(self.endTime) class TripFaceDetection(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, blank=True) firstFace = models.DateTimeField() lastFace = models.DateTimeField() faceCount = models.IntegerField() Serializers: class TripSerializer(serializers.ModelSerializer): faces = TripFaceDetectionSerializer() class Meta: model = Trip fields = ('id', 'startTime', 'endTime', 'faces') def create(self, validated_data): face_data = validated_data.pop('faces') trip = Trip.objects.create(**validated_data) TripFaceDetection.objects.create(trip=trip, **face_data) return trip The objects are created but I also get the error: backend_1 | AttributeError: Got AttributeError when attempting to get a value for field faces on serializer TripSerializer. backend_1 | The serializer field might be named incorrectly and not match any attribute or key on the Trip instance. I understand I don't have the field within the Trip model, but I expect that since I define the field in the serializer and create it in the create method that it shouldn't return this error. How can I get rid of this error while using faces for both reading/writing as well as leaving my model structure as-is? -
How to implement Auh0's Direct Password Change feature using Management API in Django?
I have a Django App, and I am trying to use Auth0 for my Django App's authentication. I have successfully integrated Login and Logout using social-auth-app-django library. But I am facing a lot of hurdles in implementing Auth0's Management API to use direct password change feature in Django? I tried to follow what this Auth0's official documentation's link says to implement Auth0's Management API for direct password change feature, but it is throwing Error Code 500, and I am not understanding what I did wrong. The link shows the following example to implement Auth0 Management API for firect password change feature in Django: import http.client conn = http.client.HTTPSConnection("") payload = "{\"password\": \"NEW_PASSWORD\",\"connection\": \"CONNECTION_NAME\"}" headers = { 'content-type': "application/json" } conn.request("PATCH", "/dev-9fj5kydc.us.auth0.com/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) And my implementation for the same is: import http.client user = self.request.user NEW_PASSWORD = form.cleaned_data["new_password1"] CONNECTION_NAME = settings.AUTH0_CONNECTION_NAME DOMAIN = settings.SOCIAL_AUTH_AUTH0_DOMAIN USER_ID = user.auth0_id URL = f"/{DOMAIN}/api/v2/users/{USER_ID}" conn = http.client.HTTPSConnection("") payload = f"{{\"password\": \"{NEW_PASSWORD}\",\"connection\": \"{CONNECTION_NAME}\"}}" headers = { 'content-type': "application/json" } conn.request("PATCH", URL, payload, headers) res = conn.getresponse() data = res.read() I have double checked that everything is fine by printing values in console and all variables hold correct values. … -
should pulled API data be stored inside a database
I am creating my own django project to show stats of fantasy premier league players (FPL) where i use API data from another website. In my own website i want users to be able to search and query these players based on certain attributes such as goals scored, minutes played etc... Am i best to store these values inside my own database to make the querying process easier and more efficient OR just filter out certain players from the API data in the json format OR do a combination of both methods -
Save python output into Django Models
I have this code in my views.py: def home_output(request): commandRun = 'python script.py' data = os.system(commandRun) print(data) return render(request, 'home-view.html', {'data': data}) So when I open the page in Django, there is button to run the above code. When I run the server, and click the button, I get errors on the screen, but I can see the output in my terminal, which means, button worked and ran the script. All I want is to capture that output, and show it on the web page. I'm new to Django, so I don't know how to approach this problem. Do I have to modify my script to go to django.models and save some data? Or should I do something in Django to capture the data? I need some guidance like how to go forward.. -
Django oscar cannot import 'Basket' and 'Order'
i'm running into an issue where the oscar library attempts to import 'oscar.apps.orderoscar'. throwing the following error: File "/usr/lib/python3.10/importlib/init.py", line 139, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'oscar.apps.orderoscar' It seems to me that the logical import should be 'oscar.apps.order' but it somehow won't trigger that import. I've ran the following command to grab all the 'oscar.apps.orderoscar' occurences within my django project: $find ./ -type f -exec grep -H 'oscar.apps.orderoscar' {} ; It outputs the following occurences: ./shop/shop/pycache/.settings.cpython-310.pyc.swp: binary file matches ./shop/shop/pycache/settings.cpython-310.pyc: binary file matches The .pyc files seem to be immutable from a security perspective as far as i could tell I've attempted to set a breakpoint in the '/usr/lib/python3.10/importlib/init.py' def import_module(name, package=None): if name == 'oscar.apps.orderoscar': name = 'oscar.apps.order' set_trace() This breakpoint is never reached. Any help or tips … -
django cors HTTP/1.1 200 OK
Can someone help me for this cors django problem. I request a link to get value but cors won't let me do this. image1 image2 function get_log_modal(id) { clearInterval(logInterval); $('#log_container').html("") $(location).attr('href', '#analysis_log'); logInterval = setInterval(function () { console.log("id", id) $.ajax({ url: `https://blablablabla/${id}/`, method: "GET", success: function (res) { . . . That is my cors problem -
Django admin list : how to specify custom field instead of model __str__ method?
I have a model that has multi attributes rendered in __str__ method. I only want to display the name attribute in the admin list display. How do I achieve this without overriding __str__? In the example below I have tried using list_display in the admin model but Django still renders the attributes in __str__ defined for the model. Model class Product(models.Model): """ Product """ id = models.PositiveBigIntegerField(primary_key=True) attributes = models.JSONField() labels = models.JSONField() name = models.TextField() relative_url = models.TextField() image = models.URLField() delivery = models.TextField() online = models.BooleanField() is_customizable = models.BooleanField() is_exclusive = models.BooleanField() url = models.TextField() max_price = models.PositiveIntegerField() min_price = models.PositiveIntegerField() currency = models.ForeignKey(Currency, on_delete=models.CASCADE) discount_percentage = models.PositiveSmallIntegerField(default=0) recommended_retail_price = models.PositiveIntegerField() def __str__(self) -> str: product_str = ( f"id: {self.id}\n" f"attributes: {self.attributes}\n" f"labels: {self.labels}\n" f"name: {self.name}\n" f"relative_url: {self.relative_url}\n" f"image: {self.image}\n" f"delivery: {self.delivery}\n" f"online: {self.online}\n" f"is_customizable: {self.is_customizable}\n" f"is_exclusive: {self.is_exclusive}\n" f"url: {self.url}\n" f"max_price: {self.max_price}\n" f"min_price: {self.min_price}\n" f"currency: {self.currency}\n" f"discount_percentage: {self.discount_percentage}\n" f"recommended_retail_price: {self.recommended_retail_price}\n" ) return product_str def get_absolute_url(self) -> str: return reverse("web:product-detail", args=[self.id]) class Meta: db_table = "product" ordering = ["recommended_retail_price"] Admin class ProductAdmin(admin.ModelAdmin): list_display = ("name",) form = ProductForm Form class ProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" -
pass a parameter into serilazer under ListModelMixin
I am passing a parameter to a serilaizer like this: serializer = AttractionTicketSerializer(attraction, context={'api_consumer':request.auth.application}) I have a view which inherits from ListModelMixin, I need to pass this context param to the serilizer as well. here is a summarized view: class AttractionView(mixins.ListModelMixin, generics.GenericAPIView): authentication_classes = AUTHENTICATION_CLASSES permission_classes = [IsAuthenticatedOrTokenHasReadWriteScope] queryset = Attraction.objects.all() serializer_class = AttractionSerializer def get(self, request: Request, *args, **kwargs): attractions: Dict[str, Any] = self.list(request, *args, **kwargs) return attractions Is there a way to do it? Thanx in advance -
How to stock a list in a Django Model?
I'm trying to stock a list in a Django Model like this : class Search(models.Model): result = models.CharField(max_length=100, null=True, blank=True) name = models.BooleanField(default=True) eotp = models.BooleanField(default=True) reference = models.BooleanField(default=True) date = models.BooleanField(default=True) contains = [] But I don't think that it's the best way to stock a list, because I have an error when i want to create an element (like this): new_search = Search(result=result, name=name, eotp=eotp, reference=reference, date=date, contains=contains) "Search() got an unexpected keyword argument 'contains'" Do you know if there is a better way to stock lists in django models or if I have to do this in another way ? Thanks -
Django Problem with count of model objects
I need to disable adding new users in the admin panel once the number of users exceeds a particular value. The code below works to remove the "add user" button when I test it with hard coded integers. However, this line does not appear to be returning the count of users without hard coding a count: usercount = CustomUser.objects.count() Any ideas for getting the count of users already added? The model: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group from django.contrib import admin from django.db.models import Count from django.db.models.signals import post_save class CustomUser(AbstractUser): full_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1) is_active = models.BooleanField(null=False, default=True) # disable add new user in the admin panel class RemoveAddNew(admin.ModelAdmin): usercount = CustomUser.objects.count() if usercount > 5: def has_add_permission(self, request, obj=None): return False The admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser, RemoveAddNew class CustomUserAdmin(RemoveAddNew, UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['username', 'email', 'full_name', 'age', 'is_staff', 'is_active'] fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('full_name', 'age', )}), ) add_fieldsets = UserAdmin.add_fieldsets + ( (None, {'fields': ('email','full_name', 'age', 'employee_type', … -
Why static files for drf views dont work on my hosing site, but on local it works
There is how it looks on hosting: enter image description here There is how it looks on local: enter image description here