Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run HtmlTestRunner Selenium UnitTests in Django GitLab Repository
I have a Django Project on a GitLab repository. I've created a Test Suite using Selenium, UnitTest and HtmlTestRunner in Python. I want to automatically run the tests when pushing in GitLab. I read something about GitLab CI, but I'm not sure how this can be made. -
how do I return an actually image instead of the array returned by sentinelhub py satelite data
I am trying to write an api endpoint using the sentinelhub py service using the process api module...that gets the NDVI index of place passed in by a geometry and returns its image now when I write this api everything works perfectly fine just that what I get is an array when testing with post man. response = request.get_data() returns an array and I can"t seem to get how to return the actually image using python class vegetativeIndexView(APIView): def get(self, request): #Credentials CLIENT_ID = 'client_id' CLIENT_SECRET = 'secrete' config = SHConfig() if CLIENT_ID and CLIENT_SECRET: config.sh_client_id = CLIENT_ID config.sh_client_secret = CLIENT_SECRET else: config = None evalscript = """ //VERSION=3 function setup() { return { input: [{ bands:["B04", "B08"], }], output: { id: "default", bands: 3, } }; } function evaluatePixel(sample) { let ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04) if (ndvi<-0.5) return [0.05,0.05,0.05] else if (ndvi<-0.2) return [0.75,0.75,0.75] else if (ndvi<-0.1) return [0.86,0.86,0.86] else if (ndvi<0) return [0.92,0.92,0.92] else if (ndvi<0.025) return [1,0.98,0.8] else if (ndvi<0.05) return [0.93,0.91,0.71] else if (ndvi<0.075) return [0.87,0.85,0.61] else if (ndvi<0.1) return [0.8,0.78,0.51] else if (ndvi<0.125) return [0.74,0.72,0.42] else if (ndvi<0.15) return [0.69,0.76,0.38] else if (ndvi<0.175) return [0.64,0.8,0.35] else if (ndvi<0.2) return [0.57,0.75,0.32] … -
Django send mail with slightly different templates
I am sending mail with django and I would like to send lots of mails at the same time to different users. I am aware that the recieverparameter takes a list with multiple users, but all of my email will have some small changes in the html-template which limits me to have only one messageobject per user. As for now I am just looping but is there a faster way? -
Why is my image field not getting updated in django?
Basically , in my django website , a user can register and make his profile . Now if he wants to change some data after creation of his profile , he can do it through the settings page . Now , one of the things that he can edit is his profile picture Here is the model of the user profile in question: class Vendor(models.Model): name = models.CharField(max_length=255) phone = models.CharField(blank=True, null=True, max_length=20) email = models.EmailField(blank=True, null=True) city = models.CharField(blank=True, null=True, max_length=40) state = models.CharField(blank=True, null=True, max_length=40) address = models.CharField(blank=True, null=True, max_length=200) pincode = models.IntegerField(blank=True, null=True) image1 = models.ImageField(upload_to='shop_images/', blank=True, null=True) latitude = models.DecimalField(max_digits=24, decimal_places=18, blank=True, null=True) longitude = models.DecimalField(max_digits=24, decimal_places=18, blank=True, null=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_balance(self): items = self.items.filter(vendor_paid=False, order__vendors__in=[self.id]) return sum((item.product.price * item.quantity) for item in items) def get_paid_amount(self): items = self.items.filter(vendor_paid=True, order__vendors__in=[self.id]) return sum((item.product.price * item.quantity) for item in items) This is the view that I created for updating the model @login_required def vendor_settings(request): vendor = request.user.vendor if request.method == 'POST': name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') city = request.POST.get('city') state = request.POST.get('state') address = request.POST.get('address') pincode = request.POST.get('pincode') … -
Django how to avoid rounding decimals in ArrayField?
I'm trying to save decimals in ArrayField, using Django and Django REST Framework, but somehow when I save my model instance with my array of decimals set, django rounds it and saves only integers without precision. I have a following PostgreSQL field in model: losses = ArrayField( models.DecimalField( max_digits=7, decimal_places=2, ), blank=True, ) I pass values by REST API in the following way: { "losses": [ 9.93, 5 ], } Here is validated array of decimals in DRF serializer: [Decimal('9.93'), Decimal('5.00')] My current result is: [10, 5] Expected result is: [9.93, 5] Does anyone know why django round my DecimalField in array, despite of I have decimal_places=2 in model field? Thanks! P.S. Changing losses array in Django Admin with decimals also rounds my decimals, so it's not a problem of DRF. -
How to run Django and hardware code together on raspberry pi
I'm new to raspberry pi and Django. I'm creating an application that has a webpage (on Django) and some relays. Django is working fine. It serving the page as http server and I have another small code in another py file. I dont know how to make these things work together. Django has manage.py file. Should I write my relay code into manage.py or should I have to create another py file. Thanks in Advance -
How to pass and display value from a model on a template from another app upon login in views.py
views.py models.py template of another app where it is redirected after logging in -
Optimize Video Delivery(media files) in Django
I am using Amazon S3 for storing and serving Static Files and Media Files. For delivering optimized images I am using sorl-thumbnail. I want to know how to deliver optimized video to users so that page load speed increases and at the same time users are delivered optimized video. My main aim is to load the video as fast as possible and to achieve optimized delivery by any methods available for Django web application, like the best methods and practices. -
Problem with inlines formset using django-extra-views
I'm Having 3 models in my django app: Car, Driver and Access. Each Car has a unique Acces and each Driver has a unique Car. I would like to create objects from all of these models at the same time in the same view using django-extra-views inline formset. This is what i've done so far. models.py class Car(models.Model): # Some fields access = models.OneToOneField(Access, on_delete=models.CASCADE, default="", related_name="Car") Class Driver(models.Model): # Some fields car = models.OneToOneField(Car, on_delete=models.CASCADE, related_name="Driver") Class Access(models.Model): # Some fields views.py class DriverInline(InlineFormSetFactory): model = Driver form_class = DriverForm factory_kwargs = {'can_delete': False} class CarInline(InlineFormSetFactory, CreateWithInlinesView): model = Car inlines = [DriverInline] form_class = CarForm factory_kwargs = {'can_delete': False} class CreateAccess(CreateWithInlinesView): model = Acces inlines = [CarInline] form_class = AccessForm template_name = "create.html" success_url = reverse_lazy('access:list') create.html <form method="post"> ... {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} ... <input type="submit" value="Submit" /> </form> I was expecting to get the Driver inline formset in the inlines and therefore be able to create a Driver as well an his Car and the Access of his Car. -
i ran "Django manage.py runserver" and i get a "NodeNotFoundError"
newbie to python so i followed "Django by example" after i finished the blog project i committed to GitHub repository master. Only for me to clone the project later and -
Django PostgreSQL - the password isn't saved to the database
I have a custom User model and a function in views.py to handle the registration. when I register a user with Postman for example all the user data is stored in the database correctly but the password -field remains empty. I think that causes the problem when I try to use a simple login -page - it never accepts my credentials (because there is no password in the database). Any ideas why the password isn't saved and how to fix it? I have a function like this in views.py when registering a new user: def register(response): if response.method == 'POST': form = RegisterForm(response.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.id = form.cleaned_data.get('id') user.save() username = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(username=email, password=password) return HttpResponse(status=201) else: form = RegisterForm() return HttpResponse(status=400) And this is my custom user model: class UserManager(BaseUserManager): def create_user(self, email, password): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('A user must have a email.') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user -
Is there a way to put an interactive globe on your Django website?
I was looking at the home page of github, and saw that they had updated it with an interactive globe. I did some research, and I was able to find out a little about the globe. I was unable to find a definet answer, but I know that this is a WebGL globe that was probably taken from a three.js library. Does anyone know of any way that I could put this globe in my HTML file on my website? Thank you to everyone who helps! -
Getting continuous data stream on server side in django
I am pretty new to django. I want to run an everlasting task on server side to get continuous data using websocket and store it in database. What will be the best approach to do this ? Best regards, -
Problem with the grading queue in the online judge
I am working on creating an online judge using django and I have the following problem: Let's say I have a website that can score 6 (this number can be changed by admin) submissions at the same time. A user logged into the website can submit a submission for grading and if there are currently 6 submissions being graded it will enter something called a "queue" and wait for one of the submissions to finish scoring it will start dot. Same problem with multiple users submitting submissions to my website. How can I do that? (Here I treat grading as a "task", no matter what the task does.) -
How to redirect to another page with a search term?
I have a search engine that works great in home/views.py: def home(request): ... form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = products.annotate( similarity=TrigramSimilarity('name', query), ).filter(similarity__gt=0.15).distinct().order_by('-similarity') # return render(request, 'search/search_results.html', locals()) return redirect(reverse('home:search_results')) else: form = SearchForm() ... return render(request, 'home/home.html', context) def search_results(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = products.annotate( similarity=TrigramSimilarity('name', query), ).filter(similarity__gt=0.15).distinct().order_by('-similarity') return render(request, 'search/search_results.html', locals()) else: form = SearchForm() return render(request, 'search/search_results.html', locals()) I also have in urls.py: app_name = 'home' urlpatterns = [ path('', views.home, name='home'), path('search_results/<query>', views.search_results, name='search_results'), ]\ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) How can I get a redirect to a page with url construction like this localhost/search_results/?query=['query']? -
Validation of Django Model form overwrie
Greeting people. I think this is pretty much a typical problem, but I can't find a way to solve it. Django admin has a model form, which always overwrites submitted fields. The most typical issue here is that user write changes that user didn't want to change (when data have been changed between opened and submit form) Do we have any best practice to avoide that? -
Django 'Upload a valid image' when using png and jpeg
I am trying to upload an image, when posting .gif it works, and not with jpeg and png -
How to load a trained model in django
I'm working on a django project where I have to use Doc2Vec model to predict most similar articles based on the user input. I have trained a model with the help of articles in our database and when I test that model using a python file .py by right clicking in the file and selecting run from the context menu its working. The problem is Now I'm moving that working code to a django function to load model and predict article based on user-given abstract text But I'm getting FileNotFoundError. I have searched how to load model in django and it seems the way is already OK. here is the complete exception: FileNotFoundError at /searchresult [Errno 2] No such file or directory: 'd2vmodel.model' Request Method: GET Request URL: http://127.0.0.1:8000/searchresult Django Version: 3.1.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'd2vmodel.model' Exception Location: C:\Users\INZIMAM_TARIQ\AppData\Roaming\Python\Python37\site-packages\smart_open\smart_open_lib.py, line 346, in _shortcut_open Python Executable: C:\Program Files\Python37\python.exe Python Version: 3.7.9 Python Path: ['D:\Web Work\doc2vec final submission', 'C:\Program Files\Python37\python37.zip', 'C:\Program Files\Python37\DLLs', 'C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Users\INZIMAM_TARIQ\AppData\Roaming\Python\Python37\site-packages', 'C:\Program Files\Python37\lib\site-packages'] Server time: Mon, 24 May 2021 12:44:47 +0000 D:\Web Work\doc2vec final submission\App\views.py, line 171, in searchresult model = Doc2Vec.load("d2vmodel.model") Here is my django function … -
How i can get plaint text from django-tinymce htmlfield?
I need to get only text from html field to add it to another field, to search from it so how can i do that? -
How do i have a different data for every account in Django
Excuse my lack of knowledge I'm a complete newbie to Backend Development. I've had this very simple model for testing class Text(models.Model): text = models.CharField(max_length=30) def __str__(self): return self.text And with that I have this simple app that saves text through a form and also I've made an entire basic login & sign up system with UserCreationForm and AuthenticationForm and with that I've made 3 different users. With my lack of knowledge, I'm expecting to see a completely fresh app with no text saved to it when I log in with brand new user. But instead I just saw the same texts saved as every other users. So my question is what Django method should I learn so that my text database is empty everytime I create a new user Thank you in advance -
How to get total in django template
My database have one col namely MaxSubjectMarks MaxSubjectMarks (Column name) 10 20 30 40 50 150 (I want 150 output) q = SubjectsMaximumMarks.objects.filter(SessionCode=SessionResult,ClassCode=StudentClass).values('MaxSubjectMarks').annotate(total=Sum("MaxSubjectMarks")) {{ q }} output => <QuerySet [{'MaxSubjectMarks': '10', 'total': 10.0}, {'MaxSubjectMarks': '20', 'total': 20.0}, {'MaxSubjectMarks': '30', 'total': 30.0}, {'MaxSubjectMarks': '40', 'total': 40.0}, {'MaxSubjectMarks': '50', 'total': 50.0}]> i want output Total = 150 -
Is there any way to join three tables for querying to find the aggregate sum of a field in django (query set api)?
i am a complete beginner in django i'm stuck with this problem and can't seem to find a solution to query it properly. T.T T.T django ver : 1.11 python ver : 2.7 let's say we have 3 models: class Coupon(models.Model): pass class CouponApplication(models.Model): """ Track application of a coupon. """ coupon = models.ForeignKey(Coupon, related_name="applications",verbose_name=("Coupon")) order = models.ForeignKey(Order, verbose_name=("Order")related_name='order_coupon_applications') class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_order', verbose_name="Customer") order_date = models.DateTimeField(verbose_name='Order Date and Time') shop = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='order_items') order_type = models.CharField('Type', choices=ORDER_ITEM_TYPE, default=INVENTORY) buy_get_discount = models.DecimalField(_('Buy & Get Discount')) sub_total = models.DecimalField(_('Sub Total'), max_digits=18, decimal_places=2) now for each coupon i need to find the gross sales of the products sold using it. I am finding it pretty hard to write a query for the same cos i need to annotate the sum of subtotal of order item to each coupon object and i guess this requires joining coupon application, order item and order table so far i've wrote this much: buy_gets_gross_sales = OrderItem.objects.filter(order_type=OrderItem.INVENTORY, buy_get_discount__gt=0, order_id__in=CouponApplication.objects.filter(coupon=OuterRef('pk'), ).values('order') ).values('order_type') gross_sales = buy_gets_gross_sales.annotate(gross=Sum('sub_total')).values('gross') gross_Sales_report = Coupon.objects.annotate( total_gross_sales =Round(Coalesce(Subquery(gross_sales, output_field=models.DecimalField()), Value(0))) ,) i know this wont work, but i need something of this sort. it is already throwing some … -
I am new to django,is it mandatory to use django authorization
Is it required to use django authorization or is it possible to implement my own code for authorization? Can we implement own authorization. -
DRF and admin static urls pointing to wrong location
I have a Django Rest Framework project running on a subpath /api, together with the frontend on the root /. When I go to /api and /api/admin I get messages in the console saying that the static is missing. The urls listed are /static/... instead of the expected /api/static/.... I found out that this was bug a bug in Django before version 3.1 by looking at the answers to related questions. Hence I upgraded to version 3.2.2. This should have fixed the problem, but it did not. Neither did clearing cache, recollecting static and restarting apache. What else could be the issue? Note: An environment with the same apache settings works when not placed on a subpath and not behind the proxy. The errors Settings: My pip packages: apache2.4 django version 3.2.2 python 3.8 djangorestframework 3.11.2 My Apache conf: <VirtualHost *:443> ... SSLProxyEngine on SSLProxyVerify none SSLProxyCheckPeerCN off SSLProxyCheckPeerName off SSLProxyCheckPeerExpire off ProxyPreserveHost on ProxyPass "/admin" "https://localhost:8081/api/admin" ProxyPassReverse "/admin" "https://localhost:8081/api/admin" ProxyPass "/api" "https://localhost:8081/api" ProxyPassReverse "/api" "https://localhost:8081/api" <Directory ${docroot}> Options FollowSymlinks Require all granted FallbackResource /index.html </Directory> ErrorLog ${APACHE_LOG_DIR}/frontend-error.log CustomLog ${APACHE_LOG_DIR}/frontend-access.log combined </VirtualHost> <VirtualHost *:8081> ... <Directory ${docroot}/${project}> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess API python-path=${docroot}:${docroot}/venv/lib/python3.8/site-packages display-name=api WSGIProcessGroup API … -
Django nameing conventions
I have tried to find best practice for naming conventions but I can't find a site that explains it. I would like to correct my project so it is up to standard and before deployment. I know that can take alot of time, but I think it is best to correct it now then later. I can tell what I have done and I hope some one tell me what I need to change. the project name: MyToolsProject apps name: myapp_ap, pages_app, to_do_list_app Class: Asset, AssetType functions: do_this(), happy() variables: var, this_variable objects: obj. this_obj Module: my_app_asset, my_app_asset_type Module fields: last_updated, notes templates: asset.html, asset_type.html url: path("asset_app/asset/", views.AssetListView.as_view(), name="asset_app_asset_list"),