Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello All, I'm new in learning in Django and getting error when I try to call the webpage. Please refer to the below code
def index(request): ob=Com1.objects.all() return render(request,'index.html',{'ob':ob}) def sports(request,name): cat=Categ.objects.filter(name=name) com=Com1.objects.filter(categ_id=cat[0].id) return render(request,'sports.html') -
Django Tenant Schemas "argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks"
I faced the same issue as here but was unable to fix it from the answer provided with the question. I tried adding tenant_schemas to the end of INSTALLED_APPS like this INSTALLED_APPS = SHARED_APPS + TENANT_APPS + INSTALLED_APPS + ['tenant_schemas'] but this didn't worked. I moved INSTALLED_APPS to the bottom of the settings file and this also didn't worked. The only option left for me is to copy the entire tenant_schemas library, fix it using the changes provided in the pull request in the answer, and connect it with the project as an app, which is a terrible way to proceed. If there is an example for the solution provided in the above answer, or a better solution in itself, please let me know. TRACEBACK - Traceback (most recent call last): File "E:\PycharmProjects\uniuno\uniuno\manage.py", line 22, in <module> main() File "E:\PycharmProjects\uniuno\uniuno\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 322, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 296, in create_parser self.add_arguments(parser) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\tenant_schemas\management\commands\migrate_schemas.py", line 20, in add_arguments command.add_arguments(parser) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 26, in add_arguments parser.add_argument( File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\argparse.py", line 1434, in add_argument return self._add_action(action) File "C:\Users\Ishu\AppData\Local\Programs\Python\Python39\lib\argparse.py", … -
Django smtplib.SMTPRecipientsRefused: Recipient address rejected: User unknown in virtual mailbox table
I have a django app that requires users to create an account before they are able to use the service. Upon registration, the user is sent an email with a link to activate their account. Lately however, I have noticed that when someone creates an account with slightly more unusual email addresses than gmail.com, an error is being thrown that the user is 'unknown in the virtual mailbox table. This used to not be the case, but i dont understand what has changed. Full error below (with email address anonymized): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 881, in sendmail raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'testing@xxxx.com': (550, b'5.1.1 <testing@xxxx.com>: Recipient address rejected: User unknown in virtual mailbox table')} Do you guys have an idea? Thanks! -
Is there a way of defining variables in HTML files with Django?
I'm working on a Django project that has a "random page" link that leads the user to (you guessed it) a random page of the website. I made a function in views.py that returns randomly the name of a page: def randomPage(request): fileList = util.list_entries() num = random.randint(0,len(fileList)-1) fileName = fileList[num] return fileName And I was wondering if there was a way of passing the result to a variable in the HTML file where the link is, like this: {% random = views.randomPage() %} <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <div> <a href="{{random}}/">Random Page</a> </div> {% block nav %} {% endblock %} </div> </div> What I'm trying to achieve is to lead the user to an url such as "/CSS" or "/HTML" (both are pages of the website) -
How to create model fields in a loop?
I am creating a project in Django where in my 'Myapp' I have two models in models.py. I am trying to achieve the objects of model_1 to be the field of my model_2. The example of my code and what I have tried has been shown below:- Model_1 in models.py class Skills(models.Model): skill_name = models.CharField(max_length=200, blank= False) Model_2 in models.py (What I have tried) class Resources(models.Model): pass for skill in Skills.objects.all(): Resources.add_to_class(skill, models.CharField(max_length=200)) the error that I am getting NameError: name 'Resources' is not defined Can anyone provide a better solution to my problem that can create a model_2(Resources) that will have fields skill_1, skill_2,...,skill_3 from my model_1(Skills) -
Python/Django how to stop duplicate entry in list
I have been struggling with a hard puzzle :), but I can't seem to figure it out. It is probably something easy but I don't see it. Maybe you guys can help me out. The problem is that a product shows a duplicate in the cart, but I want to stop that if 2 products in the cart are a 1+1=1 deal/campaign. The problem: First item of the cart reaches the elif not combi_sets and product.deal_type: and if product.deal_type: statements, it adds the product to the items and also sets it as an entry for a combi product. Thats probably why it is a duplicate? The case: Check before adding the product to the items if the product is already matched in the combi_sets list and skip adding that in the items. Here I loop through the cart items and check if there is a product with deal.type: combi_products = [] combi_sets = [] for i in cart: try: cartitems += cart[i]['quantity'] product = Product.objects.get(product_id=i) total = (product.price * cart[i]['quantity']) order['get_original_price'] += total order['get_cart_items'] += cart[i]['quantity'] if product.deal_type: # deal.type is combi, combi applies when admin creates a deal of 1+1 product for one price product_id = product.product_id combi_products.append(product_id) # … -
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()?