Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not raising validation error when passwords don't match
I'm creating a page for users to register and can't seem to get the validation error to show when users try registering with two passwords that don't match. It continues to allow them to register and creates a User object in the database with the first password they entered. Here is my UserRegistrationForm: class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) passsword2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError("Passwords don't match.") print("Passwords dont match") return cd['password2'] and my register view: def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): #Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) #Set the chosen password new_user.set_password(user_form.cleaned_data['password']) #Save the User object new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) and finally my register.html. I have just tried adding in {{ user_form.errors }} as per the answer to a similar question but it did not help. <p>Please sign up using the following form: </p> <form method="post"> {{ user_form.as_p }} {{ user_form.errors }} {% csrf_token %} <p><input type="submit" value="Create my account"></p> </form> {% endblock %} Thanks!! -
How can you create a registration form for an already existing template? Django
I'm looking to create a registration form but for a template that I've already build. The problem is that such template doesn't detect Django's prebuild form methods and the form isn't saved when the user enters his details. How can you fix this? template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin 2 - Login</title> <!-- Custom fonts for this template--> <link href='{% static "vendor/fontawesome-free/css/all.min.css" %}' rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href='{% static "css/sb-admin-2.min.css" %}' rel="stylesheet"> </head> <body class="bg-gradient-primary"> <div class="container"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-5 d-none d-lg-block bg-register-image"></div> <div class="col-lg-7"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1> </div> <form class="user" method="POST"> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <input type="text" class="form-control form-control-user" id="exampleFirstName" placeholder="First Name"> </div> <div class="col-sm-6"> <input type="text" class="form-control form-control-user" id="exampleLastName" placeholder="Last Name"> </div> </div> <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" placeholder="Email Address"> </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <div class="col-sm-6"> <input type="password" … -
Production Docker/Django/Gunicorn/Nginx works locally but "Exit code 0" when deployed as AWS ECS Task
I have a Docker/Django/Gunicorn/Nginx project that I have just Dockerised and deployed to AWS. When running locally everything works as expected when I visit localhost:1337, but when deployed to AWS, the container exits with Exit Code 0 and no logs. It seems like everything else in my AWS VPC is working as it should. Code is hosted on GitHub, when pushed, buildspec.yml starts a build on CodeBuild which happily passes and pushes to ECR. I have an ELB that is redirecting 80 to 443 which then forwards to my EC2 target group. SSL Certificates registered with AWS, and if I visit the DNS of the ELB I can see it is secured. I have an ECS Cluster running an active ECS Service, with a single task to run my container. My container is trying to run my production image from ECR. I'm also running a postgres RDS, the URI passed in to the container via EnvVars (see below). Every time the instance tries to spin up the Task, it exits with a code 0. I'm a front end dev and new to these technologies so am having difficulty troubleshooting the issue. My code as is follows, some information starred out … -
How to add IDW as a vector overlay in GIS map
I have developed a GIS based web application project using Django 3.1 and openlayers version 6. In my project we have a polygon boundary of an area and 6 pre-fixed sample locations inside the boundary for collecting the data. Now I want to show the inverse distance weighted(IDW) interpolation of the polygon as vector overlay layer in the map based on the collected data from the sample locations. advice the best method to integrate idw in my project. -
Updating cleaned_data based on forms input?
I am trying to adjust the cleaned_data that I get from the modelform to save certain values to the model based on the users input. These inputs can vary greatly, please see the model below along with the forms and views. Should I call the model methods into the model form or should I do all the calculations in the modelForm itself. The figures can change depending on the contract selected and the start date selected as it will count the number of days and base it on this price for the contract, however if it is a half day then it will just divide the number by 2. I am still new to Django but trying to figure out where all this information should be put, I am certainly clueless on this and trying to learn Django myself through real lifelike applications instead so appreciate your help. Model class AdminData(models.Model): year1 = models.IntegerField() year3 = models.IntegerField() year1_fortnight = models.IntegerField() year3_fortnight = models.IntegerField() @property def fortnight_dayrate_year1(self): return self.year1_fortnight / weeksinyear / 5 @property def fortnight_dayrate_year3(self): return self.year3_fortnight / weeksinyear / 5 @property def day_rate_year1(self): return self.year1 / weeksinyear / 5 @property def day_rate_year3(self): return self.year3 / weeksinyear / 5 class … -
Django Project with data import service
I want to add a service to my Django project that connects to an external streaming API to fetch new data, and inserts this into the database. The service uses the Django ORM. This service never ends, and it should therefore not intervene with the website. Can I create such a service by generating a new app called importservice, or where should such service be created? In addition, how would I run such service? -
Fetch specific related models from a one-to-many relationship
I have two models Contact and Address. Contact has a one to many relationship to Address. There's a column "is_primary" on Address to indicate the main address for each Contact. Now, I'd like to create a model manager to return a queryset with all Contact objects and the related Address object that has "is_primary=True". The database should only be hit once. The goal is to use the queryset in a template and have the primary address together with the contact information in one record. How can this be done? Here's are the simplified models: class Contact(models.Model): id = models.UUIDField(primary_key=True) class Address(models.Model): id = models.UUIDField(primary_key=True) contact = models.ForeignKey(Contact, on_delete=models.PROTECT) is_primary = models.Boolean() first_name = models.CharField(max_length=50) ... -
django.core.exceptions.ImproperlyConfigured: uses parameter name 'order.id' which isn't a valid Python identifier
when im running the command python manage.py runserver im grting error django.core.exceptions.ImproperlyConfigured: URL route 'order_detail/int:order.id/' uses parameter name 'order.id' which isn't a valid Python identifier. views.py def order_detail(request, order_id): if request.user.is_authenticated: email = str(request.user.email) order = Order.objects.get(id=order_id, emailAddress=email) order_items = OrderItem.objects.filter(order=order) return render(request, 'store/order_detail.html', {'order': order, 'order_items': order_items}) urls.py urlpatterns = [ path('', views.home, name='home') path('order/<int:order.id>/', views.order_detail, name='order_detail'), ] template file detail.html {% for order in order_details %} <tr> <td>{{ order.id }}</td> <td>{{ order.created|date:"d M Y" }}</td> <td>{{ order.total }}</td> <td><i class="fas fa-check"></i>&nbsp;Complete</td> <td><a href="{% url 'order_detail' order.id %}">View Order</a></td> </tr> {% endfor %} -
Why is my django-filter input box not appearing?
Why is my django-filter input box not appearing? I am trying to replace a search bar with this filtering system so when they search for a particular username at the header, they will be directed to an account/filter_results.html page to show the filtered results. However, only the submit button appears but not the input box. Kindly advise filters.py import django_filters from account.models import Account class UserNameFilter(django_filters.FilterSet): username = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = Account fields = ['username'] views.py def account_search_view(request, *args, **kwargs): context = {} account = Account.objects.all() context['account'] = account username = UserNameFilter(request.GET, queryset=Account.objects.all()) context['username'] = username return render(request, "account/filter_results.html", context) urls.py urlpatterns = [ path('search/', account_search_view, name="search"), ] header.html page <form method="get"> {{ username.form }} <input class="btn btn-success" type="submit"/> </form> filter_results.html page {% for obj in username.qs %} {{ obj.email }} - ${{ obj.price }}<br /> {% endfor %} models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) -
Vue app structure in a Django application
I added VueJS to my Django project, i just integrated it using webpack and django webpack-loader, but i'm very new to Vue so i have some doubts on how should my app be structured. I have a main.js file, an app.vue and a folder of components that i created on my own. In this project it's Django rendering Vue on a template, so what i do is to render an html template and inside of it the Vue app. Now i have some doubts about the structure: instead of loading the whole app, i load the app and choose the components i need according to the page where Vue is being used. Here is an example: myDjangoTemplate.html {% load render_bundle from webpack_loader %} {% block content %} <div id="app"> <someComponent /> <anotherComponent /> </div> {% render_bundle 'chunk-vendors' %} {% render_bundle 'chart' %} {% endblock %} My question is: is this the right way to use Vue? Is it ok to only load the app and then only the components i need or is it bad practice? Any kind of advice is appreciated -
i want my every model object to have its own view and url
I have 100's of companies in my DB, I want each model to have a view and URL. how to do it in Django? I have gone through Django docs but couldn't use that method because my primary key is not an id but a string field. This is my model. class CompBrief(models.Model): company_N_B = models.CharField(max_length=100) company_S_B = models.CharField(max_length=100, primary_key=True) industry_N = models.CharField(max_length=100, null=True) price = models.CharField(max_length=100) pe = models.CharField(max_length=100) pb = models.CharField(max_length=100) ps = models.CharField(max_length=100) dy = models.CharField(max_length=100) -
django raise uncommited atomic block without reporting any exception
I have used nginx + gunicorn + django + drf setup for running my website. I have somehow large amount of requests to process using this config, sometimes it could reach 10k requests per second in a simple server. If the concurrency rate reaches a significant amount, I get an exception from django talking about using new query in an unrolled back atomic block. An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block I am getting this error in different parts of the code, and it is strange that the traceback did not report any exception inside another exception so I could not find any atomic block that did not roll back already. I wonder may be it is a problem with an opened connection and reusing it before completely getting rolled back. I try to find a way to debug this problem and find what is the atomic block which is not rolled back before new query. I used gunicorn 20.0.4 and django 3.1.1 and mysql 8.0 and I do not set CONN_MAX_AGE so I except to remained open connection for another use. For gunicorn I used gevent worker class. -
How to create a Django MPTT model with multiple trees
I am trying to create a structure where I have one model named "Company" and another model named "FSLI". The FSLI is an MPTT model. Each FSLI must be mapped to a Company. Each Company can have multiple FSLIs. Following is my code for FSLI model: class Fsli(MPTTModel): name = models.CharField(max_length=255) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='parent_child') company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="company_fsli") ASSET = "asset" LIABILITY = "liability" EQUITY = "equity" INCOME = "income" EXPENSE = "expense" FSLI_TYPES = ( (ASSET, "Asset"), (LIABILITY, "Liability"), (EQUITY, "Equity"), (INCOME, "Income"), (EXPENSE, "Expense"), ) fsli_type = models.CharField(max_length=9, choices=FSLI_TYPES, default=ASSET) remap_locked = models.BooleanField(default=False) rename_locked = models.BooleanField(default=False) delete_locked = models.BooleanField(default=False) unmapped_cat = models.BooleanField(default=False) statement = None if fsli_type == 'income' or fsli_type == 'expense': statement = 'pl' else: statement = 'bs' def __str__(self): return f"{self.name} - {self.fsli_type} - {self.company}" I want Django-MPTT to create separate tree structures for FSLI objects based on their 'company' field. For example, one tree of FSLI objects for company "foo" and another for company "bar" How do I do that? Also, will I encounter any additional problems/limitations later when accessing and updating the trees using this approach, as compared to simple single tree structures? -
I can't integrate aramex API with django
ARAMEX Response {http://ws.aramex.net/ShippingAPI/v1/}Shipment() got an unexpected keyword argument 'TransportType'. Signature: Reference1: xsd:string, Reference2: xsd:string, Reference3: xsd:string, Shipper: {http://ws.aramex.net/ShippingAPI/v1/}Party, Consignee: {http://ws.aramex.net/ShippingAPI/v1/}Party, ThirdParty: {http://ws.aramex.net/ShippingAPI/v1/}Party, ShippingDateTime: xsd:dateTime, DueDate: xsd:dateTime, Comments: xsd:string, PickupLocation: xsd:string, OperationsInstructions: xsd:string, AccountingInstrcutions: xsd:string, Details: {http://ws.aramex.net/ShippingAPI/v1/}ShipmentDetails, Attachments: {http://ws.aramex.net/ShippingAPI/v1/}ArrayOfAttachment, ForeignHAWB: xsd:string, TransportType_x0020_: xsd:int, PickupGUID: xsd:string, Number: xsd:string, ScheduledDelivery: {http://ws.aramex.net/ShippingAPI/v1/}ScheduledDelivery Request DATA request_data = {"Shipments":{"Shipment":{"Shipper":{"Reference1":"123","Reference2":"","AccountNumber":"20016","PartyAddress":{"Line1":"44 rue ariana","Line2":"","Line3":"","City":"ariana","StateOrProvinceCode":"","PostCode":"","CountryCode":"TN"},"Contact":{"Department":"","PersonName":"Tiktak","Title":"","CompanyName":"Tiktak","PhoneNumber1":"50487183","PhoneNumber1Ext":"","PhoneNumber2":"22554777","PhoneNumber2Ext":"","FaxNumber":"","CellPhone":"50487183","EmailAddress":"bouhejbazied@gmail.com","Type":""}},"Consignee":{"Reference1":"100","Reference2":"","AccountNumber":"","PartyAddress":{"Line1":"adresse","Line2":"","Line3":"","City":"tunis","StateOrProvinceCode":"","PostCode":"","CountryCode":"TN"},"Contact":{"Department":"","PersonName":"Ali","Title":"","CompanyName":"Ali","PhoneNumber1":"48777999","PhoneNumber1Ext":"","PhoneNumber2":"","PhoneNumber2Ext":"","FaxNumber":"","CellPhone":"48777999","EmailAddress":"bouhejbazied@gmail.com","Type":""}},"ThirdParty":{"Reference1":"","Reference2":"","AccountNumber":"","PartyAddress":{"Line1":"","Line2":"","Line3":"","City":"","StateOrProvinceCode":"","PostCode":"","CountryCode":""},"Contact":{"Department":"","PersonName":"","Title":"","CompanyName":"","PhoneNumber1":"","PhoneNumber1Ext":"","PhoneNumber2":"","PhoneNumber2Ext":"","FaxNumber":"","CellPhone":"","EmailAddress":"","Type":""}},"Reference1":"1","Reference2":"","Reference3":"","ForeignHAWB":"","TransportType":0,"ShippingDateTime":1604504020,"DueDate":1604504020,"PickupLocation":"","PickupGUID":"","Comments":"","AccountingInstrcutions":"","OperationsInstructions":"","Details":{"Dimensions":{"Length":"1","Width":"1","Height":"0.1","Unit":"cm"},"ActualWeight":{"Value":"0.5","Unit":"kg"},"ProductGroup":"DOM","ProductType":"FIX","PaymentType":"P","PaymentOptions":"","Services":"CODS","NumberOfPieces":1,"DescriptionOfGoods":"","GoodsOriginCountry":"TN","CashOnDeliveryAmount":{"Value":"99.8","CurrencyCode":"TND"},"InsuranceAmount":{"Value":0,"CurrencyCode":""},"CollectAmount":{"Value":"","CurrencyCode":""},"CashAdditionalAmount":{"Value":0,"CurrencyCode":""},"CashAdditionalAmountDescription":"","CustomsValueAmount":{"Value":0,"CurrencyCode":""},"Items":[]}}},"ClientInfo":{"AccountCountryCode":"JO","AccountEntity":"AMM","AccountNumber":"20016","AccountPin":"331421","UserName":"reem@reem.com","Password":"123456789","Version":"v1.0"},"Transaction":{"Reference1":"1","Reference2":"","Reference3":"","Reference4":"","Reference5":""},"LabelInfo":{"ReportID":9737,"ReportType":"URL"}} WSDL USED https://ws.dev.aramex.net/ShippingAPI.V2/Shipping/Service_1_0.svc?wsdl REQUEST SENT WITH ZEEP PACKAGE client = Client(wsdl) response = client.service['CreateShipments'](**request_data) ``` -
Add static field to django-allauth
I have already seen this official documentation of django-allauth. Imagine that I am using djangorestframework for implementing registration based on both django user model and the django-allauth. Imagine that we have a static field named role. Based on users' preferences, they can have a different role. for example student, teacher and parent. For the django user model I have created an enum field which handled properly as below: class Profile(models.Model): class RolesChoice(models.TextChoices): LEARNER = 1, _('learner'), TEACHER = 2, _('teacher'), PARENT = 3, _('parent') user = models.OneToOneField( User, on_delete=models.CASCADE, related_name="profile", ) role = models.CharField( max_length=1, choices=RolesChoice.choices, default=RolesChoice.LEARNER, ) How can I do the same thing for django-allauth? Is there any way to add a static field to the table that it creates? How? -
Django models.Model class. models.CharField
This question might have been asked before ... but sorry i couldn't find it so that is why am asking i want to understand the title models.CharField() i understand that the we inherit the Model class from the module call models. but then why not the class Model.charfield() as the method or function of Model why models? which seams to me like a module and CharField seems like a class its seems to me we are accessing a class from the models module. example from django.db import models class Page(models.Model): title = models.CharField(max_length=60) permalink = models.CharField(max_length=12, unique=True) update_date = models.DateTimeField('Last Updates') bodytext = models.TextField('Page Content', blank=True) i appreciate your time :D -
How can fetch data in NUXT.JS on DRF
I tried NUXT and tried following the manual on his website. But now I'm stuck with the problem of fetching data from DJANGO. this my code. <template> <div> <ul v-for="product in products" :key="product.results.id"> <NuxtLink :to="`/${product.results.id}`"> <li>{{ product.results.id }}</li> </NuxtLink> </ul> </div> </template> <script> export default { async asyncData() { const products = await fetch( '***/product_api/api/v1/Product/?format=json' ).then((res) => res.json()) // .then(productmap => console.log(productmap.results[0].name)) return { products } } } </script> and my JSON { "count": 46786, "next": "***/product_api/api/v1/Product/?limit=100&offset=100", "previous": null, "results": [ { "id": 2, "catID": "TOO08", "catname": "เครื่องมือช่าง", "sku": "1690", "name": "เส้นเอ็น SL NO.50", "brand": "ระกา", "price": "40", "detail": "เส้นเอ็น SL NO.50", "imgurl1": "****", "imgurl2": "****", "productclick": "*****" }, I tried following the guide to the basics. But still don't understand Anyone have a way to solve this problem? I just want to do Dynamic Pages.https://nuxtjs.org/examples/routing-dynamic-pages -
Django Error: Field 'id' expected a number but got 'Action'
Error: Field 'id' expected a number but got 'Action'. I am getting this error when trying to submit a form. It works fine if i use the admnin page to add a post so the errror must be in the forms. models.py: class Genres(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Genres" ordering = ('name',) class Post(models.Model): genres = models.ManyToManyField(Genres, null=True, blank=True) forms.py: genre_choices = Genres.objects.all().values_list('name', 'name') genre_choices_list = [] for item in genre_choices: genre_choices_list.append(item) class NewPost(forms.ModelForm): genres = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'form_input_select_multi'}), choices=genre_choices_list, required=False) -
Django Filter Objects with Euclidean distance
Is there a way to convert the following Postgres query: SELECT a FROM test ORDER BY a <-> cube(array[0.5,0.5,0.5]) LIMIT 50; To a working Django Model query using the ORM? Perhaps using annotate() with that expression, then order_by()? -
For Django, how can I make a button that duplicates a form?
I am making some sort of financial calculator and I have no JavaScript experience. I want to add a button that would allow users to add another asset/amount field in the form. I also want the values to be inputted from the homepage. How would I go about doing this? this is my views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import Assets from .models import PortfolioScan, Item def home(request): if request.method == "POST": if request.POST.get("calculate"): form = Assets(request.POST) if form.is_valid(): t = form.cleaned_data['ticker'] a = form.cleaned_data['amount'] assets = PortfolioScan(ticker=t, amount=a) assets.save() return HttpResponseRedirect('/calculate/') elif request.POST.get("additem"): pass else: form = Assets() return render(request, "portfolioscan/home.html", {"form":form}) forms.py from django import forms class Assets(forms.Form): ticker = forms.CharField(label="ticker", max_length=100) amount = forms.IntegerField(label="amount", max_value=1000000, min_value=-1000000) models.py from django.db import models # Create your models here. class PortfolioScan(models.Model): ticker = models.CharField(max_length=100) amount = models.IntegerField() def __str__(self): return self.ticker def __int__(self): return self.amount class Item(models.Model): portfolio = models.ForeignKey(PortfolioScan, on_delete=models.CASCADE) stock = models.CharField(max_length=100) allocation = models.IntegerField() def __str__(self): return self.stock def __int__(self): return self.allocation home.html <div> <form method="post" action="#"> {% csrf_token %} {{form}} <button type="submit", name="additem", value="additem">Add Another</button> <button type="submit", name="calculate", value="calculate">Calculate</button> </form> </div> I have tried everything in my knowledge and have tried … -
django 3.1 multilanguage site breaks login
I have set up a django 3.1 site that uses 2 languages, English and German, and I use i18n_patterns in my urls.py. The problem is, in my views.py method, I never get a POST request, even though I specify method="POST" in my form. It always comes in as a GET request, and I cannot login. Somewhere along the way, the system changes my POST request into a GET request. urlpatterns = [] urlpatterns += i18n_patterns( path('{}/'.format(settings.DJANGO_ADMIN_URL), admin.site.urls), path('review/', include('review.urls')), path('anmelden_success/', views.anmelden_success, name='anmelden_success'), path('', views.site_login, name='site_login'), path('site_login/', views.site_login, name='site_login'), path('site_logout/', views.site_logout, name='site_logout'), ) I log in with this form, specifying method="POST": <form action="/site_login/" method="POST" id="login-form">{% csrf_token %} <label class="required" for="id_username">Benutzer:</label> <input type="text" name="username" autofocus required id="id_username"> <label class="required" for="id_password">Passwort:</label>&nbsp;<input type="password" name="password" required id="id_password"> <input type="hidden" name="next" value="/review/"> <label>&nbsp;</label><input type="submit" value="Anmelden"> </form> The request comes to my views.py method site_login: def site_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/anmelden_success') else: return HttpResponse("Sorry, you failed to login.") else: if request.user.is_authenticated: return redirect('/review') else: return render(request, 'registration/login.html') Since it somehow gets changed from a POST request to a GET request, my login fails, and I come straight … -
my edit function is not working where are my going wrong?
i am trying to make a edit function for my project but it not working it only updating my five of my variables that are in another table but the rest it isn't updating it - it only update the variables in my custom user model which are first_name,last_name,username and email - it doesnt update the variables in my admin model - where are my going wrong- any help will be appreciated - i am still new in django so excuse any mistakes this is my custom user model class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee")) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) this is my admin model class admin(models.Model): id = models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) Dob = models.DateField() Nationality = models.TextField() Address = models.TextField() Postcode = models.TextField() Telephone = models.TextField() Wage = models.TextField() Passportnumber = models.TextField() passportexpirydate = models.DateField() gender = models.CharField(max_length=255) profile_pic = models.FileField() kinname = models.TextField() kinrelation = models.TextField() kinaddress = models.TextField() kinphonenumber = models.TextField() kinemail = models.TextField() profile_pic = models.FileField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects = models.Manager() this is my edit function def edit_admin_save(request): if request.method!="POST": return HttpResponse("<h2> Method Not Allowed </h2>") else: admin_id = request.POST.get("admin_id") first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") email=request.POST.get("email") Dob=request.POST.get("Dob") Nationality=request.POST.get("Nationality") Address=request.POST.get("Address") Postcode=request.POST.get("Postcode") Telephone=request.POST.get("Telephone") Wage=request.POST.get("Wage") Passportnumber=request.POST.get("Passportnumber") passportexpirydate=request.POST.get("passportexpirydate") gender=request.POST.get("gender") kinname=request.POST.get("kinname") kinrelation=request.POST.get("kinrelation") kinaddress=request.POST.get("kinaddress") kinphonenumber=request.POST.get("kinphonenumber") kinemail=request.POST.get("kinemail") if request.FILES.get('profile_pic',False): profile_pic=request.FILES['profile_pic'] fs =FileSystemStorage() … -
How to configure a django model in such a way, that one model will only migrate to one specific database?
say I define a parameter "db_select" inside a "params" class in my model, and I want all migrations from this model to automatically route to that mentioned database. Similarly for other models with other db_select option to be automatically route to their respective database. How should I write my routers.py script ? I am using django 3.1.4 My Models.py: from django.db import models # Create your models here. class Project(models.Model): startDate=models.DateField() endDate=models.DateField(max_length=20) name=models.CharField(max_length=20) assignedTo=models.CharField(max_length=30) priority=models.IntegerField() class params: db_select = 'default' my Database settings: DATABASE_ROUTERS=('movieForm.dbrouters.myRouter',) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectInfo', 'USER': 'root', 'PASSWORD': '123@abc', }, 'movie': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'movieDB', 'USER': 'root', 'PASSWORD': '123@abc', } } -
Django-Compressor won't work in offline mode with custom S3 domain
I get the following error whenever a custom domain for the S3 endpoint is used. # WORKS AWS_S3_CUSTOM_DOMAIN = 'example.fra1.digitaloceanspaces.com/{}'.format(AWS_STORAGE_BUCKET_NAME) # DOES NOT WORK ⁉️ AWS_S3_CUSTOM_DOMAIN = 'cdn.example.com/{}'.format(AWS_STORAGE_BUCKET_NAME) CommandError: An error occurred during rendering /home/<user>/<app>/templates/public/index.html: 'https://cdn.example.com/storage/static/node_modules/nouislider/distribute/nouislider.min.css' isn't accessible via COMPRESS_URL ('https://example.fra1.digitaloceanspaces.com/storage/static/') and can't be compressed If I go to either url the file is accessible, hence its likely that the CDN is ok, URLs are correctly defined, CORS are fine too. Also without django-compressor subdomain delivery had been working fine, leading me to believe the issue is not with django-storages I've been trying for several hours and ultimately had to do a temporary fix by setting the AWS_S3_CUSTOM_DOMAIN to be the same as the AWS_S3_ENDPOINT_URL. However this is not ideal. Please see the implementation below. /requirements.txt Django==3.1.4 ... boto3~=1.16.46 botocore~=1.19.46 s3transfer~=0.3.3 ... django-storages~=1.11.1 django-compressor~=2.4 /config/settings.py ... # ========================================================== # DJANGO-STORAGES # ========================================================== if LOCALHOST_MODE: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), ] else: AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = 'storage' AWS_S3_ENDPOINT_URL = 'https://example.fra1.digitaloceanspaces.com' # WORKS ⚠️ AWS_S3_CUSTOM_DOMAIN = 'example.fra1.digitaloceanspaces.com/{}'.format(AWS_STORAGE_BUCKET_NAME) # DOES NOT WORK ⁉️ AWS_S3_CUSTOM_DOMAIN = 'cdn.example.com/{}'.format(AWS_STORAGE_BUCKET_NAME) AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = 'public-read' STATICFILES_DIRS = … -
Using Javascript in executing a Search by title for items in a Django Project
I am adding a Search functionality to my E-commerce Project using Javascript, I have followed a tutorial that explains that when writing the title in the search bar only the items with the same letter appears. In my project, it was working fine for basic HTML but I am trying to make it a little more complex to include a complete card with some details such as price, not just the title. Here is the model.py class Item(models.Model): title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) price = models.DecimalField(decimal_places=2, max_digits=100) discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now) Here is the views.py class ItemListView(ListView): model = Item paginate_by = 12 template_name = "store/product_list.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder) return context Here is the scripts.py <script> const data = '{{qs_json}}' const rdata = JSON.parse(data.replace(/&quot;/g, '"')) console.log(rdata) const input = document.getElementById('search_here') console.log(input) let filteredArr = [] input.addEventListener('keyup', (e)=>{ box.innerHTML = "" filteredArr = rdata.filter(store=> store['title'].includes(e.target.value)) console.log(filteredArr) if (filteredArr.length > 0){ filteredArr.map(store=>{ box.innerHTML += `<b>${store['title']}</b><br>` }) } else { box.innerHTML = "<b>No results found...</b>" } }) </script> Here is the template.html <input id="search_here" class="mb-2 form-control" placeholder="Type to search..."> <!--Card--> <div id="box" class='row card-group'> {% for item …