Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django validating a field even when a depending field is empty
I am trying to validate two depending fields such that, if a checkbox is checked, then validate the URL field, but if the checkbox is not checked, do not validate the URL field. Using clean() I have a code that looks like this: models.py class MyModel(models.Model): chkbk = MultiSelectField(max_length=15, choices=choices.SOME_CHOICES, blank=True, null=True) url_field = models.URLField(max_length=200, blank=True, null=True) form.py def clean(self): cleaned_data = super().clean() chkbk = cleaned_data.get('chkbk') url_field = cleaned_data.get('url_field') if chkbk and url_field is None: self.add_error('chkbk', ValidationError("Fix this error")) The logic works if the user checks box and submit a valid URL the user checks box and leaves url field empty, error message the user unchecks box and leaves url field empty But, when the user unchecks the box but have invalid url in the url field, the for does not submit, because regardless of the validation checks, the url field will still try to submit to the database, which is an expected behaviour. Is there a way to not validate the URL field if checkbox is unchecked or set the value of that field to empty/null/None in clean just before submitting the form so validation on the url field can pass if the checkbox it depends on is not … -
how to filter on a reversed relationship on Django?
I have this two models: class Company(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField() class Employee(models.Model): name = models.CharField(max_length=255) incorporated_at = models.DateTimeField() company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="employees") If I do the following reversed lookup: Company.objects.filter(employees__incorporated_at="2021-01-01T00:00:00+00:00") Then I'll get a list of those companies with at least one employee that satisfies such a query. But what I want to get is a list of companies with all its employees satisfying that query. How can I do it? -
Django Pyrebase retrieving from firebase using infinite scroll
I'm a bit stuck on how best to approach this problem. I currently have data being pulled in from Firebase and use django paginator with jquery and waypoints to get an infinite scroll. However, the def innovations_view currently returns all the entries in the database. I want it to return the first 5 then on scroll load another 5. I believe I may need to add a listener, but not sure how best to approach it. Any help would be greatly appreciated. views.py def innovations_view(request): db_name = database.child('1aBDytzaM232X_H3tjTuanG8-jxiEn0rg5_pg_cvnbgw') object_list = db_name.child('Sheet1').get().val() page = request.GET.get('page', 1) paginator = Paginator(object_list, 5) try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) context = { "object_list": objects, } return render(request, 'list.html', context) list.html {% extends 'base.html' %} {% block content %} {% load static %} <div class="container-fluid"> <div class="row row-cols-1 row-cols-md-3 g-4 infinite-container"> {% for instance in object_list %} <div class="col infinite-item"> <div class="card h-100"> <img src="{{ instance.featureimg}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ instance.title }}</h5> <p class="card-text">{{ instance.summary|truncatewords:20 }}</p> </div> </div> </div> {% endfor %} </div> <div class="spinload position-fixed" style="display: none; top:35vh; left:46vw;"> <div class="spinner-border" role="status"> <span class="visually-hidden">Loading...</span> </div> </div> <div> {% if object_list.has_next %} <a class="infinite-more-link" href="?page={{ … -
i want to generate short link and render it to templates using pyshorteners
I want to convert my full url to short url using pyshorteners and render to every detail templates of the link . Here, i am giving below, the views and the link template, with the url patterns. Below is my Views.py: import pyshorteners def get_absolute_url(request): link = request.get_full_path() shortener = pyshorteners.Shortener() short_link = shortener.tinyurl.short(link) return reverse('link', {"link": short_link}) Below is my Link Template: <!-- Copy to Clipboard --> <center> <label for="text_copy" class="text-primary">Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy" value="{{ request.build_absolute_uri }}"/> <div class="container"> <button onclick="copyToClipboard('#text_copy')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </div> </center> <!-- Copy to Clipboard --> <center> <label for="text_copy" class="text-primary"> Short Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy1" value='{{ link.short_link }}'/> <div class="container"> <button onclick="copyToClipboard('#text_copy1')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </div> </center> As I am trying to convert my url to short url, I also tried using python function to also create a short link. Below is how the pyshorteners function module is working. import pyshorteners link = input("Enter the link:") Enter the link:>? http://127.0.0.1:8000/affiliation/link/10003/ shortener = pyshorteners.Shortener() x = shortener.tinyurl.short(link) print(x) h__ps://tinyurlcom/yfzx7uxm #this is the short link i have received and its working. #Also … -
Connect local database in heroko using django
I want don't want to use the Heroku database instead I want to use my local database in the Heroku server. so how do I connect my local database to Heroko. -
Can't I save data in django model from files other than views?I am getting this error
I want to save data in a model. Lets say I want to hard code data from views.py it saves but when i try to do it by creating a seperate file it doesn't. It doesnt import models at all giving error ImportError: attempted relative import with no known parent package.Am I missing something here : I have tried doing: from .models import className from models import className from . import models and calling models.className -
Unable to show user specific link to specific page in django
I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in create/ form. So my problem is, when I filled out the form and redirect to list/ page, there are no links. My code: models.py from django.db import models from django.contrib.auth.models import User class File(models.Model): file = models.OneToOneField(User, on_delete=models.CASCADE, null=True) #Further, they are fileds, which is nececary to create schedule. #title = models.CharField('Название Графика', max_length = 50) #x_title = models.CharField('Название Оси Х', max_length = 50) #y_title = models.CharField('Название Оси Y', max_length = 50) #etc... views.py: def create(request): error = '' if request.method == 'POST': form = FileForm(request.POST) if form.is_valid(): form.save() return redirect('grafic:list') else: error = 'Форма была неверной(' form = FileForm() data = { 'form': form, 'error': error, } return render(request, 'graf/create.html', data) def list(request): qs = File.objects.filter(file=request.user) context = { 'user': request.user, 'qs': qs, } return render(request, 'graf/list.html', context) list.html {% extends 'base.html' %} {% block content %} … -
count event by day?
I need to do a count view that counts the appointments by day for example if there are 4 appointments on June 20 and 3 appointments on June 21. if I logged in on June 20 it will only show me the 4 appointments. this is my current view which didn't work models.py class Appointment(models.Model): appointment_date = models.DateField(null=True) appointment_time = models.TimeField(null=True) patient = models.ForeignKey('Patient', on_delete=models.CASCADE) reseptionist = models.ForeignKey('Reseptionist', on_delete=models.SET_NULL, blank=True, null=True) service = models.ForeignKey('Service', on_delete=models.CASCADE) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) views.py def count_appointment(request): appointment = Appointment.objects.filter(appointment_date__day=datetime.today().day).count() data = {} data['appointment'] = appointment return render(request, 'index.html', context=data) index.html {{appointment.count}} -
How to logout in django
i have created login system for my project. but this login is not django's built in authentication. I think i have successfully completed login but i am unable to logout by either built-in authentication or custom logout. def loginpage(request): if request.method == "POST": loginemail = request.POST.get('email') loginpassword = request.POST.get('password') try: var = Patient.objects.get(email=loginemail) if var.password == loginpassword: #i am not sure for this line also wheather it's right or not for login request.session['user'] = var.id return redirect('/patient') else: messages.add_message(request, messages.INFO, 'Hello world.') except: return HttpResponse("Not Logged in") return render(request, 'home/login.html') this is function i have created for login but not sure if that is working perfectly or not but if i print(request.session) it is giving <django.contrib.sessions.backends.db.SessionStore object at 0x10a150bb0> def handlelogout(request): if request.session: print(request.session) try: del request.session['user'] except: print("not logged out") return redirect('loginpage') this is function for log out. but it always print not logged out in terminal. now what can i do to specify login and logout in this project. -
django-autocomplete-light dependant filter over 3 models
I have 3 models. class FilterDefaultValues(BaseModel): value = models.CharField(max_length=255, null=True, blank=True) display_value = models.CharField(max_length=255, null=True, blank=True) class Filter(BaseModel): name = models.CharField(max_length=255) default_value = models.ManyToManyField(FilterDefaultValues, blank=True) class ProductFilter(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='filters') filter = models.ForeignKey(Filter, on_delete=models.CASCADE) value = models.ForeignKey(FilterDefaultValues, blank=True, on_delete=models.RESTRICT) urls.py class LinkedDataView(autocomplete.Select2QuerySetView): def get_queryset(self): qs = super(LinkedDataView, self).get_queryset() filter = self.forwarded.get('filter', None) if filter: qs = qs.filter(filter_id=filter) return qs urlpatterns = [ url( '^linked_data/$', LinkedDataView.as_view(model=ProductFilter), name='linked_data' ), ] forms.py class ProductFilterForm(forms.ModelForm): def clean_test(self): filter = self.cleaned_data.get('filter', None) value = self.cleaned_data.get('value', None) if value and filter and value.filter != filter: raise forms.ValidationError('Wrong owner for test') return value class Meta: model = ProductFilter fields = ('product', 'filter', 'value', 'value_type', 'product_images', 'is_variation') widgets = { 'value': autocomplete.ModelSelect2(url='linked_data', forward=('filter',)) } class Media: js = ( 'linked_data.js', ) What I want to is in the admin panel when the user selects a filter, then the value field must be populated with appropriate default values. But now what I get is: When user selects filter then only productfilter items are populated here. What I am missing here? -
Why Django cannot extends my form.html contact page and returns a TemplateSyntaxError or an Exception Thrown?
I'm trying to build a contact page ("/contact-us/") as a modular app instead of the similar already working contact page ("/contact/") located in the "/app/" directory. The former is failing, returning either Exception Thrown or TemplateSyntaxError while trying to {% extends %} the form.html with its base.html. My file structure: BlogDjango |-BlogDjango | | settings.py | | urls.py |-app | |-Templates | | | base.html | | | form.html |-blogpost |-contactform | |-Templates | | | base.html | | | form.html | | forms.py | | views.py settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),os.path.join(BASE_DIR,'app','templates'),os.path.join(BASE_DIR,'contactform','templates')],... base.html <!DOCTYPE html> <html> <head></head> <body> {% block content %}{% endblock %} </body></html> form.html {% extends base.html %} {% block content %} {% if title %} <h1>{{ title }}</h1> {% endif %} <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> {% endblock %} It seems that Django doesn't recognise that the base.html is located in the same directory than the form.html and therefor cannot extend it. So I get those two errors thrown at me: Exception Thrown: Failed lookup for key [base] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x000001D62DDBBAF0>>, 'request': <WSGIRequest: GET '/contact-us/'>, … -
Does HTTP 401 response from server clears user credentials from browsers cache?
My Django 2.2 application is using basic http authentication with Apache LDAP. Users can login by entering their username and password using the browser pop-up (image shown below): I'm working on writing a logout function that would return a httpresponse. Below is an incomplete example snippet of what I have mentioned: def process_request(self, request): if request.path == '/accounts/logout/': httpResponse = HttpResponse() httpResponse.status_code = 401 httpResponse.headers['WWW-Authenticate'] = 'Basic realm="<same realm as in the http server>"' return httpResponse else: ... I wanted to know if returning Status code: 401, clear the credentials in browser cache. If not, then is there any other way I can achieve this? Any help is highly appreciated! -
Python: Module not found while importing from multiple subfolders
I have a folder structure like below (attached image) enter image description here In Main.py I imported all the folders. Now Main.py calls subMain.py which is inside the Project 1. subMain.py imports spark, common etc. Now sparkUtils.py has functions from helper.py hence need to import helper.py This throws module import error that "No module named Common" I tried putting init.py in all the folders, however no luck. Can anyone help please? Thanks in advance. -
How to recover deleted data from AWS PostgreSQL database for Django project?
I tried to add a new field in my existing Django project. I run the following command to do it: manage.py makemigrations manage.py migrate appname zero manage.py makemigration manage.py migrate Now I have lost all my previous data from the database (PostgreSQL) for that application. The migration folder only has the most recent migration file. How can I retrieve previous data? I am using AWS PostgreSQL in the project. Any help/suggestion will be appreciated. -
How to include the thumbnail image with using TabularInline admin model?
What I am trying to do I would like to include thumbnail in PhotoInline and could be shown into ProductAdmin. What I have done I made two admin model which are ProductAdmin and PhotoInline. PhotoInline model is a separate admin model that only contains information of photos of products, which is to be connected to ProductAdmin. Inside of PhotoInline, I included custom admin function called product_thumbnail and tried to include list_display admin option of ProductAdmin. Here are my codes: class PhotoInline(admin.TabularInline): ''' PhotoAdmin Definition ''' model = models.Photo fieldsets = ( ( None, { 'fields': ('caption', 'file',) } ), ) extra = 0 and then ProductAdmin admin model looks as follows: @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): ''' ProductAdmin Definition ''' inlines = [ PhotoInline, ] list_display = ( 'product_name', 'product_price', 'product_color', 'product_size', 'product_category', 'is_onsale', 'is_newarrival', 'is_preorder', ) list_filter = ( 'is_onsale', 'is_newarrival', 'is_preorder', ) ordering = ('product_name', 'product_price', 'product_category') search_fields = [ 'product_name', 'product_category' ] Error that I got <class 'products.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[8]' refers to 'product_thumbnail', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'products.Product'. It seems my approach is somewhat wrong. Do I need to include separate ImageField for my Product … -
Django: Simple One:Many fields aren't showing in parent object view in admin
I'm new to Django and have made a couple of classes whereby one Account can have many Subscribers. When viewing a subscriber in the django admin, it correctly shows which account the subscriber is related to. However, when looking at the account, it does not show which subscribers it has. I saw an article (How to create many-to-one relation with django and to display it in admin interface) that suggested using inlines, although it’s not working for me. Where am I going wrong here? Models.py: from django.db import models from django.contrib.auth.models import AbstractUser class Account(AbstractUser): pass class Subscriber(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True) date_joined = models.DateTimeField(auto_now_add=True, null=True) verified = models.BooleanField(default=False) account = models.ForeignKey( Account, on_delete=models.CASCADE) def __str__(self): return self.email list_display = ('first_name', 'email', 'date_joined', 'verified') Admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from accounts import models # does nothing class SubscriberInline(admin.TabularInline): model = models.Subscriber extra = 1 admin.site.register(models.Account, UserAdmin) # does noting class AccountAdmin(admin.ModelAdmin): inlines = [SubscriberInline, ] #inlines = (SubscriberInline, ) @admin.register(models.Subscriber) class SubscriberAdmin(admin.ModelAdmin): list_display = ("first_name", "email", "date_joined", "verified", "account") -
Remove specific object from Many-to-many relationship
I have Two models : class Product(models.Model): product_model = models.CharField(max_length=255, default='') ... class Discount(models.Model): name = models.CharField(max_length=255, default='') items = models.ManyToManyField(Product, blank=True) discount_percent = models.IntegerField(default=0, validators=[ MaxValueValidator(100), MinValueValidator(1), ] ) I want to delete specific item from items(ManyToManyField) my views : def delete_from_discount(request, id, product_url): if request.user.is_staff or request.user.is_superuser: a = Product(product_url=product_url) b = Discount(id=id) b = b.items.remove(a) return redirect("/staff/discount/"+id) else: return redirect('/staff') There is no error but also nothing change from my models, no remove my html: {% for dis in discount.items.all %} <a href="/staff/discount/delete-from-discount/{{discount.id}}/{{dis.product_url}}/">delet</a> {% endfor %} -
TemplateDoesNotExist error while I am using Class-Based Views in django for updating and deleting a record
Here, I am trying to update and delete the product, but whenever I click on the Update and Delete Link Buttons, it shows me TemplateDoesNotExist at affiliation/affproduct_form.html and for delete, it shows TemplateDoesNotExist at affiliation/affproduct_confirm_delete.html I have created the form and done adding and viewing using function-based views. Below is my models.py : #Product details uploaded class AffProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo') product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255, null=True) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product_title Below is my views for update and delete function. I have not used class-based views for creating and detail. but for updating and deleting i have done using class-based views. # update view for details class AffProductUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = AffProduct #model fields = ['product_title', 'uid', 'specification', 'sale_price', 'discount', 'img1', 'img2', 'promote_method', 'terms_conditions',] # fields template_name = 'affiliation/affproduct_form.html' # template for updating #success_url = "/blink_viewproduct.html" # redirect url def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def test_func(self): product = self.get_object() if self.request.user == product.user: … -
Django REST Framework: Use of 'pk' in get_object_or_404
I'm a beginner with the Django REST framework and am building an app that summarizes articles with headers. I'm trying to get information from the Article model to pass into the Summary one. I'm having trouble understanding the use of get_object_or_404 in this scenario (how to instantiate a model) and how I use the pk argument. I tried changing the status URL to status/<int:article_id> and passed article as the pk, but I get a 404 when running the POST request. I'm stuck on how to use that argument otherwise. How do I instantiate a model from my request by using get_object_or_404 properly? views.py: import json from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from rest_framework.decorators import api_view from .models import * @api_view(['POST']) def get_summary(request, pk): article = get_object_or_404(Article, pk=pk) mdl = Summary() return JsonResponse(mdl.preprocess(article.content), safe=False) models.py: # Article class class Article(models.Model): headings = models.CharField(max_length=200) content = models.CharField(max_length=500000) # Summary results class (so far) class Summary(models.Model): preprocessor = TextPreprocessor() in_text = models.CharField(max_length=500000) topics = models.CharField(max_length=200) def preprocess(self, text): return self.preprocessor.preprocess(text) urls.py: from django.urls import path, include from rest_framework import routers from .api import * from .views import * router = routers.DefaultRouter() router.register('my_api', SummaryViewSet, 'api') urlpatterns = [ path('api/', include(router.urls)), … -
AttributeError at /akolaprofile/ 'MyRegistration' object has no attribute 'get'
I am trying to create a user profile by using Django's UserChangeForm. I'm not using Django's User model and had created a custom user model (MyRegistration) by inheriting AbstractBaseUser. I have also assigned my custom user model to AUTH_USER_MODEL in the settings.py. But when I try to access the user's profile page, it throws an AttributeError stating that 'MyRegistration' object has no attribute 'get'. What could possibly be wrong? Below are my codes: models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils import timezone from .manager import FirstManager class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('Solapur', 'Solapur'), ('Latur', 'Latur'), ('Dhule', 'Dhule'), ('Akola', 'Akola'), ('Nashik', 'Nashik') ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default='Latur') designation=models.CharField(max_length=70) is_active=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username views.py: def akolaprofile(request): if request.user.is_authenticated: print(request.user) fm=UserChangeForm(request.user) return render(request, 'akola/akolaprofile.html', {'form':fm}) else: return HttpResponseRedirect('/login/') URLs: path('akolaprofile/', ve.akolaprofile, name='akolaprofile'), Template: {% block content %} <form action="" method="post"> {% csrf_token %} {{form.as_p}} </form> {% endblock content %} Traceback: Traceback (most recent call last): File "C:\Users\pande\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\pande\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Sonu\Projects\Billing\accounting\akola\views.py", line 21, in akolaprofile return render(request, 'akola/akolaprofile.html', … -
best practice for Django junction table model structure
I am using a junction table called "UserRole" for 2 different Django model called CustomUser and Role to specify many to many relationship from both of the table. My consideration is 1 customer can have multiple groups and 1 groups has multiple customers. So now I am little confused that my current model is OK or Do I need to modify from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(models.Model): """Model representing a User with some extended fields and email as username field""" USERNAME_FIELD = 'email' email = models.EmailField(max_length=100, unique=True) is_admin = models.BooleanField(default=False) permissions = models.ManyToManyField('Permission', related_name='+') # other fields goes here if needed REQUIRED_FIELDS = [] def __str__(self): """String for representing the Model object.""" return self.email class Role(models.Model): """Model representing a Role""" name = models.CharField(max_length=200) # other fields goes here if needed class Meta: ordering = ['name'] def __str__(self): """String for representing the Model object.""" return self.name class UserRole(models.Model): """Model representing a User's Role""" # ManyToManyField used because one user can have multiple roles and one role can have multiple users role_id = models.ManyToManyField(Role, on_delete=models.CASCADE, null=False, verbose_name = 'Role', related_name='role') user_id = models.ManyToManyField(CustomUser, on_delete=models.CASCADE, null=False, verbose_name = 'User', related_name='user_role') # other fields goes here if needed So my … -
how to analyzing financial stock data properly
I would like to do a lot of analysis/performance/statistics on my stock portfolio, which I plan to track with my app. E.g.: Week performance Month performance Year performance Best performer and a lot of other things I can't imagine right now... Where I'm struggling right now: - What is a good/the best way to archive this? - Also to show this info on a dashboard --> I think I should store this information somehow... But how to do this on a daily/weekly/whatever basis? --> I don't see a way to do such things while runtime? --> Maybe there is also an MVP solution, that can evolve into a top-notch solution? My models are locking like this at the moment - The position is the clamp around my orders and my EOD data. Right now I'm working with yfinance to get range financial data + finnhub API to get real time prices: class Position(models.Model): name = models.CharField(max_length=100) shares = models.FloatField(default=0.0) symbol = models.CharField(max_length=100, default="") transaction_fee_sum = models.FloatField(default=0.0) profit = models.FloatField(default=0.0) average_price = models.FloatField(default=0.0) cost_value = models.FloatField(default=0.0) last_price = models.FloatField(default=0.0) position_value = models.FloatField(default=0.0) last_update = models.DateTimeField(default=datetime.now(), blank=True) position_started = models.DateTimeField(default=datetime.now(), blank=True) position_ended = models.DateTimeField(default=datetime.now(), blank=True) isin = models.CharField(max_length=12) depot = models.ForeignKey("Depot", blank=True, … -
Django pass input data from an HTML file to a python script and then send the final data to another HTML file
I'm trying to build a simple dictionary in Django. In the home.html file there's a form, which asks the user to enter a word. This word should 'become a variable' in a python script which needs it to retrieve certain data from an API. import json import urllib.request url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/' + user_input response = urllib.request.urlopen(url) result = json.loads(response.read()) final_word = str(result[0]['word']) + ' \n\n' final_def = str(result[0]['meanings'][0]['definitions'][0]['definition'])) 'user_input' would be the variable where the input is stored It should then pass the data obtained from the API (in this case final_word and final_def to another HTML file, final.html I can't figure out how to do this. Any help is appreciated. Comment if I need to add some of the code. Forgive my bad english. -
Styling a email link in Django sent email
I used the example from this example email authorization : to do a user authorization email, which works fine. My email link displays as something like: Hi rascal345, Please click on the link below to confirm your registration: http://127.0.0.1:8000/activate/Mjk/aoi2oo-b778abe73e5c8c0a31910d82039d5d67/ I would like to try to style this link so that it shows as a single clickable button or anchor type link (rather than the link as shown above). I have had a look at various suggestions, but I'm sure how to display this link as a single styled button say. Any suggestions? regards Russell -
Dynamically save the form
I am trying not to use formset in my form. Instead of that, I trying to create form dynamically and save all forms data in DB. Currently, I can create a dynamic form, but the thing is I fail to save all data from the form even though I create multiple forms. Now my code only can save only one form. But I want to save the whole form (with multiple form data) in DB. views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': forms = OrderForm(request.POST) if forms.is_valid(): po_id = forms.cleaned_data['po_id'] supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] order = Order.objects.create( po_id=po_id, supplier=supplier, product=product, part=part, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'product', 'part','po_id'] widgets = { 'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}), 'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}), 'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}), } HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div class="form"> <div class="form-group"> <label for="po_id" class="control-label mb-1">ID</label> {{ form.po_id }} </div> <div class="form-group"> <label for="supplier" class="control-label mb-1">Supplier</label> {{ form.supplier }} </div> <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product }} </div> <div …