Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST API CORS problems
I am trying to connect Django with React. So I created a REST Api and I was trying to access the data from React using fetch() method. And this problem occurred: Access to fetch at 'http://127.0.0.1:8000/api/project-list' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. settings.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'portfolioRest', 'corsheaders',] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", ] Fetch.js import React, { Component } from 'react' export class Fetch extends Component { componentWillMount() { this.fetchProjects() } fetchProjects() { fetch('http://127.0.0.1:8000/api/project-list') .then(response => response.json()) .then(data => console.log('Data', data) /* I just want to print out the data from the api*/ ) } render() { return ( <div> </div> ) }} export default Fetch -
How reliable are Django Signals?
Have some questions regarding Django Signals in general: Is there a possibility that signals are sent more than once? Is there a possibility that signals don't fire? Is there a way to ensure that signals are sent once and once only? Is there a way to "replay" the signal without replaying the actual event? Is there a package that stores Django signals in the DB to act as a history? Is there a package that can auto-retry signals that fail, kinda like webhooks with exponential backoffs? Thanks in advance! -
Filtering models Django
I have these models in my models.py: class Category(models.Model): main_category= models.ForeignKey(HovedKategori, on_delete=models.CASCADE) name= models.CharField(max_length=200) def __str__(self): return self.name class UnderCategori(models.Model): main_kategory= models.ForeignKey(Category, on_delete=models.CASCADE) supplier = models.CharField(max_length=200) price = models.IntegerField() title = models.CharField(max_length=200) img = models.CharField(max_length=200) info= models.CharField(max_length=200) link= models.CharField(max_length=200) def __str__(self): return str(self.supplier ) + " " + str(self.title) Ho do i query all the different category suppliers without repeating them? What i mean is if i have 10 different suppliers with 500 products combined how do i query the 10 different suppliers. Also im not sure if this is the correct data stucture i should use, if there are any tips on that, that would also be appretiated. -
How to do search with priority in django?
I'm using djangorestframework with mysql database. I have a view that returns a list based on a search query param. I'm using rest_frameworks.filters SearchFilter for the search based filtering. Here's my view: from rest_framework import filters from rest_framework.generics import ListAPIView ... class FooListView(ListAPIView): serializer_class = SymbolSerializer queryset = Symbol.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['field_A', 'field_B', 'field_C'] An example URL to call is: http://localhost:8000/symbols/symbols/?search=bird Now everything works fine but I need a feature that filters.SearchFilter doesn't support. I want my search to be ordered by priority of search_fields. For example here's two records: foo1 : {"field_A": "any", "field_B": "many", "field_C": "bar", "id": 3} foo2 : {"field_A": "many", "field_B": "any", "field_C": "bar", "id": 4} Now when I do a search with search='many' param, I want the view to return me a list which foo2 record is higher that foo1 ( like this [foo2, foo1] ) because I want the search's priority to be field_A score but It just returns me a list that is sorted by id ([foo1, foo2]). Any help? -
how to create a chat app in django from scratch without using any external modules [closed]
how to design a chat app in django from scratch .is it possible to do it without using Channels or any other external libraries -
Django model choice field: How to remove empty field ? Django form exclude a value from the list of choices?
how to remove a empty field? YEAR_IN_SCHOOL_CHOICES = [ (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), (GRADUATE, 'Graduate'), ] year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, ) Django form exclude a value from the list of choices example: 'Junior'? class ArticleForm(ModelForm): class Meta: model = Article fields = ['year_in_school '] -
how to apply css on form in django
I'm using form of django in my sign up page and i want to apply css on it. This is the sign up html : <div class="login-space"> <div class="sign-up-form"> <form method="POST" class="register-form" action="" id="register-form"> {% csrf_token %} <div class="group"> {{form.username}} </div> <div class="group"> {{form.email}} </div> <div class="group"> {{form.password1}} </div> <div class="group"> {{form.password2}} </div> <div class="group">{{form.country}}</div> <div class="group">{{form.age}}</div> <div class="group">{{form.preferences}}</div> <div class="group"> <input type="submit" name="signup" class="button" id="signup" class="form-submit" value="Register"> </div> <div class="foot"> <a href="{% url 'login' %}" class="signup-image-link">I am already member</a></div> </form> </div> </div> So how can i apply css on the fields( username, email ....). Can someone help please. Thank you so much. -
What became available_attrs on Django 3?
First of all, I'm new to Django, so please be nice with me :D I'm currently adapting .py files for Django 3 because the files I have are compatible for Django 2. So, some changes have been made for the new version and in a file, it's written : @wraps(view_func, assigned=available_attrs(view_func)) With the import : from django.utils.decorators import available_attrs I searched for an adaptation of available_attrs, and I quickly found that it has been removed for the new version. And when I launch the code, I have this : ImportError : cannot import name 'available_attrs' from 'django.utils.decorators' So I was wondering what should I write instead of available_attrs to make it work ? PS : Sorry for my bad english -
Why it gives me zero after running? and also I can't use (import python) statement?
The first picture is my function and I want to import all module to utils but, it doesn't work and also when I run this code it gives me zero -
How to distinguish forms inside of a class based views in Django?
so basically I'm trying to process 2 different model forms in the same Detail View. One form has 2 fields and expects input from the user (and is working fine), and the other form is just a button, that supposed to submit self.request.user to a model. My problem is, that for the first form I wrote a lot of validating functionality in the form_valid method. And I need to distinguish these two forms in order to validate them differently. forms.py # second form class WatchlistForm(forms.ModelForm): class Meta: model = Listing fields = ['watchlist'] widgets = {'watchlist': forms.HiddenInput()} views.py class ListingDetail(FormMixin, SuccessMessageMixin, DetailView): """ Handles listing view by get request Handles Bid processing & validation on post request """ model = Listing form_class = CreateBidForm form_class_2 = WatchlistForm initial = {'bid_amount': 'Bid'} def get_success_url(self): return reverse('listing_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(ListingDetail, self).get_context_data(**kwargs) print(f'\ncontext: {context}\n') # if 'bid_form' not in context: context['bid_form'] = CreateBidForm() # if 'watchlist_form' not in context: context['watchlist_form'] = WatchlistForm(initial={'watchlist': self.request.user}) try: context['bid_amount'] = Bid.objects.filter(listing=self.object.pk)[0].bid_amount except IndexError: context['bid_amount'] = 0 return context def post(self, request, *args, **kwargs): print(f'\n\nrequest.POST: {request.POST}\n\n') if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() if 'bid_form' in request.POST: form_class = self.get_form_class() else: form_class … -
Django print loop index inside List
I am trying to print the list of values from a list. This code works: <td id="b0">{{data.0.B}}</td> <td id="b1">{{data.1.B}}</td> <td id="b2">{{data.2.B}}</td> <td id="b3">{{data.3.B}}</td> I am trying to put this in a loop like so: {% for i in data%} <td id ='b{{forloop.counter0}}'> Data is{{ data.forloop.counter0.B }} </td> {% endfor %} This prints the td id as b0, b1 etc correctly. However it is unable to replace the forloop.counter0 inside data.forloop.counter0.B and is not printing it as data.0.B, data.1.B etc. How do I change the code so that data.forloop.counter0.B is printed in the loop as data.0.B, data.1.B etc? -
django web applicaton does not work in iframe
How can i show my django web application in iframe tag html? i do it , but when i fill out form i get forbidden error see this: views.py: from django.contrib.auth import authenticate , login , logout from django.contrib import messages from .models import User from django.views.decorators.clickjacking import xframe_options_exempt def user_login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,tag=cd['tag'],password=cd['password']) find = User.objects.filter(tag=cd['tag']) if user is not None: login(request,user) messages.success(request,'You logged successfully.','success') return redirect('roleplay:index') else: messages.error(request,'Your Username Or Password does not correct.','danger') else: form = UserLoginForm() return render(request,'account/login.html',{'form':form}) def user_logout(request): logout(request) messages.success(request,'You loged out successfully.','success') return redirect('roleplay:index') def user_register(request): if request.method == "POST": form = UserRegisterationForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = User.objects.create_user(cd['tag'],cd['fname'],cd['lname'],'Citizen',cd['password']) user.save() tag = form.cleaned_data.get('tag') password = form.cleaned_data.get('password') user2 = authenticate(tag=tag,password=password) login(request,user2) messages.success(request,'Your account has been created and you logged in.','success') return redirect('roleplay:index') else: form = UserRegisterationForm() return render(request,'account/register.html',{'form':form}) what should i do to fix it? i need this site run in iframe(another html page). -
How do I get rid of memory overflow when calling batch slurm?
I need to run another program with parameters based on the form data. I have a page handler on Django. It builds a .sh file from the form, this file is called in a separate process using Popen and SBatch. All this runs fine but the page itself hangs and memory overflow occurs via the python3 process. Below is a sample program: def sbatch_subproc(self, file_path): >>Creates .sh file. pop_sbatch = subprocess.Popen(args = ["sbatch", sh_file_path]) def post(self, *args, **kwargs): >>The path to the .sh file is created. proc = Process(target = self.sbatch_subproc, args=(sh_file_path)) proc.start() Example .sh file: #!/bin/sh srun ./program -param1 value1 -param2 value2 -param3 value3 exit 0 memory overflow of 5.4 GB -
How to create separate DB for every company in django?
I'm going to create Saas CRM system and now i'm trying to design a database architecture. Using separate DB for each company seems to me most efficient. But in this case new database must be created automatically after user's registration. How can i implement this on django? Or is there a better way to do this? -
Where do I define the Content-Type I want to receive in my Django API?
I have a Django app that only needs to receive requests with Content-Type: text/plain. Is there an option for that when using the GenericViewSet? -
Dropify not updating the image
I use dopify for create and update form file, I use my update with old input entry file with data-default-file.The problem with request.I can not know if the user remove older file or leave the older file the result request in django is always NULL. HTML CODE: <input type="file" name="photo" data-default-file="/media/{{ Staff.photo }}" class="dropify" accept="image/*" data-max-file-size="1M" /> <input required type="text" class="form-control ct-label text-navy" name="id_no" minlength="2" maxlength="15" placeholder="{% trans 'ID Card Number' %}" value="{{ Staff.id_no }}"> <input type="text" required class="form-control ct-label text-navy" name="name" minlength="2" maxlength="30" placeholder="{% trans 'Name' %}" value="{{ Staff.name }}"> <input type="text" required class="form-control ct-label text-navy" name="surname" minlength="2" maxlength="30" laceholder="{% trans 'Surname' %}" value="{{ Staff.surname }}"> Scripts Code: $('.dropify').dropify(); $('.dropify-fr').dropify({ messages: { default: "{% trans 'Drag and drop a file or click to add' %}", replace: "{% trans 'Drag and drop a file or click to change' %}", remove: "{% trans 'Remove' %}", error: "{% trans 'Sorry, the file is too large' %}" } }); var drEvent = $('.dropify').dropify(); drEvent.on('dropify.beforeClear', function(event, element) {console.log(element.file.name); return confirm("Do you really want to delete \"" + element.file.name + "\" ?");}); drEvent.on('dropify.afterClear', function(event, element) { alert('File deleted');}); drEvent.on('dropify.errors', function(event, element) {console.log('Has Errors');}); -
How i can set custome model fields order in django?
I use django and drf. For example i have such model: class Book(models.Model): id = ... name = ... author = ... page_count = ... I use drf and recive such response: { "id": ..., "name": ..., "author": ..., "page_count": ..., } Can i set custome order for fields? Example: { "id": ..., "page_count": ..., "author": ..., "name": ..., } -
Django template replace null entries with zero
I am getting a list of students where their status is active studentdata = Students.objects.filter(status='active').values() This is passed from the view to the template and is printed like so <table> <tr> <th>Student 1 Name</th> <th>Student 2 Name</th> <th>Student 3 Name</th> </tr><tr> <td id="a0">{{studentdata.0.name}}</td> <td id="a1">{{studentdata.1.name}}</td> <td id="a2">{{studentdata.2.name}}</td> </tr> The issue is that not all students have active status. So the view does not return the same number of rows as the table. This means if student.1 does not have 'active' status, the value in studentdata.1.name will be studentdata.2.name instead. How do I fix this so that the data will be replaced by 0 wherever the student is inactive for the particular index? -
prepopulated fields refuse to work in a django-project that is hosted on the server DO
models.py class Product(models.Model): category = TreeManyToManyField(ProductCategory, blank=True, symmetrical=False, related_name='products', verbose_name='Категория') status = models.ForeignKey(ProductStatus, default=None, null=True, blank=True, on_delete=models.CASCADE, verbose_name='Статус') name = models.CharField(max_length=200, db_index=True, verbose_name='Наименование товара') slug = models.SlugField(max_length=200, db_index=True, verbose_name='Уникальная строка') ... code = models.CharField(max_length=6, db_index=True, default=None, blank=True, verbose_name='Код товара', help_text='Код товара должен быть 6-значным') vendor_code = models.CharField(max_length=6, db_index=True, blank=True, default=None, verbose_name='Артикул') ... admin.py @admin.register(Product) class ProductAdmin(admin.ModelAdmin): save_as = True inlines = [ProductDetailInline] fields = ['category', ('name', 'slug'), ('code', 'vendor_code'), 'memory', 'status', ('hot_deal', 'as_new', 'recommended', 'hot_sales'), ('price', 'discount'), 'image', 'description', 'available', 'is_active', ('created', 'updated')] prepopulated_fields = {'slug': ('name',), 'vendor_code': ('code',)} ... Everything works correctly and correctly on a local project, but by placing the project on the server DigitalOcean, the prepopulated_fields does not work. I'm afraid to suggest that this may be due to js files in static_prod. -
Django RadioSelect widget, add additional information
I have this simplified model and form: class Books(models.Model): name = models.CharField(max_length=500) price = models.DecimalField(max_digits=6, decimal_places=2) default = models.BooleanField(default=False) def __str__(self): return self.name class BookForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['Field'] = forms.ModelChoiceField(queryset=None, empty_label=None, widget=forms.RadioSelect) self.fields['Field'].queryset = Books.objects.all() self.fields['Field'].initial = Books.objects.filter(default=True).first() This will result in a RadioSelect-Form, like this: (x) Book1 ( ) Book2 ( ) Book3 My problem is, how can I add the price in the RadioSelect form, that it's just visible. It should appear after the name of the book, ideally even in a different font, which I set over a bootstrap class (e.g "text-primary") (this is not mandatory) (x) Book1 (10 €) ( ) Book2 (20 €) ( ) Book3 (30 €) I know i can return the name and price in the model, like class Books(models.Model): name = models.CharField(max_length=500) price = models.DecimalField(max_digits=6, decimal_places=2) default = models.BooleanField(default=False) def __str__(self): return '%s (%s €)' % (self.value, str(self.price)) But because of other reasons, i can not do this. I just need to return the name. Are there other ways to do this? I even read into django-crispy-forms, but couldnt find a solution. -
How long Redis stores a result
I'm using Django + Celery + Redis and can't find out how long data are stored, i.e. after how much time I'm not able to get result by task_id. Is it possible to configure this timeout? Also, is it possible in Celery to configure queue-timeout, i.e. number of seconds the task will wait in queue for execution before raising some error? -
Dynamic Display in Base HTML using DJango
I am new to DJango and i am creating a Website. I have created a base HTML page with a NAV bar which will be used across all pages. I want to display the message "Welcome 'username'" as the first line across all pages. I had written the following code in views.py def getusername(request): uname=request.getusername return (request,'main.html',{'uname':uname}) in the main.html after defining the title and nave bar, i have the following html code <span class="label label-default">Welcome{{uname}}</span> When i run this code, I am able to view the NavBar in all pages tat extends the base page(main.html) but the welcome message does not fetch the username. I have configured the following in urls.py path("", views.getusername,name='getusername') Note: Even when i hardcode a string to be returned from views.py, the string is not displayed as part of the welcome message -
Django TypeError - 'ModelBase' object is not iterable
I have searched all the other threads with similar Questions on this topic but nothing is working. Hoping someone here can help. It only fails when trying to access 'api/orders'. I am having the following errors Traceback (most recent call last): File "C:\Users\thard\projects\foreside\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\mixins.py", line 46, in list return Response(serializer.data) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\serializers.py", line 760, in data ret = super().data File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\serializers.py", line 260, in data self._data = self.to_representation(self.instance) File "C:\Users\thard\projects\foreside\venv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation return [ Exception Type: TypeError at /api/orders/ Exception Value: 'ModelBase' object is not iterable Here are the pertinent files users.models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): ADMIN = 1 APPROVER = 2 TRADER = 3 USER_ROLE_CHOICES = ( (ADMIN, 'admin'), (APPROVER, 'approver'), (TRADER, 'trader'), ) role = models.PositiveSmallIntegerField(choices=USER_ROLE_CHOICES) REQUIRED_FIELDS … -
non-ORM method in django rest api
views.py def get_content_view(request): if request.method == 'POST': if request.method == 'POST': save_editor = request.post["editor"] r = requests.post('http://127.0.0.1:8000/api_uidatas/', data=request.POST.save_editor) else: r = requests.post('http://127.0.0.1:8000/api_uidatas/', data=request.POST.save_editor) responses = r.content.decode("utf-8") return HttpResponse (responses) how to save the data for forms to db without non-orm method(without using serializers) -
Not able to build python code into binary using pyinstaller --onefile in ubuntu 19.04
We trying to convert python code into binary using pyinstaller --onefile. Following are the packages we are using Python3.7.5 pip3 install django==3.0.5 python-dateutil==2.8.1 nltk==3.5 spacy==2.2.4 gensim==3.8.2 pandas==1.0.3 clickhouse_driver==0.1.3 numpy==1.18.1 sklearn==0.0 statistics scipy==1.4.1 statsmodels==0.11.0 seaborn==0.10.0 matplotlib==3.1.3 word2number==1.1 n2w==0.1.3 pyLDAvis==2.1.2 textblob==0.15.3 xgboost plot_metric==0.0.6 pmdarima==1.5.3 vaderSentiment==3.3.1 imblearn==0.0 gunicorn==20.0.4 h2o==3.30.0.1 python -m spacy download en_core_web_sm we are getting error: AttributeError: type object 'statsmodels.tsa.statespace._kalman_filter.array' has no attribute 'reduce_cython' Following are the steps where we are running step 1: pyinstaller --onefile manage.py Step 2: pyinstaller manage.spec