Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found, request method: get using Django when all pages correctly in urls.py
I know there are many similar posts, but having tried: Page not found (404) Request Method: GET Django -Page not found (404) Request Method: GET Method Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about I'm still not able to solve this problem. This is a practice sample from cs50w. I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in airline.urls, Django tried these URL patterns, in this order: admin/ flights/ users/ The empty path didn’t match any of these. I have a main urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path("flights/", include("flights.urls")), path("users/", include("users.urls")) ] urls.py in flights: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.book, name="book") ] and in users, url.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout") ] My settings.py: """ Django settings for airline project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os … -
Django with dropzone multiple images do not upload in CBV
Im working on bulletin board for sporting shoes with django. For now my goal is to give an opportunity for users create and post their own bboards with information from models through model.Forms. And the biggest problem is upload propely multiple images using dropzone.js, i spend lots of time for this problem. The first part on 'addpage.html' is usual forms with text and selected inputs, but the second one is the dropzone js div class, cause i know i cannot affort to use 2 forms straight on current page. My question is how am i have to organize my CreateView at views.py for uploading images on server. For now i have only traceback 'AddCardCreateView' object has no attribute 'object!!! And dictionary of images is empty So let's see my code. We will start from models.py (ImagePhoto fk to Card) class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, verbose_name='Пользователь') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд') boots_model = models.CharField(max_length=100, db_index=True, verbose_name='Модель бутс') description = models.TextField(verbose_name='Описание') slug = AutoSlugField('URL', max_length=70, db_index=True, unique_with=('created', 'boots_model', 'size', 'color', 'price'), populate_from=instance_boots_model, slugify=slugify_value) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена') created = models.DateTimeField(auto_now_add=True, db_index=True) updated = models.DateTimeField(auto_now=True) size = models.DecimalField(max_digits=4, decimal_places=1, verbose_name='Размер') NEW = 'new' USED = … -
Django ModelForm Widget attributes generation in HTML
What is the proper way to have Django rendering widgets to html elements with correct attributes? Following the documentation I did the following for my class: CLASS: class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='TravelsApp/profile_pics',blank=True) phone_number = models.CharField() credits = models.PositiveIntegerField(default=10) exp_date = models.DateField(default = timezone.now) ..... FORM class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('profile_pic', 'phone_number', 'exp_date') widgets = { 'profile_pic': forms.ClearableFileInput(attrs={'class': "w3-btn w3-blue w3-center"}), 'phone_number': forms.TextInput(attrs={'class': "w3-input", 'required':'True'}), 'exp_date': forms.DateInput(attrs={'class': "w3-input", 'required':'False', 'disabled': 'True'}), } ....... VIEW: def register(request): ....... # GET: Just render the forms as blank. user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'TravelsApp/registration.html', {'user_form':user_form, 'profile_form':profile_form, }) When register() gets called and the code after #GET is executed the 'exp_date' UserProfileInfoForm is not rendered properly : HTML: <p><label for="id_exp_date">Exp date:</label> <input type="text" name="exp_date" value="2021-07-21" class="w3-input" disabled="True" required id="id_exp_date"> <input type="hidden" name="initial-exp_date" value="2021-07-21 20:06:53+00:00" id="initial-id_exp_date"></p> The attribute 'required' is present (hence meaning required = true) while it should be set to false (It also generates this 'initial-exp-date' which is hidden and I think it's added just for security reasons) I tried to play around for one long evening then I noticed that if I change the form definition removing the 'exp_date' from the 'fields' … -
Add a button along save buttons in Django Admin Change Form
I have this code for a custom change_form: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block after_related_objects %} <button>Another button</button> {% endblock %} {% block submit_buttons_bottom %} {{ block.super }} <!-- import script --> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} which produces this view: It works fine but I wanted to add it inside the button row below: I tried to change the code to: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block submit_buttons_bottom %} <button>Another button</button> {% endblock %} {{ block.super }} <!-- import script --> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} but it's giving me an invalid block error. How do I add the button element to produce the result in the image above? -
Django custom user error when registering: get_session_auth_hash() missing 1 required positional argument: 'self' (new user can otherwise log in)
I am aware of this answer: TypeError: get_session_auth_hash() missing 1 required positional argument: 'self', but I am not using a custom backend and the error in question happens when registering a new user through a Django form, not when logging in. Further, whilst the user does not remain logged in when registering and is not automatically redirected to the main page as intended, logging in from the log in form seems to function normally. The error happens on this line in my registration view: login(request, User) And traces back to this line in django.contrib.auth: if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() <<<<<<<<< This line I think because I'm using a custom user, there's something else I need to modify in the default code, but I'm not sure what this should be. I think the custom user model should be interchangeable with the default user model, but it isn't and I'd welcome someone with more experience than me pointing me in the right direction. My code as follows: Custom user model and manager in models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password = None, active = True, staff = False, superuser … -
Django get all objects whose many to many filed contains a filter
I have 3 models: City: indicating a city Titles: indicating job titles Contacts: indicating people. A person can have multiple titles and multiple cities Now, given an city object and a title object, I want to query for all people that have those objects in their instance. Basically something like "All Lawyers in NY". class City(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name=models.CharField(max_length=40) state=models.CharField(max_length=15) class Title(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title_name=models.CharField(max_length=40) class Contact(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name_surname = models.CharField(max_length=60) title = models.ManyToManyField(Title) city = models.ManyToManyField(City) -
Django models create multiple choices field with status
I have a question about my models, I need to create a post request in which I select a couple of people for one POST and I want to add a status to each of them assigned to a given person my models.py class Daily(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.CharField(choices=utils.TEAM, max_length=8, default=None, blank=False) person1 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) person2 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) person3 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) date = models.DateField() class Meta: ordering = ('-date',) constraints = [ models.UniqueConstraint(fields=['user', 'date'], name='name of constraint') ] so my question is how to optimize it, for every record will be choices 2 or 3 person, but now i wanna add status choices for each of them and be unique for choices person -
How to reformat a Nigerian phone number in Javascript or Python function [closed]
I received phone numbers in different formats and I will like to convert them to a particular format before using them.These are the following formats users will always submit: +234 816 312 1111 234 816 312 1111 +2348163121111 2348163121111 0816 312 1111 08163121111 I will like to always reformat the number to No 6. i.e 08163121111. The implications of this are: '+' signs are removed spaces between the numbers are removed. country code (234) are removed. '0' are added at the beginning of the numbers after removing country code. How do I achieve this in javascript or using a python function. -
How can I create submit form in Django with dropping down list?
I am just starting to work with Django and I have some problems with forms and dropping lists. So, let me explain my problem: I have a model with two attributes, I want to display one of the attributes in a dropping down list (This one will be unchangeable) and another one in a text field (This one will be changeable). Also, I have a submit button, so I want to change a second attribute in a text field and by pressing on the button. I have no idea how to do this, can somebody type examples? Thank you! -
Using django model in django template javascript json error
I want to use django model in template javascript and people say I need to make it into json and then pass it so I made json object from models.py and views.py like this. models.py from django.db import models from django.utils.timezone import localdate class Posts(models.Model): address = models.CharField(max_length=100, null=True) lat = models.CharField(max_length=50, null=True) lng = models.CharField(max_length=50, null=True) name = models.CharField(max_length=50, null=True) title = models.CharField(max_length=50, null=True) pick_date = models.DateField(null=True) create_date = models.DateField(auto_now=True, null=True) music = models.CharField(max_length=100, null=True) mood = models.CharField(max_length=50, null=True) description = models.CharField(max_length=300, null=True) image = models.ImageField(upload_to="images/", null=True) # H E R E # def to_json(self): return { "address": self.address, "lat": self.lat, "lng": self.lng, "name": self.name, } def __str__(self): return str(self.title) views.py import json def post_list(request): posts = Posts.objects.all() context = { "posts": posts, "posts_js": json.dumps([post.to_json() for post in posts]), } return render(request, "posts/map_marker.html") map_marker.js // this js file is linked to map_marker.html let posts = JSON.parse("{{ posts_js | escapejs }}"); console.log(posts); I want to see how the posts object looks like but it keeps saying json error JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data It's hard to find a reason as I can't look through how the json object looks like. … -
Perform action from a form or link without refreshing the page/view with django
I'm developing a project where I need to add members to a group, for that, I go through all registered members and present them in my html template. Each member has the "add" button next to it, but always when doing this it refreshes a page... I would like to know how to do this without needing to refresh, ie click on add and it is already added automatically. views.py def add_members(request, id): plan=Plan.objects.get(id=id) users = User.objects.all() # extended django's default user model return render(request,'site/add_members.html', {'plan':plan, 'users':users}) add_members.html {% extends 'base.html' %} {% block title %} Add Members {%endblock%} {% block content %} <div class="row"> {% for i in users %} <h4>{{i.first_name}}</h4> <form method="POST"> {% csrf_token %} <input type="submit">Add</input> </form> {%endfor%} </div> {%endblock%} -
css is not working in my blog page only other pages working properly in my django project
I am working on a django project. All css working well on my local server but when i am hosting on pythonanywhere.com then css of only /blog url not working properly. I can't able to find the error. Please help me. You can visit my hosted website at http://sauravportfolio.pythonanywhere.com/blog/ and you can see my entire code at github https://github.com/saurav389/portfolio . you can see my all css code at portfolio/src/portfolio/static/css/ folder. and my bootstrap is not working in chrome browser too. Please do something for me. -
Django filter Logging to slack channel
I am trying to implement a function to filter the error message that sent to Slack channel. I still want it to log in .log file just dont want it sent it out to Slack. This is what i have tried so far: def contains_url(record): if 'abc' in record.request.path: return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[{levelname}] {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': {'format': '[{levelname}] -- : {message}', 'style': '{',}, }, 'filters': { 'contains_url': { '()': 'django.utils.log.CallbackFilter', 'callback': contains_url, } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.log', 'formatter': 'simple', }, 'slack_admins': { 'level': 'ERROR', 'filters': ['contains_url'], 'class': 'django_slack.log.SlackExceptionHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'slack_admins'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), } } so basically, i would want all the error message from an url that contain 'abc' log to the log.log as usual but just not want it in slack channel. I added slack_admins -> filters but it didn't help. Any suggestions ? Thanks -
Getting an error when attempting to run my utility script
I am trying to build a database load utility for my project. The old application is running and has MySQL dB records that I want to import into the Django mysql instance. I started writing a script and was able to connect to my old (outside of Django) DB just fine, but wanted to use the models in my new Django project so that I can create objects and use the save routines/methods etc. Just in the beginning stages, but when I attempt to import the models from my Django site in my new utility app, it says module not found...? Am I missing something? I did a python manage.py startapp db_load to create my app. The code resides there in a file named db_load.py. Here is what it looks like: #!/usr/bin/env python ################################ # This utility will load old records from a Production db # stored in local host into the Django database on local host # ################################ import MySQLdb from trackx_site.models import Program db_old_trackx = MySQLdb.connect( host= "localhost", db = "old_db", user = "root", passwd = "blah blah", charset='utf8mb4') db_django_db = MySQLdb.connect( host = "localhost", db = "new_project_blah", user = "root", passwd = "blah") sql = "select ......" … -
ModuleNotFoundError: No module named 'music_controller.api'
When I run the server, I am getting the following error: from music_controller.api.models import Room ModuleNotFoundError: No module named 'music_controller.api' I think the problem is from the import in the views.py: from django.shortcuts import render from rest_framework import generics from .serializers import RoomSerializer from .models import Room # Create your views here. class RoomView(generics.CreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer I made sure that the app name is included in INSTALLED_APPS in the settings.py. The following is the tree of my project: -
How to get just the relational fields of a model?
Here is my model, the question is below. from django.db import models # ... class County(models.Model): name = models.CharField(max_length=50, verbose_name=_("Numele județului")) capital = models.ForeignKey("Municipality", on_delete=models.PROTECT, null=True, blank=True, related_name="capital_of", verbose_name=_("Reședința")) region = models.ManyToManyField(Region, related_name="counties", verbose_name=_("Regiunea")) area = models.IntegerField(verbose_name=_("Suprafața")) population = models.IntegerField(verbose_name=_("Populația")) description = models.TextField(verbose_name=_("Descrierea")) north = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_south", verbose_name=_("Nord")) northeast = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_southwest", verbose_name=_("Nord-est")) east = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_west", verbose_name=_("Est")) southeast = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_northwest", verbose_name=_("Sud-est")) south = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_north", verbose_name=_("Sud")) southwest = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_northeast", verbose_name=_("Sud-vest")) west = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_east", verbose_name=_("Vest")) northwest = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="to_southeast", verbose_name=_("Nord-vest")) class Meta: verbose_name = _("Județ") verbose_name_plural = _("Județe") def __str__(self): return self.name @property def neighbours(self): neighbour_counties = {} for field in self._meta.fields: if field.related_model == County: neighbour_counties[field.name] = field return neighbour_counties neighbours.fget.short_description = _("Vecinii") In this example I want to add two instances: Olt and Teleorman. If I create Olt and specify Teleorman as its eastern neighbour, how can I automatically set the western neighbour of Teleorman to Olt? My idea was to get a list with the eight neighbour fields as a property and it works fine until I try to get … -
How to prevent "Frame load interrupted" Safari browser console error upon form-initiated download?
I have tried all the answers I could find regarding this Safari browser console error: Failed to load resource: Frame load interrupted and so far, none of the suggestions have prevented the error. To summarize, I have an advanced search page that presents search results on the same page as the search form. When there are results, I include a separate download form (with a hidden element containing the DB query (in the form of JSON) and a visible button named "Download". There are 2 classes involved: the advanced search class (AdvancedSearchView) and the advanced search download class (AdvancedSearchTSVView). The download works. So all I want to do is prevent the error from appearing in the browser console. Here are the snippets that I believe are relevant: views.py class AdvancedSearchView(MultiFormsView): template_name = "DataRepo/search_advanced.html" download_form = AdvSearchDownloadForm() ... def form_valid(self, formset): download_form = AdvSearchDownloadForm(initial={"qryjson": json.dumps(qry)}) return self.render_to_response(self.get_context_data( ... download_form=download_form)) class AdvancedSearchTSVView(FormView): form_class = AdvSearchDownloadForm template_name = "DataRepo/search_advanced.tsv" content_type = "application/text" success_url = "" basv_metadata = BaseAdvancedSearchView() def form_valid(self, form): cform = form.cleaned_data qry = json.loads(cform["qryjson"]) now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") filename = (qry["searches"][qry["selectedtemplate"]]["name"] + "_" + now.strftime("%d.%m.%Y.%H.%M.%S") + ".tsv") res = performQuery(qry, q_exp, self.basv_metadata.getPrefetches(qry["selectedtemplate"])) response = self.render_to_response(self.get_context_data(res=res, qry=qry, dt=dt_string, … -
How to get a DateTime picker on clear django?
I need to have a picker for DateTimeField, but I dont realy know how to do it. Ive tried admin widget but I think I did it wrong. The closest thing to a solution was: models.py class MyModel(models.Model): myfield = models.DateTimeField() forms.py class MyModelForm(forms.ModelForm): class Meta: widgets = {'myfield': widgets.SplitDateTimeWidget( date_attrs={'type': 'date'}, tame_attr={'type': 'time'})} It shows me a working picker, but when i try to press a save button it says me an error about method 'strip' (forgot actual error, sry). -
HTML forloop - double
I am in my HTML file for my website. The first forloop checks to see what account the user is logged into and then only displays that user's data and it works perfectly on its own. {% for item in user.Doc.all %} The second forloop loops through all the data that "__stratswith"Title: " and displays it and this works perfectly on its own. {% for post in templates %} I am using Django and python to build the website and once running into this problem I have researched if there is any other way to loop through the forloops in a different location like my views.py file and I have had no luck. I need to do it in the HTML but when I write this... {% for item in user.Doc.all %} {% for post in item.templates %} {{ post.content }} {% endfor %} {% endfor %} It doesn't work. It indicated that there is data trying to be displayed because I have an if statement before the for-loops but no data is displayed. I need the proper way to write a nested forloop in an HTML file properly and I cant figure it out. The example I have should … -
Django - How to create ManyToMany relations with "through" and "to"?
I have 3 models to create a proper relation between a Genre and a Movie object. In addition I also have MovieGenre model to glue Movies and Genre model together: class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name=_("Genre"), blank=True, null=True, editable=False, unique=True, max_length=50) class Movies(models.Model): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) genre_relation = models.ManyToManyField(through='MovieGenre', to='Genre') class MovieGenre(models.Model): movie = models.ForeignKey(Movies, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) I have noticed that if I create new genre objects and there relations like so: def pull_genre(object_id): if genre_value: object_genre = genre_value.split(", ") for genre in object_genre: new_genre, create = object_id.genre_relation.get_or_create( name=genre, movies=object_id ) I get many times the same "name" under a different "id" at my "Genre" model where I basically only need the name once. For example name=Comedy is present under many different ID's ... Why that? I also tried unique=True at the name field but running into: django.db.utils.IntegrityError: (1062, "Duplicate entry 'Drama' for key 'App_genre_name_b25416d5_uniq'") How can I create the relation without this strange flaw? In the end I only need "name" at "Genre" model once and the relation between one "Movie" and multiple "Genre" trough the MovieGenre model. Thanks in advance -
Display a Boolean field result if it's True
I'm having trouble here to display the return of a boolean field in the template. I need to display the name of the field if it is true in the template. Any help will be welcome. models ´´´ class IEIS(Model.models): topo = models.BooleanField() ´´´ views def view_ieis(request, pk): ieis = IEIS.objects.get(pk=pk) return render(request, 'ieis/view.html', {'ieis': ieis,}) template.html <div table class="table table-reponsive"> <table class="table table-bordered"> <thead> <tr> <th scope="col">Tipo</th> </tr> </thead> <tbody> <tr> <td> {% if topo is True %} <p>Topo</p> {% endif %} </td> </tr> </tbody> </table> </div> -
AttributeError: type object ' ' has no attribute 'object'
I'm learning python and follow step by step the book "Learning python" Eric Metiz. I am so confused, I had checked the code a few times and it exactly the same as in the book. Could you help me out with this? in models.py from django.db import models class Topic(models.Model): # Тема, которую изучает пользовательн text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): # Возвращает строковое представление модели return self.text class Entry(models.Model): # Информация, изученная пользователем по теме topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if len(self.text) > 50: return self.text[:50] + "..." else: return self.text in views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): # Домашняя страница Learning_log return render(request, 'learning_logs/index.html') def topics(request): # Выводит список тем topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): # Выводит одну тему и все ее записи topic = Topic.object.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) The stacktrace: [21/Jul/2021 15:12:05] "GET / HTTP/1.1" 200 396 [21/Jul/2021 15:12:06] "GET /topics HTTP/1.1" 200 352 Internal Server Error: /topics/1/ Traceback (most recent … -
Django - Why is this TableView not ordering the queryset?
I have a TableView in a Django project which isn't properly ordering its queryset. I tried adding the ordering to the model Meta, overriding the view's get_queryset method, and don't know how best to tackle this. This doesn't happen in any other view, I have many views with many different models, and usually overriding the "get_queryset" method works fine, and I can order however I need there, but right now it isn't working in this particular view. The view looks like this: class ShippingCenterPricesTableView(PurchaseViewingPermissionMixin, PagedFilteredTableView): model = ShippingCenterPriceHistory table_class = ShippingCenterPricesTable template_name = 'purchases/shipping_center/shipping_center_prices_table.html' filter_class = ShippingCenterPriceFilter export_name = "PreciosCentrosDeEmbarque" formhelper_class = ShippingCenterPriceFormHelper paginate_by = 100000000 def get_context_data(self, **kwargs): context = super(ShippingCenterPricesTableView, self).get_context_data(**kwargs) context['allows_shipping_center_creation'] = self.request.user.purchases_permission == '2' return context def get_queryset(self, **kwargs): qs = super(ShippingCenterPricesTableView, self).get_queryset() qs = qs.order_by('-date') return qs The model looks like this: class ShippingCenterPriceHistory(models.Model): shipping_center = models.ForeignKey(ShippingCenter, on_delete=models.SET_NULL, null=True, blank=False, verbose_name='Centro de embarque') circular_price = models.FloatField(verbose_name='Precio circular sin I.V.A.', null=False, blank=False) differenced_price = models.FloatField(verbose_name='Precio diferenciado', null=False, blank=False) date = models.DateField(verbose_name='Fecha actualización', auto_now_add=True) observations = models.CharField(verbose_name='Observaciones', max_length=100, null=True, blank=True) current = models.BooleanField(verbose_name='Precio actual', default=True) @property def discount_percentage(self): return 1 - (self.differenced_price / self.circular_price) class Meta: ordering = ('-date',) And, in case it's relevant, the Table looks … -
ERROR RUN pip install -r requirements.txt when using docker-compose up
How should I create and install the requirements.txt file in order to be able to read it properly when running docker-compose up? Problems when running docker-compose up with the requirements.txt created via pip freeze > requirements.txt requirements.txt: certifi==2021.5.30 charset-normalizer==2.0.3 Django==2.2.5 django-cors-headers==3.7.0 django-rest-framework==0.1.0 djangorestframework==3.12.4 idna==3.2 psycopg2 @ file:///C:/ci/psycopg2_1612298715048/work python-decouple==3.4 pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work requests==2.26.0 sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work urllib3==1.26.6 wincertstore==0.2 I use anaconda and pip to install packages The Dockerfile for the backend of my app tries to RUN pip install -r requirements.txt rising the following errors. I could sense the @ packages arise error, but the strangest for me is the first one (#17 1.299) since it seems to be focusing on python-decouple==3.4 as just python. => ERROR [... 4/5] RUN pip install -r requirements.txt 1.8s ------ > [... 4/5] RUN pip install -r requirements.txt: #17 1.299 DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429). #17 1.345 Collecting certifi==2021.5.30 (from -r requirements.txt (line 1)) #17 1.515 Collecting charset-normalizer==2.0.3 (from -r requirements.txt (line 2)) #17 1.541 Could not find a version that satisfies the requirement charset-normalizer==2.0.3 (from -r requirements.txt … -
Django How to capture a C2B Transaction in Django
I want to capture transactions made to my till number directly (Not those paid via STK push) so that I can save them to database. How do I go about it. I am using django