Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I always get this error:The site can't be reached
python app.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 312-522-468 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) This error is displayed when I deploy the server either in Django or flask. How to resolve it? -
How to allow load iframe at django page?
I have a page at django project, who contains an iframe object. But this object dont showing. what should I do to make the element work? Here is the code of page: <div class="container"> <iframe height="640" width="480" src="https://sslcharts.forexprostools.com/index.php?force_lang=7&pair_ID=962711&timescale=300&candles=50&style=line"></iframe> </div> view.py def view_rouble(request): return render(request, template_name='rouble/rouble.html') -
Django 3 invalid syntax in models.py on FileField Model
I am getting invalid syntax (, line 15) pylint(syntax-error) [15,6] which is preventing me from making migrations. Was working before I added a few fields that one was working before. It had previously worked. I added the model class choices using named groups to group the meteorites instead of inherited classes which people say causes issues from what I read. Could find anything in it that could cause it but still a possibility. I have tried deleting and reformatting it to see if the indentation was off nothing working. This usually fixes issues for me. i also tried this stackoverflow result Adding ImageField to model causes exception in django But I had pillow already installed and the unicode part did not make a difference. I also checked to see if [my parenthesis are balanced][1] which I believe they are but was a stackoverflow result. . I added the default to everything so i can makemigrations last time this worked and i made migrations and added a example. default='') it saying its this line below main_image=models.FileField(upload_to='media/', default='') blog/models.py from django.db import models from django.utils import timezone class Post(models.Model): CATEGORY_CHOICES = ( ('iron meteorites', 'iron meteorites'), ('stony meteorites', 'stony meteorites'), ('stony-iron meteorites', … -
How can I display certain fields of a django model in a template?
I would like to display certain fields for all objects of a model in a table. And I also want to render the url property of some FileFields, which are part of that model. So, I got models with obj_data = ThatObject.objects.only('field1', 'field2', 'field3') But I do not know how to access everything in the template. I could say {% for single_object in obj_data %}, but I cannot iterate over the fields of single_object. How can I do that? -
Django redirect does not change page
I am on Django 3.0.5 and in my views.py I have class SDNAList(LoginRequiredMixin, ListView): model = Protocols template_name = 'pages/protocols.html' queryset = Protocols.objects.filter(device='sDNA') login_url = '/login/' def post(self, request, *args, **kwargs): data = request.POST f = ProtocolModelForm(data) if f.is_valid(): form = f.save() # Redirect to correct page # TODO!~ print("/sdna/%i" % form.id) # return redirect("/sdna/%i" % form.id) return redirect("protocols:sdna") And in my urls.py app_name = 'protocols' urlpatterns = [ path('sdna/', views.SDNAList.as_view(), name='sdna'), In the terminal I see the GET taking place but the page does not redirect [08/May/2020 21:32:17] "POST /sdna/ HTTP/1.1" 302 0 [08/May/2020 21:32:17] "GET /sdna/ HTTP/1.1" 200 45350 -
Django allauth and Angular, how to check in Angular user is authenticated?
I'm using on the BE Django + allauth for authentication (Google) and for the front-end Angular. I have a view and a template in Django that holds the dist files from Angular. So when you get to the base URL the Angular app is bootstrapped right away. Inside Angular, I want to have a route that is accessible only for authenticated users. What would be a secure and a good way to achieve this? How can I tell in Angular that a user is authenticated or not? -
Why are my images not in one column? What am I doing wrong here?
I'm new to the front end world, and I'm wondering what I'm doing wrong here. I'm trying to get my images all in one row, but they are all over the place and my text isn't showing up correctly either. matches.html <div class="container "> <h2>It's a match!</h2> <div class = "row"> <div class="col-4"> <img src="{{ user.photo.url }}" width= "300" height= "300" object-fit = "cover" > </div> <div class="col-8"> <img src="{% static 'images/matching_cupid.png' %}" width= "300" height= "300" object-fit = "cover" > <div class="col-12"> <img src="{{ match.photo.url }}" width= "300" height= "300" object-fit = "cover" > </div> </div> <p>You and {{ match.username }} like each other!</p> <p><a href="{% url 'dating_app:messages' user.id %}">Start messaging </a></p> <br> <p><a href="{% url 'dating_app:mingle' %}">Keep mingling!</a></p> {% endblock %} -
Django display related objects inside related objects in the admin
According to my assignment admin must be able to create Polls with Questions (create, delete, update) and Choices related to this questions. All of this should be displayed and changable on the same admin page. Poll | |_question_1 | | | |_choice_1(text) | | | |_choice_2 | | | |_choice_3 | |_question_2 | | | |_choice_1 | | | |_choice_2 | | | |_choice_3 | |_question_3 | |_choice_1 | |_choice_2 | |_choice_3 Ok, it's not a problem to display one level of nesting like so on class QuestionInline(admin.StackedInline): model = Question class PollAdmin(ModelAdmin): inlines = [ QuestionInline, ] But how to do to get the required poll design structure? -
Dynamic fields in django forms
I am trying to have a custom form on django admin for my ModelB, with fields taken from other ModelA. models.py class ModelA(models.Model): source = models.CharField(max_length=80) keys = ArrayField( models.CharField(max_length=50) ) class ModelB(models.Model): characteristic_keys = JSONField() forms.py class ModelBForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) queryset = ModelA.objects.all() dynamic_fields = [(x.source, x.keys) for x in queryset] # New fields to be shown on admin => # Field name => "source" from modelA # Field type => multiple choice with options => "keys" from modelA for field in dynamic_fields: self.fields[field[0]] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=field[1]) def save(self, commit=True): # ...do something with extra_field here... return super().save(commit=commit) class Meta: model = Workflow fields = "__all__" admin.py class ModelBAdmin(admin.ModelAdmin): form = ModelBForm admin.site.register(ModelB, ModelBAdmin) I want a single form for ModelB on django admin, with dynamic "source" fields takes from ModelA, with multiple choice options from their corresponding "key" values in modelB. I have tried to keep information clear and understandable, please let me know if I have missed any information that might be needed to understand the problem. Any ideas to deal this problem would be a great help! -
NoReverseMatch at / Reverse for 'product' with no arguments not found
I have this error NoReverseMatch at / Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<slug>[^/]+)$'] when using Django urls patterns This is my URL patterns urlpatterns = [ path('',HomeView.as_view(),name='home'), path('checkout/',checkout,name='checkout'), path('product/<str:slug>',ItemDetailView.as_view(),name='product'), ] This is my views.py class ItemDetailView(DetailView): model = Item template_name = 'product.html' This is my models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES,max_length=2) label = models.CharField(choices=LABEL_CHOICES,max_length=1) slug = models.SlugField() def __str__(self): return self.title def get_absolute_url(self): return reverse('core:product',kwargs={'slug':self.slug}) This is my base.html <li class="nav-item"> <a class="nav-link waves-effect" href="{% url 'core:checkout' %}" target="_blank">Checkout</a> </li> <li class="nav-item"> <a class="nav-link waves-effect" href="{% url 'core:product' %}" target="_blank">Product</a> </li> -
Business Logic Between 2+ Models in Django rest Framework
i've read a lot about this but i still can't get to the bottom of how to implement it. I'm new into Python/Django programming and i'm making an application with DRF+PostgreSQL. All good, i'm making basic post/get operations wich basically return the models as they are, no business logic or data treatments between. My complication now is that i need to build a "custom response" with business logic and i don't know how to do it or where to implement it, for example, i have these models: class Parking(models.Model): adress = models.ForeignKey(Adress, on_delete=models.CASCADE, null=False, related_name='adress') price = models.DecimalField(max_digits=4, decimal_places=2, null=True, blank=True) class ParkingLot(models.Model): parking = models.ForeignKey(Parking, on_delete=models.CASCADE, null=False, related_name='parkinglots') floor = models.IntegerField(null=False) class ParkingAvailability(models.Model): parkinglot = models.ForeignKey(ParkingLot, on_delete=models.CASCADE, null=False, related_name='availability') available = models.BooleanField(null=False, blank=False) if i return a Parking, i get all the other models in the response(parkinglot and availability), wich is fine. Now, i want to return the adress of the parking, but just the total of the ParkingLots that meet x conditions, for example: number of parkinglots that the floor is 4 and that are available. Where should i implement this? I've read about a service or manager file that implement these types of business conditions but some … -
Python, how to perform an iterate formula?
I'm trying to export from excel a formula that (as usual) iterate two other value. I'm trying to explain me better. I have the following three variables: iva_versamenti_totale, utilizzato, riporto iva_versamenti_totalehave a len equal to 13 and it is given by the following formula iva_versamenti_totale={'Saldo IVA': [sum(t) for t in zip(*iva_versamenti.values())],} Utilizzato and riporto are simultaneously obtained in an iterate manner. I have tried to get the following code but does not work: utilizzato=dict() riporto=dict() for index, xi in enumerate(iva_versamenti_totale['Saldo IVA']): if xi > 0 : riporto[index] = riporto[index] + xi else: riporto[index] = riporto[index-1]-utilizzato[index] for index, xi in enumerate(iva_versamenti_totale['Saldo IVA']): if xi > 0 : utilizzato[index] == 0 elif riporto[index-1] >= xi: utilizzato[index] = -xi else: utilizzato[index]=riporto[index-1] Python give me KeyError:0. EDIT Here my excel file: https://drive.google.com/open?id=1SRp9uscUgYsV88991yTnZ8X4c8NElhuD In grey input and in yellow the variables -
How else can I write a timestamp with timezone in postgresql/django python shell?
I am working on a django API project with a postgres db. I have also added a serializers.py file. I am trying to test what I've done by adding a row to the db via python shell but I keep getting this error: django.db.utils.ProgrammingError: column "date_created" is of type timestamp with time zone but expression is of type time without time zone LINE 1: ...bility" = NULL, "rating" = NULL, "date_created" = '00:00:00'... ^ HINT: You will need to rewrite or cast the expression. This is the code: from vendor.models import Vendors from vendor.serializers import VendorsRegisterSerializer p = Vendors(id=1, first_name='Flavio', last_name='Akin', email='sheeku@gmail.com', profession='plumber', username='Flanne', pin='1234', phone_number='12345678901', number_of_jobs=300, number_of_patrons=788, date_created='21:00:00 +05:00') I have tried replacing date_created value '21:00:00 +05:00' with '21:00:00 EST', '21:00+05' and '21:00:00+05' but I keep getting the same error. Any help will be appreciated. Thanks in advance. -
OperationalError in Django Migrations
First I created a Model named 'userorders' having fields : id(by default), user_id, and order_id. Then after realizing I don't need order_id, I deleted it from MySQL DB first (using Workbench), then I made changes in the model in Django, but it keeps showing errors now. 0013_orderdetails_userorders.py migrations.CreateModel( name='userorders', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.IntegerField()), ('order_id', models.IntegerField()), ], ), 0014_remove_userorders_order_id.py dependencies = [ ('shoppingCart', '0013_orderdetails_userorders'), ] operations = [ migrations.RemoveField( model_name='userorders', name='order_id', ), ] 0015_userorders_order_id.py dependencies = [ ('shoppingCart', '0014_remove_userorders_order_id'), ] operations = [ migrations.AddField( model_name='userorders', name='order_id', field=models.IntegerField(default=None), preserve_default=False, ), 0016_remove_userorders_order_id.py dependencies = [ ('shoppingCart', '0015_userorders_order_id'), ] operations = [ migrations.RemoveField( model_name='userorders', name='order_id', ), ] 0017_auto_20200508_1639.py dependencies = [ ('shoppingCart', '0016_remove_userorders_order_id'), ] operations = [ migrations.RenameField( model_name='orderdetails', old_name='user_id', new_name='order_id', ), ] ERRORS - when I try to make migrations for any changes I do (Changes are not reflected in DB) MySQLdb._exceptions.OperationalError: (1091, "Can't DROP 'order_id'; check that column/key exists") The above exception was the direct cause of the following exception: django.db.utils.OperationalError: (1091, "Can't DROP 'order_id'; check that column/key exists") Currently, userorders contains 2 fields- id and user_id How can I fix this? -
static files in the media folder not showing when i upload on live server
Hey guys sorry to bother you, I'm new to django and I made a personal portfolio and locally everything is perfect but the deployed one is not loading the images that I upload on the live app. I tried to see youtube videos a lot of topics over here and I cant find a solution...:( Heres my code: settings.py import os import django_heroku from decouple import config import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['***********'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portfolio', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'my_portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'my_portfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS … -
Can i embed interactive matplotlib plots in a webpage?
I have numerous scripts that prompt for user input, pull relevant data from the web, manipulate it in pandas and visualize it in matplotlib. The matplotlib plots have a cursor feature that updates as the mouse is moved and displays the x and y points in a text box, which I'd like to keep. I want to move these scripts to a webpage so I can access them quickly from anywhere. Maybe instead of prompting the user for input it would make more sense to use input fields, drop down menus or radio buttons. Either say, can this be done via Django or some other way in python? -
How do I show loading animation on Django while rendering PDF?
What do i need to show a progress bar or a loading animation while I am generating PDF on Django? Currently I am using Weasyprint to generate PDF from HTML and it takes about 8-15 seconds to load one. And I am wondering if it is possible to show a loading or progress bar while it is being loaded so people will not mistake the link as broken or bug or anything. -
Django Sending Modelform as an email
I created a site where my techs submit their inventory using model forms. Everything is working as intended but I would like to add the function of sending the whole form as an email when they submit their inventory. This would allow for my inventory team to verify counts without having to log in and check the website. Here is my view.py I know it works if I remove the email bits and saves to my models. Currently returns an error: 'dict' object has no attribute 'splitlines' form = Inventory_Form() if request.method == 'POST': form = Inventory_Form(request.POST) tech_field = form.save(commit=False) tech_field.technician = request.user tech_field.save() if form.is_valid(): form.save() name = form.cleaned_data['initials_date'] from_email = 'operations@imbadatthis.com' subject = 'Weekly Inventory', form.cleaned_data['initials_date'] message = form.cleaned_data try: send_mail(subject, message, from_email, ['myemail@n00b.com'], name) except BadHeaderError: return HttpResponse('Invalid header found.') return response, redirect('inventory_submitted') return render(request, 'inventory.html', {'form': form}) Would it be better to save the form to a csv then attach it as an email? I looked at this and also had issues with that part. -
One of the pages of my application is displayed by a code
Help me by advice, please. When I go to one of the pages, its code is displayed, in inspector I see, that all the code is taken in the <pre> tag, although the code does not have this tag. How can this be overcome? Thanks in advance! navbar: python <li {% if 'about' in request.path %} class="active" {% else %} {% endif %}><a href="{% url 'about' %}" class="nav-link">About</a></li> Main url: urlpatterns = [ path('', include("pages.urls")), ... Url of app pages: urlpatterns = [ path('', views.index, name="index"), path('about', views.about, name = "about"), ... I'm at first here, don't know, maybe page with code shold be placed separately About page: {% extends 'base.html' %} {% block title %} About {% endblock %} {% load static %} {% block content %} {% include "partials/_header_internal.html" %} <div class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-6 mb-5 mb-lg-0 order-lg-2"> <img src="{% static 'images/hero_2.jpg' %}" alt="Image" class="img-fluid"> </div> <div class="col-lg-4 mr-auto"> <h2>Car Company</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit suscipit, repudiandae similique accusantium eius nulla quam laudantium sequi.</p> <p>Debitis voluptates corporis saepe molestias tenetur ab quae, quo earum commodi, laborum dolore, fuga aliquid delectus cum ipsa?</p> </div> </div> </div> </div> <div class="site-section bg-light"> <div … -
DJANGO - Order table by a column
I have two models: Worktime : month = charfield time = timefield Sales: month = charfield sales = decimalfied my view is : times = Worktime.objects.values('Month__Month').annotate(total_hour=Sum('time')) sales = Sales.objects.values('Month__Month').annotate(total_sales=Sum('sales')) my template is : {% for time in times %} <tr> <td>{{time.Month__Month}}</td> <td>{{time.total_hour }}</td> {% for sale in sales %} {% if time.Month__Month== sale.Month__Month%} <td>{{sale.total_sales }}</td> {% endif %} {% endfor %} </tr> {% endfor %} Question : How can I order my table by the last column ? (total sales) I tried to do sales= sales.order_by('-total_sales') but I do nothing, only the order_by on time works FYI : there can be worktime but no sales dependings on month, i don't know if it's can cause an issue -
Cpanel SQLite 3.8.3 or later is required (found 3.7.17)
so i want to create a simple web page with django on Cpanel. I followed the tutorial right here : https://www.jvmhost.com/articles/django3-python3.7-cpanel/ But when i try to run the command : ./manage.py collectstatic it gives me this error : SQLite 3.8.3 or later is required (found 3.7.17). In the tutorial they say you need to modifiy the ~/.bashrc file and add this too lines : export LD_LIBRARY_PATH='/opt/atomicorp/atomic/root/usr/lib64/' export PATH=/opt/atomicorp/atomic/root/bin:$PATH I don't understand what these two lines do, but it don't change the problem and i still get the same error What could i do to upgrade the sqlite in Cpanel ? -
Query to get data in particular format in Django
My Models: class Student(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=25) class Subject(models.Model): name = models.CharField(max_length=100) class Student_subject_mapping(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) I'm trying to get all Student_subject_mapping data in the database in a format given below: { "results": [{ "id": 1, ----------------> student id "email": "student_1@gmail.com",------------> student email "subjects": [ { "id": 1, "name": "subject_1" }, { "id": 2, "name": "subject_2" }, ... ] }, What will be the query to get the data in the following manner? How can I achieve data in the above format? -
how to display forms values before form_name.is_valid () in views.py on django?
I want to make a condition for checking the entered data views.py class ViewName(View): def post(self, request, id): pk = ModelName.objects.get(id=id) another = AnotherModel.objects.get(id=id) form = FormName() if form.is_valid(): model_value = pk.model_field form_value = form.cleaned_data['model_field'] if model_value > form_value: another.title = x_value another.save() form.save() forms.py class FormName(forms.ModelForm): class Meta: model = ModelName fields = ['model_field'] I want to fulfill if the of comparing values, but after is_valid () the value of model_value becomes the same as form.cleaned_data ['form_value'] -
I am doing a training project and have encountered a problem
I am doing a training project and have encountered a problem. I try to display the "events" block and the "news" block on the main page, but when I run the loop cycle, only one block is displayed, and the second is not displayed. Explain who knows what I'm doing wrong. I have been solving this problem for three days now. Thanks in advance who will respond to help <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if post %} {% for post in post %} {{ post.title }} {% endfor %} {% else %} <p>У вас нет материала</p> {% endif %} {% if event %} {% for event in event %} {{ event.name }} {% endfor %} {% else %} <p>У вас нет материала</p> {% endif %} </body> </html> Views: from django.shortcuts import get_object_or_404, render from django.views.generic.base import View from .models import Blog, Event # Create your views here. class EventView(View): def get(self, request): event = Event.objects.all() return render(request, "home/home_list.html", {"event": event}) class BlogView(View): def get(self, request): post = Blog.objects.all() return render(request, "home/home_list.html", {"post": post}) Urls: from django.urls import path from . import views urlpatterns = [ path("", views.EventView.as_view()), path("", views.BlogView.as_view()) ] Models: from django.db import models from … -
Django doesn't seem to mock model methods
I am trying to write some test cases for the following method as part of a model called Project: def to_mouse_model(self): details = mm.ProjectDetails( self.name, self.larc, self.investigator, self.release_date, self.priority) details_query = self.strategies.all() designs = {details.design.to_mouse_model() for details in details_query} strategies = {details.strategy.to_mouse_model() for details in details_query} return mm.Project(details, designs, strategies) The trouble seems to be in the details.design.to_mouse_model() and details.strategy.to_mouse_model() and I cannot seem to accurately mock this function. This is the test I have (self.details2 is the only model linked to the project in this test case, so it would be the only record returned by self.strategies.all()): @patch(PROJECT_STR) @patch(DETAILS_STR) def test_to_mouse_model_one_strategy(self, mock_details, mock_project): details = MagicMock() mock_details.return_value = details project = MagicMock() mock_project.return_value = project mm_design = MagicMock() self.details2.design.to_mouse_model = MagicMock(return_value=mm_design) mm_strategy = MagicMock() self.details2.strategy.to_mouse_model = MagicMock(return_value=mm_strategy) self.assertEqual(self.project2.to_mouse_model(), project) mock_details.assert_called_once_with( "Project2", 456, self.inv, RELEASE2, 3) mock_project.assert_called_once_with( details, {mm_design}, {mm_strategy}) And here is the error message I get: AssertionError: Expected call: Project(<MagicMock name='ProjectDetails()' id='172695792'>, {<MagicMock id='172758448'>}, {<MagicMock id='172771504'>}) Actual call: Project(<MagicMock name='ProjectDetails()' id='172695792'>, {<MouseModel.LabWork.DesignTask.DesignTask object at 0x0A4C8CB0>}, {<MouseModel.LabWork.Strategy.Strategy object at 0x0A4C8BD0>}) So from the error message I can see that it is not actually mocking the to_mouse_model() method. I have tried to assert that the method was called and that …