Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am not able to upload files in tastypie
my models.py class Payment(models.Model): paid_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="payment_history" ) paid_at = models.DateTimeField(auto_now_add=True) voucher = models.FileField(upload_to=voucher_directory_path, null=True, blank=True) my resource.py class PaymentResource(ModelResource): class Meta: allowed_methods = ['get', 'post'] queryset = Payment.objects.all() resource_name = 'payment' excludes = ['paid_by',] authentication = OAuthAuthentication() authorization = Authorization() Note: OAuthAuthentication() is my custom authentication. I am getting this error django.http.request.RawPostDataException: You cannot access body after reading from request's data stream what I have tried is commenting OAuthAuthentication() is not working and also trying to add below class also not working, adding content-type: application/json or multiform/form-data header not working. And also trying to add below class in my modelresource also not working for me. class MultiPartResource(object): def deserialize(self, request, data, format=None): if not format: format = request.Meta.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(MultiPartResource, self).deserialize(request, data, format) And added in my resource class PaymentResource(MultiPartResource, ModelResource): #above code here pass Have I miss something ? new to tastypie -
Django Createsuperuser Bug?
Is there some sort of bug when you use createsuperuser in Django? I am literally typing the following: python manage.py createsuperuser. Here is what happens: 1) The first time I type this, it will say Username (leave blank to use 'whatever') : so I typed 'batman' It then says 'batman' is not recognized as an internal or external command, operable program or batch file. When I retype python manage.py createsuperuser, it accepts my answer of batman. I am on a Windows machine, has anyone seen this before? -
Proper way to upload video files to model without form in Django?
New to programming and have got in a bit of a tangle with this. I have a webpage which has a button "click" to run a python script. The script generates a video file which is then uploaded into a model. The video is then displayed on the webpage. What I have works and is based in part on this tutorial but in terms of the webpage I don't want the front end form functionality (choose file / upload buttons) I just want the "click" to make script button and video that is created. I am unclear how to remove the front end form stuff without breaking everything. Should I even be using a form? What is the proper way to do this? Here is the code I have so far: video.html {% load static %} <html> <head> <meta charset="UTF-8"> <title>Upload Videos</title> </head> <body> <h1>Video Uploader</h1> <form method='POST' action='' enctype='multipart/form-data' > {% csrf_token %} {{ form.as_p }} <input type='submit' value='Upload' /> </form> <br><br> <video width='400' controls> <source src='{{ MEDIA_URL }}{{ videofile }}' type='video/mp4'> Your browser does not support the video tag. </video> <br><br> </p> <p></p> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <button id="myClickButton" type="button">Click</button> <div id="myOutput"></div> <script> $("#myClickButton").click(function() { $.get("/output/", function(data) { $("#myOutput").html(data); }, … -
Inconsistent file paths in django rest framework
I have the following view: class UserProfileView(APIView): permissions_classes = [permissions.IsAuthenticated] def get(self, request): user = User.objects.get(id=request.user.id) serializer = UserPrivateSerializer(user) return Response(serializer.data) The following Model: class User(AbstractUser): pp = models.ImageField(blank=True) and the following serializer: class UserPrivateSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The following urls: urlpatterns = [ path('profile/', UserProfileView.as_view()) ] I response I get is: { "pp": "/media/WIN_20190423_18_50_32_Pro.jpg" } when I expect: { "pp": "localhost:8000/media/WIN_20190423_18_50_32_Pro.jpg" } I know it's not a model or serializer issue because I have other views that use the same model and serializer where it returns the full path. -
Django How to Create the Pip and Piplock file?
I am new to Django. How do Pipefiles and Pipefile.lock files get created? I created them earlier, but I'm not sure what I did. Thank you -
How can we link third party databases (specifically MS Access) to Django for the inspectdb utility?
I want to just automate model creation and also just double check against my manual models using Django's inspectdb utility. However, the database I want to observe is Microsoft Access and it's not very clear how I can do this properly. There is a django-pyodbc but only works for Django 1.4-1.10. Any thoughts on using Inspectdb for a Microsoft Access database? -
Trying to Edit a Foreign Key Field to one model in the other model
I have two models TextDocument and TranslatedText as shown below. I upload a pdf to another model (Document), and if it has text, perform some OCR and save the OCR text in the original_text field in TextDocument. If the text is not in English, I then translate it and store the translation in the translated_text field in TranslatedText. TranslatedText has a foreign key relationship to TextDocument. class TextDocument(models.Model): document_id = models.ForeignKey(Document, on_delete=models.CASCADE,) original_text_file_name = models.FileField('OCR File name', upload_to=settings.DOCUMENT_FOLDER_OCR, default=settings.DEFAULT_OCR_PATH, storage=OverwriteStorage()) original_text = models.TextField(default=get_default_text, blank=True) original_language = models.CharField(default=get_default_language, max_length=100) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") class TranslatedText(models.Model): document_id = models.ForeignKey(Document, on_delete=models.CASCADE,) text_document_id = models.ForeignKey(TextDocument, on_delete=models.CASCADE,) translated_text_file_name = models.FileField('Translated File name', upload_to=settings.DOCUMENT_FOLDER_TRANSLATION, default=settings.DEFAULT_TRANSLATION_PATH, storage=OverwriteStorage()) translated_text = models.TextField() translated_language = models.CharField(default=get_default_language, max_length=100) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") In the TransaltedTextAdmin change page I display the translated_text field in a TextBox so it can be edited if needed. I also want to display the TextDocument field orignal_text as an editable field so if the OCR messed up, the admin can change that, too. However, I only seem to be able to display the original_text field as a read_only field, and cannot … -
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/$']
I am trying to display a detail view from "Property" model. I am a bit confused so I don't know how to describe the situation, I never encountered it before. modeles.py import arrow from django.db import models from datetime import datetime from autoslug import AutoSlugField from model_utils.models import TimeStampedModel from django.urls import reverse from django.conf import settings class Property(TimeStampedModel): title = models.CharField(max_length=2000, null=True) # Localizare residence_complex = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) address = models.CharField(max_length=200, null=True) street_number = models.IntegerField() zipcode = models.CharField(max_length=200, null=True) building = models.CharField(max_length=200, null=True) entrance = models.CharField(max_length=200, null=True) apartament = models.CharField(max_length=200, null=True) reper = models.CharField(max_length=200, null=True) vecinatati = models.CharField(max_length=200, null=True) slug = AutoSlugField("Property Address", unique=True, always_update=False, populate_from="title", null=True) # Caracteristici class Destination(models.TextChoices): BIROURI = "birouri", "Birouri" REZIDENTIAL = "rezidentaial", "Rezidential" COMERCIAL = "comercial", "Comercial" destination = models.CharField("Destination", max_length=20, choices=Destination.choices, default=Destination.REZIDENTIAL) class Layout(models.TextChoices): DECOMANDAT = "decomandat", "Decomandat" SEMIDECOMANDAT = "semidecomandat", "Semidecomandat" NEDECOMANDAT = "nedecomandat", "Nedecomandat" CIRCULAR = "circular", "Circular" VAGON = "vagon", "Vagon" layout = models.CharField("Layout", max_length=20, choices=Layout.choices, default=Layout.DECOMANDAT) floor = models.DecimalField(max_digits=10, decimal_places=1, null=True) class ComfortType(models.TextChoices): UNU = "1", "1" DOI = "2", "2" TREI = "3", "3" LUX = "lux", "Lux" comfort_type = models.CharField("Comfort Type", max_length=20, choices=ComfortType.choices, default=ComfortType.UNU) class InteriorState(models.TextChoices): OTHER = … -
Copy an object with a form in a django CBV
I have a Django function-based-view that copies a model object using a ModelForm def my_model_copy(request, object_id): new_object = get_object_or_404(MyModel, pk=object_id) new_object.pk = None # autogen a new primary key (object_id by default) # some other unique fields that need updating new_object.import_id = uuid.uuid4() new_object.name = new_object.name + " - COPY" form = MyModelForm(request.POST or None, instance=new_object) # lots more code I am repeating in MyModelCreateView() I'm trying to update this to use my CreateView CBV to DRY out my code, but where do I set the initial instance of the object? I tried a couple places: overriding get() class MyModelCopyView(MyModelCreateView): def get(self, request, *args, **kwargs): # Not the right place... Where to put this code? super_response = super().get(request, *args, **kwargs) # make a copy of the object new_object = get_object_or_404(MyModel, pk=self.kwargs['object_id']) new_object.pk = None # autogen a new primary key (object_id by default) # some other unique fields that need updating new_object.import_id = uuid.uuid4() new_object.name = new_object.name + " - COPY" return super_response overriding get_form() def get_form(self, *args, **kwargs): form = super().get_form(*args, **kwargs) # make a copy of the object new_object = get_object_or_404(MyModel, pk=self.kwargs['object_id']) new_object.pk = None # autogen a new primary key (object_id by default) # some other unique … -
Django ModelForm - models.FileField or models.FilePathField - retrieve an absolute file path, without uploading the file
I have a Django ModelForm and I am trying to figure out a way to create a form field where the user can choose a file from the local filesystem, and the form will retrieve and store the absolute file path. Ideally, this would operate much like models.FileField does, but instead of actually uploading the file when the form is submitted, the form would just record the absolute file path. I have tried creating the FileField using "None" file_location = models.FileField(upload_to=None, max_length=300,) But setting the upload_to=None does not allow the form to submit, it gives me a validation error - This field is required. I have also tried creating the field as FilePathField file_location = models.FilePathField(path="/tmp/",) This will record the file path correctly, but I don't want to have a fixed root path. Is there any other way I could possibly make this work? Why do I want to do this? The form, in each instance, is recording a set of metadata about a specific video file. This data once captured is pushed out of django as a CSV and used in another workflow. These are huge video files that are not meant to be stored by Django, the CSV … -
Errors from async request I did not call
I have a Django project when I visit the site, I keep getting these errors from an async request that I didn't even call. I don't know what they are and why they are coming. I have missing elements on the page. I even cleared my cache but that didn't help. It works fine in the incognito window. Here are the errors: -
To display dataTable border in Pie chart Highcharts
The tabulation shown is done using Highcharts.drawTable as in, http://jsfiddle.net/BlackLabel/d36fmcj5/ Since the table is rendered inside the piechart div manually, I need a way to add a border to the tabledata if possible, something like this enter image description here Kindly help me out to fix this issue. $(function() { Highcharts.setOptions({ colors: [ '#1cc88a', '#008a59', '#6adfb6' ] }); Highcharts.drawTable = function() { // user options var tableTop = 200, colWidth = 60, tableLeft = 50, rowHeight = 20, cellPadding = 2.5, valueDecimals = 1, valueSuffix = ''; // internal variables var chart = this, series = chart.series, renderer = chart.renderer, cellLeft = tableLeft; // draw category labels $.each(series, function(serie_index, serie) { renderer.text( serie.name, cellLeft + cellPadding, tableTop + (serie_index + 1) * rowHeight - cellPadding ) .css({ fontWeight: 'bold' }) .add(); }); $.each(series[0].data, function(i) { renderer.text( series[0].data[i].name, cellLeft + colWidth - cellPadding, tableTop + (i + 2) * rowHeight - cellPadding ) .attr({ align: 'right' }) .add(); }); $.each(series[0].data, function(i) { renderer.text( Highcharts.numberFormat(series[0].data[i].y, valueDecimals) + valueSuffix, 150, tableTop + (i + 2) * rowHeight - cellPadding ) .attr({ align: 'left' }) .add(); }); } $('#container').highcharts({ chart: { //plotBackgroundColor: null, //plotBorderWidth: null, //plotShadow: false, events: { load: Highcharts.drawTable }, height: 400, … -
Display different pages in mobile and desktop view in django
hi i want to create the different page view for mobile and desktop in django framkework i have tried everything means i have got a tutorial in which they are doing it with middleware by 'm' word but i have don it without it and it show me result correct in print but not changes template dir in setting.py of djang project. middleware.py from django.conf import settings from django.utils.deprecation import MiddlewareMixin from user_agents.parsers import UserAgent # from django_user_agents import from django_user_agents.utils import get_user_agent mob='N' class MobileTemplatesMiddleware(object): """Determines which set of templates to use for a mobile site""" ORIG_TEMPLATE_DIRS = settings.TEMPLATE_DIRS def __init__(self, next_layer=None): """We allow next_layer to be None because old-style middlewares won't accept any argument. """ self.get_response = next_layer # print(ORIG_TEMPLATE_DIRS) #if obejct other that moddleaxin # def __init__(self, get_response): # self.get_response = get_response # # def __call__(self, request): # return self.get_response(request) def process_request(self, request): print("fdafaffdahfajhadjhj") # sets are used here, you can use other logic if you have an older version of Python MOBILE_SUBDOMAINS = set(['m', 'mobile']) domain = set(request.META.get('HTTP_HOST', '').split('.')) user_agent = get_user_agent(request) print(user_agent.is_mobile) if user_agent.is_mobile: # if UserAgent.is_mobile: settings.TEMPLATE_DIRS = settings.MOBILE_TEMPLATE_DIRS + self.ORIG_TEMPLATE_DIRS print("mobile view") else: settings.TEMPLATE_DIRS = settings.DESKTOP_TEMPLATE_DIRS + self.ORIG_TEMPLATE_DIRS print("desktop viw") settings.py ` ` … -
Creating clickable map in Python for web app
I need to create an interactive, clickable map for a website similar to the one in this link: https://thebusinesscouncil.ca/canada-us-partnership/ I am not experienced in web app development and am mostly familiar with Python so my first question is, which python libraries (if any) will allow me to create a clickable map where each click opens a window with information and a PDF link? The map itself will not have much detail beyond the district carve-up - functionality is the most important component. I am planning to use Django to do have the map hosted on the web. I am thinking of making the map a python object that will be embedded directly on the web page, along with drop down bars. As this is my first time using Django, I'd like to get a sense if this is the right application to use in order to carry out the project and if a python object is a good route to take in creating this map (related to my first question above). Also open to any alternative ways to build the map or the web app. -
how to add number of visits to my to my blog in django
kindly help out i want to add view counts to my view anyone that read the blog should be counted but the code i saw online wont work for me here is my model models.py class Blog(models.Model): title = models.CharField(max_length=100) overview = models.TextField() categories = models.ManyToManyField(Category) timestamp = models.DateTimeField(auto_now_add=True) view_count = models.IntegerField(default = 0) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) image = models.ImageField() summary = models.TextField(max_length=150)][1]][1] -
Assign a different class or id to a Choice Field choices in Django
I am new to Django and learning. I am currently using a form to display my model which has a field like this: SEVERITY_CHOICES= [ ('low', 'Low'), ('medium', 'Medium'), ('high', 'High') ] severity = forms.ChoiceField(label='Severity:', widget=forms.RadioSelect(), choices=SEVERITY_CHOICES) It is displaying Radio Select option for me which I select one. But what I want to do is color code each of the text background to a color. So Low would have a background of blue, medium with yellow, and high with red. When I look at the CSS after it is being rendered they are all assigned the same class, so I am not able to add color that way. I am also not sure how to assign a class to the individual choices. Is it possible to do? -
Browsers do not send Kerberos authentication token on Linux
I am trying to configure Kerberos authentication for an application I develop. When opening the app from a browser (Chrome or FF), I get the 401 response from server with WWW-Authenticate: Negotiate header, but the browsers do not send the negotiation token back to the server. Details My platform: Linux Mint I've got ticket for my user using kinit myusername@MYREALM.RU I can verify the ticket is valid with klist. If it's relevant, myusername for the realm differs from my linux user name. I've set network.negotiate-auth.trusted-uris and network.negotiate-auth.delegation-uris in Firefox to sd.mydomain.ru (I've also tried .mydomain.ru, http://sd.mydomain.ru). I've also set network.negotiate-auth.allow-non-fqdn to true. Opening the sd.mydomain.ru:8000 sends an AJAX request to sd.mydomain.ru:8000/accounts/kerberos/login/ which responds with 401 code and WWW-Authenticate header. Nothing happens afterwords. I've tried to set $ export NSPR_LOG_MODULES=negotiateauth:5 $ export NSPR_LOG_FILE=/tmp/moz.log then ran Firefox from that console. After opening the page the log is empty. I've tried using Chrome, running it as google-chrome --auth-server-whitelist="sd.mydomain.ru:8000" with the same effect as in Firefox (401 response from server, and nothing happens). Some more details If this can help, my application is a Django app using django-kerberos library. It uses the keytab file, acquired running a command (on Windows) ktpass -princ HTTP/sd.mydomain.ru@MYREALM.RU -ptype … -
why frontend changes in django visual studio code don`t carry out immediatly in browser
I am using Django with vs code, everything is almost good, but some problems when I make changes in frontend. Changes don`t carry out immedeatly in browser. Have to restart editor, but sometimes the changes carry out lately. Is that problem only in visual studio code, or django..??? Thank in advance... -
An image in media_root folder does not get displayed in Django template
An image in media_root does not get displayed. This is how the web page looks like. My code is located at https://github.com/tomaszm-web/Django-ecommerce Can you please help me to work out why the image does not get displayed? -
Display images in the list in HTML
I want to display as a list all of my medicines. I take the values from mysql database. But I cannot display images. I get meaningless output like b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01... instead of images. Here is my code. How can I fixed it? models.py class Medicine(models.Model): #user = models.TextField(User) medicine_name = models.CharField(max_length=100) medicine_info = RichTextField(verbose_name="notes") medicine_code = models.CharField(max_length=100) medicine_price = models.IntegerField() medicine_stock = models.IntegerField() medicine_image = models.ImageField(null=True, blank=True) def get_image(self): if self.medicine_image and hasattr(self.img_photo, 'url'): return self.medicine_image.url else: return def __str__(self): return self.medicine_name class Meta: ordering = ['medicine_name'] views.py def list_item(request): medicines = Medicine.objects.filter() return render(request, 'medicine_list.html', {'medicines': medicines}) medicine_list.html <table class='table'> <thead> <tr> <th>ID</th> <th>Name</th> <th>Info</th> <th>Barcode</th> <th>Stock</th> <th>Image</th> </tr> </thead> {% for medicine in medicines %} <tr> <td>{{medicine.id }}</td> <td>{{ medicine.medicine_name }}</td> <td>{{ medicine.medicine_info }}</td> <td>{{ medicine.medicine_code }}</td> <td>{{ medicine.medicine_price }}</td> <td>{{ medicine.medicine_image }}</td> </tr> {% endfor %} </table> -
How to insert data in several models simultaneously in django rest frame work
I have created a model named product which contains product id,product category(mobiles,laptops,cloths),name,price etc. I have also created three more models named mobiles,laptops and cloths(contains same field as product except category). what i want is that when i add product to my product data base then it will automatically insert the product based on its category in one of the three models(mobile ,laptop and cloths). how can i do this in django rest frame work. I know i can filter database based on category but i don't want to do that. -
IntegrityError at /addtocart/ NOT NULL constraint failed: stock_ordereditem.ordered_name
When I try adding to cart, I get the error 'IntegrityError at /addtocart/ NOT NULL constraint failed: stock_ordereditem.ordered_name' This is my code def addtocart(request): ordered_name = request.POST.get('ordered_name') price = request.POST.get('price') image = request.POST.get('image') put_item = OrderedItem(ordered_name=ordered_name, price=price, image=image) put_item.save() return redirect('cart') class OrderedItem(models.Model): ordered_name = models.CharField(max_length=50) price = models.FloatField() image = models.ImageField(upload_to='pics') def __str__(self): return self.name {% extends 'base.html' %} {% block title %} August.shop {% endblock %} {% block content %} <h3>Ordered Items</h3> <div class="container" style="margin-top: 50px;"> <div class="row"> {% for order in order %} <div class="col-xs-3"> <div class="card" style="width: 18rem;"> <img src="{{ order.image.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ order.name }}</h5> <p class="card-text">${{ order.price }}</p> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} I appreciate a very helpful answer. -
Execute celery task when worker is not running
I want the celery task to be executed even when a celery worker is not present. That celery task should work like a normal function and get executed anyway. -
How to change the sort order within one Django View
I have a django class Equity, which I copied the relevant portions of below. In most of my model views I am fine with the Meta ordering by 'equity_name.' However, I also have a property 'weighted_strength' which I would like to create a listview that views a list of the equitys as sorted by 'weighted_strength.' Normally, if weighted_strength were an ordinary model field, I could use order_by in my view to order by that field. However, since it is a property, it appears I cannot use order_by. If there is a way to either use order_by or to change the Meta ordering so I can just this once sort by weighted_strength I would greatly appreciate it. I've searched for a while online and found some vague information relating Django to Python properties but nothing too helpful. Thank you! class Equity(models.Model): equity_name = models.CharField(max_length=255) class Meta: ordering = ['equity_name'] @property def weighted_strength(self): weight = 0.50 dataset1 = self.data_set1() dataset2 = self.data_set2() num_data = len(dataset1) if (num_data != 0): total = 0 for i in range(num_data): total +=(weight**i)*(dataset1[i][0]-dataset2[i][0]) total = total*(1-weight)/(1-weight**num_data) self._weighted_strength = total return self._weighted_strength else: self._weighted_strength = 0 return self._weighted_strength -
How to improve performance of django bulk_create for large datasets? (PostgreSQL)
I have large csv-files with approximately 164 columns x 50000 rows and would like to import those files into a PostgreSQl-Database (12.2). Using Django 3.0.7 and Python 3.6.8 I created a model DataRow which has one field for each column. When importing a file, I first validate it by checking for missing values and so on. Then I create a DataRow-object for each row and try to load everything into the database using bulk_create. Here a stylized short version of my code: import pandas as pd data = pd.read_csv(myfile) validate_my_data(data) data_row_objects = [] for row in data: data_row_objects.append(DataRow(**row_to_dict(row))) DataRow.objects.bulk_create(data_row_objects, batch_size=3000) So far it works. Validating and appending all objects to data_row_objects takes like 8 seconds, which is okay. However the bulk_create-statement takes about 3 minutes which is not acceptable. So how can I improve the performance here? I already tried increasing/decreasing the batch_size but 3000 seems to be the most stable size so far. I have also read on some posts here on stackoverflow that importing a csv file directly to the database is much faster. However, I would rather use pure django only because in my opinion this is one of the exact purposes of django: avoiding direct communication …