Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two formsets, ManagementForm data is missing or has been tampered with
i need two formsets in my form on django. i started with creating the first one and it works well, but when i created the second i had an error that says Management data is missing or has been tampred with. i tried to discover where i have the problem by doing "print" in many lines of my views file and i detected that the problem is in my formset2 = MaintenancesFormset(request.POST or None, queryset= Maintenances.objects.none(),prefix='Maintenances')(because when i print the first formsset it workes but when i put print(formset2) i have error in this line. could someone help me please? views.py def home(request): context = {} Initialisation_laveries_pipelinesFormset = modelformset_factory(Initialisation_laveries_pipelines, form=Initialisation_laveries_pipelinesForm) MaintenancesFormset = modelformset_factory(Maintenances, form=MaintenancesForm) form = EntréeForm(request.POST or None) formset = Initialisation_laveries_pipelinesFormset(request.POST or None, queryset= Initialisation_laveries_pipelines.objects.none(), prefix='Initialisation_laveries_pipelines') formset2 = MaintenancesFormset(request.POST or None, queryset= Maintenances.objects.none(),prefix='Maintenances') if request.method == "POST": print(formset2) if form.is_valid() and formset.is_valid() and formset2.is_valid(): try: with transaction.atomic(): entrée = form.save(commit=False) entrée.save() for initialisation in formset: data = initialisation.save(commit=False) data.entrée = entrée data.save() for maintenance in formset2: data2 = maintenance.save(commit=False) data2.data = data data2.save() except IntegrityError: print("Error Encountered") context['formset2'] = formset2 context['formset'] = formset context['form'] = form return render(request, 'entrée/index.html', context) class Initialisation_laveries_pipelines(models.Model): entrée = models.ForeignKey(Entrée, related_name = "Entrée", on_delete=models.CASCADE) … -
calling ajax function in views.py to get the data from database
I want to fetch data from the database. I am using ajax function to get it in the index.html. How should I call this ajax function to the views.py so i can display it in view. How should I attain it? My codes: index.html <script type="text/javascript"> function submitData(){ // Get answer from the input element var dt = document.getElementById("major1").value; var dtt = document.getElementById("major2").value; var dttt = document.getElementById("major3").value; var dtttt = document.getElementById("major4").value; var dttttt = document.getElementById("major5").value; // add the url over here where you want to submit form . var url = "{% url 'home' %}"; $.ajax({ url: url, data: { 'major1': dt, 'major2': dtt, 'major3': dttt, 'major4': dtttt, 'major5': dttttt, }, dataType: 'JSON', success: function(data){ // show an alert message when form is submitted and it gets a response from the view where result is provided and if url is provided then redirect the user to that url. alert(data.result); if (data.url){ window.open(data.url, '_self'); } } }); } </script> views.py: def home(request): majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk") if request.method == 'POST': form = request.POST.get('be_nextyr_total') line_chart = pygal.Line(width=1500) line_chart.title = 'Budget Estimation' context = { "chart": line_chart.render_data_uri(), 'majors': majors } return render(request, "website/index.html" , context ) -
I am trying to deploy Deploy a Django with Celery, Celery-beat, Redis, Postgresql, Nginx, Gunicorn with Docker to Heroku
I am trying to deploy Django with Celery, Celery-beat, Redis, Postgresql, Nginx, Gunicorn Dockerized on Heroku using container registry. After building the image, pushing, and release to Heroku, the static files are not being served by Nginx, and the Redis isn't communicating with celery, I don't know if the celery is working either. This is my Dockerfile # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add zlib libjpeg-turbo-dev libpng-dev \ freetype-dev lcms2-dev libwebp-dev \ harfbuzz-dev fribidi-dev tcl-dev tk-dev # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt # pull official base image FROM python:3.8.3-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/media WORKDIR $APP_HOME # install dependencies RUN apk update … -
Reverse for 'chained_filter' not found. 'chained_filter' is not a valid view function or pattern name Django admin
I working on a project where I need to add two dependant dropdowns for that I tried to use Django-smart-selects but I having an issue. Here's what I did Here is my models class District(models.Model): name = models.CharField(max_length=100, default=None) created_at = models.DateField(default=django.utils.timezone.now) class Meta: managed = True db_table = 'District' def __str__(self): return self.name class PoliceStation(models.Model): name = models.CharField(max_length=100, default=None) district = models.ForeignKey( District, on_delete=models.CASCADE, max_length=100) created_at = models.DateField(default=django.utils.timezone.now) class Meta: managed = True db_table = 'PoliceStation' def __str__(self): return self.name class NewsAndUpdates(models.Model): title = models.CharField(max_length=250) description = HTMLField() category = models.ForeignKey( Category, on_delete=models.CASCADE, max_length=100) district = models.ForeignKey( District, on_delete=models.CASCADE) policeStation = ChainedForeignKey( PoliceStation, chained_field="district", chained_model_field="district", show_all=False, auto_choose=True, on_delete=models.CASCADE) class Meta: managed = True db_table = 'NewsAndUpdates' This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('chaining/', include('smart_selects.urls')), ] Here is my installed apps INSTALLED_APPS = [ .... 'smart_selects', ] In setting.py I used this as it was suggested when I was searching about the issue USE_DJANGO_JQUERY = True This is my admin.py class NewsAndUpdatesAdmin(admin.ModelAdmin): list_display = ('title', 'category', 'created_at', 'is_published', 'is_draft') admin.site.register(NewsAndUpdates, NewsAndUpdatesAdmin) But I am getting issue which is Reverse for 'chained_filter' not found. 'chained_filter' is not a valid view function or pattern name Using Django version 3.1 -
Getting error message even after setting safe=False
I am working in Django. I have following list of dictionaries - userList = [{'value': '1', 'time': '2020-11-30T04:48:57.642Z'}] I want to use it in Json Response as follows - data = { 'status': 'success', 'message': userList } For that I did the following - return JsonResponse(data, safe=False) Still I am getting error as - In order to allow non-dict objects to be serialized set the safe parameter to False. Can anyone please tell me where I am going wrong or what should I do to achieve the aim? Thanks in advance -
Django-import-export, Export to xlsx only one model object. Django
I am completely new Django and I am building an e-commerce website with Django. I want to export the model's object to xlsx format. I am using django-import-export library to do that but the problem is this library exports model's all objects. I just want to export only one object. For example, if someone orders a product I want that order object export to xlsx format. I can write that in python shell but I want it to be done in the admin panel. In the picture below you can see my Order model and OrderItem model. How can I export exactly like in the picture to xlsx. Order model in admin panel Models.py class Order(models.Model): STATUS = (("NEW", "NEW"), ("ACCEPTED", "ACCEPTED"), ("COMPLETED", "COMPLETED")) customer = models.ForeignKey(Customer,on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=50) surname = models.CharField(max_length=50) phone = models.CharField(max_length=50) email = models.EmailField(max_length=50, blank=True) address = models.CharField(max_length=100) status=models.CharField(max_length=10, choices=STATUS,default='NEW') total = models.FloatField() adminnote = models.CharField(max_length=100, blank=True) updated_at=models.DateTimeField(auto_now=True) ordered_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + self.surname class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=8, decimal_places=2) total_price = models.DecimalField(max_digits=8, decimal_places=2) date_added = models.DateTimeField(auto_now_add=True) admin.py class OrderProductline(admin.TabularInline): model = OrderItem readonly_fields = ('order', 'product', 'price', 'quantity', … -
How do I send file upload progress % in Django?
I have a iOS app which can upload files to my Django API. Heres the front-end code: AF.upload(multipartFormData: { multipartFormData in multipartFormData.append( data1!, withName: "one", fileName: "one") }, to: "https://httpbin.org/post") .response { response in print(response) } .uploadProgress { prog in print(prog.fractionCompleted) } This works perfectly on https://httpbin.org/post , It keeps printing the progress % until its 100%. However, When I post the same file my own API It will only print the progress once at 100%. So, I assume it's because I have to set up my http response so it also sends the progress %? How can i mimic the http response of httpbin.org/post ? Heres what I have currently. @csrf_exempt def test (request): f = request.FILES["1"] default_storage.save(f.name, f) return HttpResponse("file saved") -
How do I establish a connection between public frontend and private backend both hosted on IIS server
I am new to this sorry but when hosting public frontend and private backend there is not a connection, no request headers are being sent. Please help how can I configure the iis server to make private backend accessible. Frontend: Reactjs Backend: django, django rest framework -
Where to download eav-django v0.9.2?
I'm working on a legacy project, and it's a customization based on eav-django version 0.9.2. My plan is to re-base the same customization to django-eav2. The original software developer didn't keep any history of change, and the only thing I have now is a lump sum commit of the final version. So I need to find the original source code and compare to find out the changes. pip install eav-django==0.9.2 now gets the below error. Could anyone give me some pointers about where to download the exact version of v0.9.2? (venv.2.7) -bash-4.2$ pip install eav-django==0.9.2 DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. ERROR: Could not find a version that satisfies the requirement eav-django==0.9.2 (from versions: 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7) ERROR: No matching distribution found for eav-django==0.9.2 WARNING: You are using pip version 20.2.3; … -
How does Django find out which modules, functions to load in?
Django has been amazing at making things easy, to the point that I am convinced this is black magic. As with most Django projects, I have some custom models in models.py. How do Django knows that this is where I keep my modules? Is it just assume that anything in a particular modules (for example, models.py) will be important to the app? That my only explanation because not only my custom models but also my callback functions is also automatically called somehow... @receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!") Can someone give me an explanation? -
Django Download/Upload Files In Production
I have a Django project that is currently hosted. I am serving static files but do not know how to handle user file uploads / downloads in the MEDIA folder. I've read a lot about Docker, Nginx, and Gunicorn but have no idea which I need nor how to set them up. I've followed no less than 20 tutorials and watched no less than 15 YouTube videos but am still confused (I've visited every link for the first 2 pages of all my Google searches). My question is, which of these do I need to allow users to upload/download files from a site? On top of that, I have tried getting all three working but can't figure them out, surely I'm not the only one that has so much difficulty with this, is there a good resource/tutorial which would guide me through the process (I've spent well over 40 hours reading about this stuff and trying to get it to work, I've gotten to the point where so long as it works, I don't care for understanding how it all fits together)? Thank you. -
Does pytest-django allow modification of the database during the test?
Let's say in my conftest.py, I have the following: import pytest from django.core.management import call_command @pytest.fixture(scope='session') def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command('loaddata', 'my_fixture.json') And then in my test_script.py: @pytest.mark.django_db def test_delete_some_data(django_db_setup): # Do some deleting... Will this change the database that is used by other test function? -
I want to fetch data from database using ajax and then define it in views.py to display in bar-chart
I want to fetch the data from database. I am using Ajax and then I want to define it in views.py to extract the data and display it in view(webpage) using Django. How may I approach in order to bring "be_total" the data from the database and then display the values of "be_total" in the form of bar chart on my webpage? Can anyone please help me ? My codes are: index.html: <form class="form-row" method="post" > {% csrf_token %} <div class="form-group col-md-2" > <select class="form-control select2" > <option>Select M Head</option> {% for major in majors %} <option value="{{ major.pk }}" id="m1">{{ major.pk }}: {{ major.description }}</option> {% endfor %} </select> </div> <div class="form-group col-md-2"> <select class="form-control select2" > <option>Select M Head</option> {% for major in majors %} <option value="{{ major.pk }}" id="m2">{{ major.pk }}: {{ major.description }}</option> {% endfor %} </select> </div> <div class="form-group col-md-2"> <select class="form-control select2" > <option>Select M Head</option> {% for major in majors %} <option value="{{ major.pk }}" id="m3">{{ major.pk }}: {{ major.description }}</option> {% endfor %} </select> </div> <div class="form-group col-md-2"> <select class="form-control select2" > <option>Select M Head</option> {% for major in majors %} <option value="{{ major.pk }}" id="m4">{{ major.pk }}: {{ major.description }}</option> {% … -
Django allauth SocialAccount model's "extra_data" field
SocialAccount model has the extra_data field in the table. And this model has a relation with the User table. when I am retrieving the User table, trying to add the SocialAccount into the User but having an error. serializers.py from rest_framework import serializers from django.contrib.auth.models import User from allauth.socialaccount.models import SocialAccount class SocialAccountExtraDataSerializer(serializers.ModelSerializer): class Meta: model = SocialAccount fields = ["extra_data"] depth = 1 class UserDisplaySerializer(serializers.ModelSerializer): extra_data = SocialAccountExtraDataSerializer() class Meta: model = User fields = ["username", "extra_data"] depth = 1 the error message says: Got AttributeError when attempting to get a value for field extra_data on serializer UserDisplaySerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'extra_data'. How should I insert the SocialAccount's extra_data into User serializer as field. incase if you need to see views.py from rest_framework.response import Response from rest_framework.views import APIView from users.routes.serializers import UserDisplaySerializer class UserDisplayApiView(APIView): def get(self, request): serializer = UserDisplaySerializer(request.user) return Response(serializer.data) -
MultiValueDictKeyError at /register 'email'
class User(AbstractUser): is_reader = models.BooleanField(default=False) is_writer= models.BooleanField(default=False) -
Multiple root pages in Wagtail
I currently use wagtail as a blog which is accessible via example.com/blog and the admin via example.com/blog/admin. I would like to also use wagtail to create a support (knowledge base) section. This would then be accessible via example.com/support. The pages and models for the blog vs support section would be different since they're catering to different use cases. Would something like the following be possible? example.com/wagtail - wagtail admin (for both the blog and knowledge base) example.com/blog - blog section of the site example.com/support - knowledge base / support section of the site If the above is not possible I would also be open to having two completely separate wagtail apps in my django project, eg: example.com/blog - this is a blog wagtail section with its own admin example.com/blog/admin example.com/support - this is a separate support wagtail section with its own admin example.com/support/admin I'm not entirely sure which option is possible or how to go about getting either one to work. -
Integrate Dataframe from a Python File to Django
I've developed a complex data analysis model using Python (for the sake of simplicity, let's call it analysis.py) which contains multiple long algorithms to transform a set of raw data and spits out output in the form of dataframe as well. I've been looking into some tutorials recently on Django framework and have tried building a simple web app that resembles a forum/blog post web app. With the dataframe output from the analysis.py, I would like to display the data in the form of multiple charts on the web app. Can anyone point me to a direction to move from here? I've looked for multiple resources online but I think I am unable to find the correct keywords that match with what I actually want to build. I just want a shell code kind of a thing to integrate into my current django backend in order to be able to call the dataframe from the analysis.py Thank you very much in advance. -
Django static files for dashboard not loading
Hi I am fairly new to django and I am trying to learn adding dashboard to django using this tutorial - Django Plotly Dash Tutorial on Youtube. I was able to load all the html files, unfortunately I am unsuccessful with the static files. This is my project file directories My Project Settings.py STATICFILES_LOCATION = 'static' STATIC_URL = '/static/' STATIC_ROOT = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'sample2/static') ] Some base.html code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="../images/favicon.ico" type="image/ico" /> <title>This </title> <!-- Bootstrap --> <link href="{% static '../vendors/bootstrap/dist/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Font Awesome --> <link href="{% static '../vendors/font-awesome/css/font-awesome.min.css'%}" rel="stylesheet"> <!-- NProgress --> <link href="{% static '../vendors/nprogress/nprogress.css'%}" rel="stylesheet"> <!-- iCheck --> <link href="{% static '../vendors/iCheck/skins/flat/green.css' %}" rel="stylesheet"> MY welcome.html under home app {% extends 'base.html'%} {% load static %} The only things that I didn't follow on the tutorial was not install a database and not declare the {%load staticfiles%} because I have read that Django 3.1.3 has depreciated this command. What am I missing here? Thank you. -
How to intigrate paypal in Django (3.1) [closed]
I'm working on a project in which I'm using Python(3.9) & Django(3.1.2) and I need to implement the Paypal payment method in this project. -
UnboundLocalError at / local variable 'context' referenced before assignment
Getting this error with views.py in my Django app - UnboundLocalError at / local variable 'context' referenced before assignment. Here is a snippet of the code that is not working: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context: {'products':products} return render(request, 'store/store.html', context) -
How to customize the HyperLinkedRelatedField in Django Rest Fraemwork?
Hey I am working with Django Rest Framework. I am using HyperLinkedRelatedField from Rest Framework Serializer. As shown in image, the url is "http://127.0.0.1:8000/api/teams/new/" but I want it like "http://127.0.0.1:8000/api/teams/new/join/" Here is the Serializer code class TeamListSerializer(serializers.ModelSerializer): privacy = serializers.ChoiceField(choices=options) avatar = serializers.ImageField(default='users/avatar/default/user.png') url = serializers.HyperlinkedIdentityField(read_only=True, view_name='team-detail', lookup_field='slug') class Meta: model = Team fields = ( 'url', 'slug', 'name', 'description', 'avatar', 'privacy', 'pinned', ) read_only_fields = ('slug',) -
Label after forms.Select does not move to a new line
So I have a Category model that is a part of my Post model. I would like to choose from available categories when creating a post by having the forms.Select widget. The problem is that the select widget does not make the next label shift to a new line. How can I make "Content" appear on the next line and not next to "General?" Please see the screenshot. . My models look like this: class Post(models.Model): title = models.CharField(max_length=100, unique=True) header_image = models.ImageField(null=True, blank=True, upload_to='post_photos') thumbnail_image = models.ImageField(null = True, blank=True, upload_to='post_thumbnails') slug = models.SlugField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = RichTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=255, default='Coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name='blog_likes') class Category(models.Model): name = models.CharField(max_length=255) My form is: categories = Category.objects.all().values_list('name', 'name') choices = [x for x in categories] class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'header_image', 'slug', 'snippet', 'author', 'category', 'content', 'status',) widgets = { 'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'views.author', 'type': 'hidden'}), 'category': forms.Select(choices=choices, attrs={'class': 'form-control'}), } Html is simply: {% csrf_token %} {{ form|crispy }} {{ form.media }} -
How to put checkboxes side by side Django Form
I'm using Django and I need to present a ModelForm with some checkboxes in my template. The problem is that the checkboxes are in a vertical line, one after another. I need them to be evenly distributed in my page, for example 3 columns containing 4 checkboxes each. At the moment I only have 1 column with all my checkboxes inside it. This creates a scroll and the page looks awful. I've tried adding CSS classes and IDs as widgets in my "forms.py" file, I can change some styles, but I can't "play" with columns and lines. Is it possible to do this using Model Forms? -
Change to Django code gives NameError name (function) is not defined
I have a Django project where the model has two classes - Equity and Article. Within the Equity class I used to have the following code which worked smoothly def fundamental_list_actual(self): l_fund = [] filtered_articles = Article.objects.filter(equity__industry = self.industry) for filtered_article in filtered_articles: if(filtered_article.equity.equity_name == self.equity_name): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) else: if (filtered_article.read_through == -1): l_fund.append([float(-1)*filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) if (filtered_article.read_through == 1): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) return l_fund However, I recently updated my code to include the following in the model code but outside any class: filename = 'fake_nums_trial_covar' #infile = open(filename, 'rb') infile = open('PATH_HIDDEN_FOR_PRIVACY/fake_nums_trial_covar', 'rb') covar_trial_nums = pickle.load(infile) infile.close() And within the Equity class, the following: def covars_abs_above_mean(row_index): covars = covar_trial_nums #cov_to_dataframe('Russel_1000_tickers_3.xlsx') stocks = covars.index pos_relation_list = [] neg_relation_list = [] pos, neg = avg_pos_and_neg(row_index) for stock in stocks: if (covars.loc[row_index, stock] > pos): pos_relation_list.append(stock) if (covars.loc[row_index, stock] < neg): neg_relation_list.append(stock) return pos_relation_list, neg_relation_list def fundamental_list(self): name = self.equity_name pos_related_cos, neg_related_cos = covars_abs_above_mean(name) #now we want to get a list of articles whose equity__equity_name matches that of ANY #of the equities in our pos / neg lists (though we'd like 2 separate filters for this) #try: pos_filtered = Article.objects.filter(equity__equity_name__in = pos_related_cos) neg_filtered = Article.objects.filter(equity__equity_name__in … -
select branch_id from report group by branch_id order by max(date) desc to Django Query
I have a model with the following fields id -> int vivitor_id -> int branch_id -> int date -> datetime I need to perform the following query in Django. How to do this using Django ORM. select branch_id from report group by branch_id order by max(date) desc ;