Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django + Html: Is it possible to display the initial value in a <select> before change is made so they can see initial
Django + Html: Is it possible to display the initial value in a before change is made, so that if user dont want to update they can leave it as it is. So current i have not choice but to do this in my account update page. Is there a way to make it such that i can query the initial date of birth so i dont have to reselect my date of birth everytime i update other fields in the same form. Thanks views.py def edit_account_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) if account.pk != request.user.pk: return HttpResponse("You cannot edit someone elses profile.") context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = AccountUpdateForm(request.POST, instance=request.user, initial={ "id": account.pk, "date_of_birth": account.date_of_birth, } ) context['form'] = form else: form = AccountUpdateForm( initial={ "id": account.pk, "date_of_birth": account.date_of_birth, } ) context['form'] = form context['DATA_UPLOAD_MAX_MEMORY_SIZE'] = settings.DATA_UPLOAD_MAX_MEMORY_SIZE return render(request, "account/edit_account.html", context) forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'date_of_birth') html <h6 class="mt-4 field-heading">Date of Birth</h6> <input type="date" name="date_of_birth" id="input_dateofbirth" class="form-control" placeholder="Date of birth" required required value="{{form.initial.date_of_birth}}"> <p >{{form.initial.username}}'s Birthday: {{form.initial.date_of_birth}}</p> <p style="color: red;">Reselect your Birthday date again during update … -
Difficulty accessing and working with Django models/QuerySets
My goal is to pull ship data once I pick the ship number but I have no idea how. Here is my model setup from django.db import models from django.contrib.auth.models import User class Hull (models.Model): hull = models.CharField(max_length = 33, ) def __str__(self): return self.hull class Hull_Spec(models.Model): ship = models.ForeignKey(Hull, on_delete=models.CASCADE) speed = models.FloatField() depth = models.FloatField() remarks = models.CharField(max_length =300) def __many_fields_simple_array__(self): return [self.remarks, self.depth, self.speed] Here is what I try starting data hull = SS1 depth = 10 speed = 10 remarks = 'remarks' from main.models import Hull. Hull_Spec hull = Hull.objects.get(hull = 'SS2') specs = hull.hull_spec_set.all() #which returns <QuerySet [<Hull_Spec: Hull_Spec object (2)>]> This is where I get stuck. I can get all of the information if I use the id but I have no idea how to retrieve a spec list's id unless I retrieve it from the terminal as shown above. Is there another way I can retrieve the data from the queryset without having to use get(id =) since I know already which ship this spec data corresponds to already? -
Why is Django authentication is now working for AbstractUser
So I have these Django models in the users app, and I have added AUTH_USER_MODEL = 'users.User' to settings.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) is_hub_manager = models.BooleanField(default=False) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' I also created an authenetication endpoint using Django rest framework. Surprisingly when I authenticate the admin everything works well. When I create a supplier and try to authenticate them. They always return invalid credentials. Here are my API views from rest_framework.generics import GenericAPIView from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status from django.conf import settings from django.contrib import auth import jwt class LoginView(GenericAPIView): serializer_class = UserSerializer def post(self, request): data = request.data username = data.get('username', '') password = data.get('password', '') user = auth.authenticate(username=username, password=password) if user: auth_token = jwt.encode({'username': user.username}, settings.JWT_SECRET_KEY) serializer = UserSerializer(user) data = {'user': serializer.data, 'token': auth_token} return Response(data, status=status.HTTP_200_OK) # SEND RES return Response({'detail': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) What could I be doing wrong? -
Bootstrap modal to confirm deletion
When I loop over my images I have an icon that you can click to delete the image. Instead I'd like to have a modal pop up to confirm the deletion. The only problem is I don't want to repeate the code for the modal for each image. I need a way to pass the image id to the modal. I was thinking I could pass the id in through an onClick but I'm not sure that will work with the Bootstrap modal. Here's how I'm currently deleting: {% for image in images %} <img src="{{image.image.url}}"> <form method="POST" action="{% url 'products:delete_image> {% csrf_token %} <button type="submit" rel="tooltip" title="Remove"> <i class="material-icons">close</i> </button> </form> {% endfor %} Here's the modal code I'd like to integrate <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div>