Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django templates url - differentiate between same url names
in my application I've got a view called download_document which works fine using {% url 'download_document' some_id %} . Installing a 3rd party app into the virtual environment cause trouble because this app has also the download_document view (also accepting one ID parameter) with the same urlname. If I'd like to use both with this name, can I somehow make the difference between them? For instance using both cases in the same template file? Python: 2.7 Django: 1.11.16 Debian . -
Two different table (nested loop?) in django template
Could you help me, please? I have two tables and I want to display different data from them on the template, here is my code: models.py: from django.db import models from suppliers.models import Company class Product(models.Model): product_name = models.CharField(max_length=200, blank=True, null=True) product_ean = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return f'{self.product_name} {self.product_ean}' class Product_company(models.Model): product_name = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) company_name = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL) product_price = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return f'{self.product_name} {self.company_name}' views.py: from .models import * def products_list(request): product = Product.objects.all() product_company = Product_company.objects.all() context = { 'product': product, 'product_company': product_company, } return render(request, 'products/products_list.html', context) products_list.html: <table class="table"> <thead> <tr> <th>Termék neve</th> <th>Termék EAN száma</th> <th>Kihez tartozik?</th> <th>Termék ára</th> <th>Műveletek</th> </tr> </thead> <tbody> {% for i in product %} {% for x in i.product_company_set.all %} <tr> <td>{{ i.product_name }}</a></td> <td>{{ i.product_ean }}</td> <td>{{ x.company_is_registered }}</td> <td>{{ i.company_name }}</td> <td>{{ i.company_give_list }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> Unfortunately, nothing display in the Product_company table, what could be the problem? Thank you! -
Should you access cleaned_data directly in views or have a method belonging to the given form that handles working with cleaned_data?
I started experimenting with django few afternoons ago and I have an app with a custom form in which I authenticate user the following way: if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] ... work with username and password ... However, I also read on some webpage (witch I no longer have in my search history :/) that you should not access cleaned_data like that and that it is better to hide using of cleaned_data to a custom method. And do something like this: if form.is_valid(): form.process() I don't think that it should matter much. Nonetheless, I'm curious which way is more preferable and django-like. Thanks! -
Django Improper URL NoReverseMatch
URL urlpatterns = [ #PAPER PROJECTS path('create-paper-project/', PTCreateView.as_view(), name='pt-create'), path('list-paper-projects/', PTListView.as_view(), name='pt-list'), path('pproj<str:pk>/', PTDetailView.as_view(), name='pt-detail'), path('pprojp<str:pk>/update/', PTUpdateView.as_view(), name='pt-update'), path('pproj<str:pk>/delete/', PTDeleteView.as_view(), name='pt-delete'), ] VIEWS class PTCreateView(generic.CreateView): model = PaperTool template_name = 'papertools/pt_create.html' success_url = '/paper-tools/list-paper-projects/' fields = ['title'] class PTListView(generic.ListView): model = PaperTool template_name = 'papertools/pt_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class PTDetailView(generic.DetailView): model = PaperTool template_name = 'papertools/pt_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class PTUpdateView(generic.UpdateView): model = PaperTool fields = ['title'] template_name = 'papertools/pt_update.html' success_url = reverse_lazy('paper:pt-detail', kwargs={'pk': model.pk}) class PTDeleteView(generic.DeleteView): model = PaperTool template_name = 'papertools/pt_delete.html' success_url = reverse_lazy('paper:pt-detail') HTML <a class="nav-link" href="{% url 'pt-detail' object_list.paper.pk %}"> Paper Project Home </a> I continuously get the following error: "Reverse for 'pt-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['paper\-tools/pproj(?P[^/]+)/$']" In the HTML portion if I replace the "object_list.paper.pk" portion with just a pk (say 6). This works just fine. I do not understand why this is giving off an error. There seem to be similar problems on StackOverflow but none exactly like this. -
Save data from form into 2 models using .save()
I'm creating a registration and login app with Django. I get the data using a form and POST. I want to save the form data into two Django models: class Customer(models.Model): username = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name And the Django User model. forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import * class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Registration View.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) form2 = Customer print(form) if form.is_valid(): form.save() user = form.cleaned_data.get('username') name = form.cleaned_data.get('username') email = form.cleaned_data.get('email') form2.save(user, name, email) messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request, 'login/register.html', context) Now my question is, how do I save the form data into the user models AND save the data(user, name, email) into the Customers model? I tried using form2.save(user, name, email) but i get an error message: 'str' object has no attribute '_meta' Thank for any help! -
The view ecommerceapp.views.checkout didn't return an HttpResponse object. It returned None instead
I'm trying to build an ecommerce app and I'm building a form that when a particular payment option is clicked, the url is pointed to a particular one. But whenever I try to run the website, this error pops out: The view ecommerceapp.views.checkout didn't return an HttpResponse object. It returned None instead. Views.ps def checkout(request): def get(self, *args, **kwargs): if request.method == 'POST': form = checkoutForm(request.POST) if form.is_valid(): # here is the place where your find the values in: if form.cleaned_data['payment_option'] == 'Stripe': return redirect('core:payment', payment_option='Stripe') elif form.cleaned_data['payment_option'] == 'Paypal': return redirect('core:payment', payment_option='Paypal') return redirect(reverse('core:index')) else: form = checkoutForm() return render(request, 'ecommerceapp/checkout.html', {'form': form,'items': OrderItem.objects.all(), 'orders': Order.objects.all()}) -
Celery+Django+RabbitMQ - I believe tasks will queue but do not execute
Following this: https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html I have a project called 'ursa' and some apps one of which is called 'core_app'. Problem: I start the task: # ./manage.py shell frPython 3.8.7 (default, Dec 22 2020, 18:46:25) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from core_app.tasks import update_gsb_status >>> update_gsb_status.apply_async(args=['https://somedomain.tld/dir/dir/file.html']) <AsyncResult: 85625fec-beea-48c0-9c7e-c9a3bd9caa2e> Nothing happens in the celery worker: [2021-02-02 12:26:00,102: INFO/MainProcess] Connected to amqp://user:**@rabbitmq:5672// [2021-02-02 12:26:00,115: INFO/MainProcess] mingle: searching for neighbors [2021-02-02 12:26:01,146: INFO/MainProcess] mingle: all alone [2021-02-02 12:26:01,168: INFO/MainProcess] celery@77267d507aec ready. ...nothing else This is the second day of banging my head against the wall on this. Notes: I am using RabbitMQ for celery but I'm also using Redis for caching. Is celery adding my tasks to the Redis queue? How can I tell? How do I not do that? If I change the ursa/ursa/settings.py file to use BROKER_URL instead of CELERY_BROKER_URL then the celery worker uses the default transport instead of the correct URL. I've also tried using the @app.task decorator instead of @shared_task by importing the celery app in ursa/core_app/tasks.py via from ursa.celery import app but the same result happens - nothing. I've also checked the celery worker to see what tasks are … -
Cannot query field \"serviceTechnician\" on type \"WorkOrderType\"
When querying for all workorders I can't access the service_technician assigned to the workorder. { "errors": [ { "message": "Cannot query field \"serviceTechnician\" on type \"WorkOrderType\".", "locations": [ { "line": 21, "column": 5 } ] } ] } This query works if you remove serviceTechnician: query workOrders { workorders { id, sameAsCustomerAddress, relatedCustomer {id, customerName, customerCity {id, locationCity}, customerZip}, serviceZip serviceCity {id, locationCity} serviceTechnician } } UserType and WorkOrderType: class UserType(UserNode): class Meta: model = get_user_model() filter_fields = app_settings.USER_NODE_FILTER_FIELDS exclude = app_settings.USER_NODE_EXCLUDE_FIELDS interfaces = (graphene.relay.Node,) skip_registry = True pk = graphene.Int() archived = graphene.Boolean() verified = graphene.Boolean() secondary_email = graphene.String() class WorkOrderType(DjangoObjectType): class Meta: model = WorkOrder fields = ('id', 'same_as_customer_address', 'service_address', 'service_city', 'service_state', 'service_zip', 'service_unit_number', 'service_technician', 'status', 'description', 'computer_brand_type', 'computer_password', 'related_customer') WorkOrderInput class WorkOrderInput(graphene.InputObjectType): id = graphene.ID() same_as_customer_address = graphene.Boolean() service_address = graphene.String() service_city = LocationInput() service_state = graphene.String() service_zip = graphene.String() service_unit_number = graphene.String() service_technician = graphene.InputField(UserInput) status = graphene.String() description = graphene.String() computer_brand_type = graphene.String() computer_password = graphene.String() related_customer = CustomerInput() Query resolve_workorder: def resolve_workorder(self, info, **kwargs): id = kwargs.get('id') if id is not None: return WorkOrder.objects.get(pk=id) return None I really have no clue why I'm unable to query this field, I have defined it in my … -
VS Code does not see sqlite3
I am building a website using Django and wanted to inspect my database using command: python manage.py dbshell however surprisingly I got CommandError: You appear not to have the 'sqlite3' program installed or on your path. I am using VS Code for my project and got the error in command prompt terminal of VS Code. I am saying surprisingly because I have already created my models before with commands python manage.py makemigrations and python manage.py migrate. These commands also don't work right now. It is impossible that sqlite3 is not installed because python installs it inherently. I assume PATH variable is also not an issue as I added it and can run sqlite3 outside of VS Code if I open command prompt from the start menu of windows. What can be the reason of this corruption/problem and how can I fix it ? This is screenshot of start menu command prompt : This is screenshot of VS Code : -
All records displayed in many to many django app
Here my models: django_zoom2/meetings/models.py from django.db import models from participants.models import Participant class Meeting(models.Model): topic = models.CharField(max_length=100) uuid = models.CharField(max_length=100, default='xxxx') participants = models.ManyToManyField(Participant) def __str__(self): return self.topic django_zoom2/participants/models.py from django.db import models # from meetings.models import Meeting class Participant(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) def __str__(self): return self.email ..and the admin views: django_zoom2/meetings/admin.py from django.contrib import admin from .models import Meeting @admin.register(Meeting) class MeetingAdmin(admin.ModelAdmin): list_display = ['topic', 'uuid'] django_zoom2/meetings/admin.py from django.contrib import admin from .models import Participant @admin.register(Participant) class ParticipantAdmin(admin.ModelAdmin): list_display = ['name', 'email'] I have a single association with the meeting blarg: >>> from meetings.models import Meeting >>> m= Meeting.objects.get(id=1) >>> m <Meeting: blarg> >>> m.participants.all() <QuerySet [<Participant: molly@myorg.org>]> ...but in the view here is what I see: Why am I seeing all the participants email addresses in this view? I only want to see the associated email addresses; in this case, there should be one. Molly. -
Django / GeoDjango / PostGis - Filter FeatureCollection
Currently i have a very basic django model containing a PointField: from django.contrib.gis.db import models from django.utils.translation import gettext_lazy as _ from api.models import AbstractModel class SampleEntity(AbstractModel): point = models.PointField(_('point')) My goal is to filter all rows and check if the point is in a certain polygon... In order to create a polygon i receive the following payload (FeatureCollection): { "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "source": "© GeoBasis-DE / BKG 2013", "features": [{ "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [10.453980128926366, 47.55557895879648], [10.438876535127962, 47.52349211089603], [10.44055084477551, 47.5135694350795], [10.431323512106337, 47.5036776164676], [10.442767953986108, 47.4846168990274], [10.45131095387671, 47.485685093946636], [10.463220692620368, 47.48277492286606], [10.468022327337152, 47.47691846929882], etc.. ] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [9.617342617593987, 47.568803310179476], [9.628007474077956, 47.570911279233016], [9.628870213746309, 47.56638028461108], [9.638605938479984, 47.56693417152559], [9.653552559008789, 47.55698746615904], [9.679038885003902, 47.55702134414172], [9.682804387548277, 47.55244003193477], [9.675623645853232, 47.54522412435771], etc.. ] ] } }] } Next i need to somehow convert my FeatureCollection to a valid "GeoDjango" Polygon in order to filter in the database: geoms = [] for feature in payload["features"]: geoms.append(GEOSGeometry(str(feature["geometry"]))) geometry = GeometryCollection(geoms) rows = SampleEntity.objects.filter(point__within=geometry) print(rows) # <- Error Raises: django.db.utils.InternalError: Relate Operation called with a LWGEOMCOLLECTION type. This is unsupported. HINT: Change argument 1: … -
django ValueError : attribute has no file associated with it
I have an annoying error that I'm not able to fix it. If the article has all 4 photos it's ok, if it doesn't have all 4 photos I got ValueError. I tried to solve this with an if statement but it seems it doesn't work. Any tips? html <div class="other"> {% if object.photo_1 %} <div class="list-one-images"> <img class="hover-shadow cursor" onclick="openModal();currentSlide(1)" src = "{{ object.photo_1.url }}"> </div> {% endif %} {% if object.photo_2 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(2)" class="hover-shadow cursor" src = "{{ object.photo_2.url }}"> </div> {% endif %} {% if object.photo_3 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(3)" class="hover-shadow cursor"src = "{{ object.photo_3.url }}"> </div> {% endif %} {% if object.photo_4 %} <div class="list-one-images"> <img onclick="openModal();currentSlide(4)" class="hover-shadow cursor" src = "{{ object.photo_4.url }}"> </div> {% endif %} </div> model: class Oglas(models.Model): agent = models.ForeignKey(Agent, on_delete = models.DO_NOTHING) title = models.CharField(max_length=120) address = models.CharField(max_length = 120) area = models.CharField(max_length=120) description = models.TextField(blank = True) price = models.IntegerField() bedrooms = models.DecimalField(max_digits=2, decimal_places=1) bathrooms = models.DecimalField(max_digits=2, decimal_places=1, blank = True, null = True) garage = models.IntegerField(default = 0) sqft = models.IntegerField() kategorii = (('prodava', 'prodava'),('iznajmuva','iznajmuva')) kategorija = models.CharField(max_length = 10, choices= kategorii, null = True) lot_size = models.DecimalField(max_digits=5, decimal_places=1) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') … -
How to solve 'module' object is not iterable in django
I have created a Django application and initially the code worked perfectly but when I restarted the development server I started having 'module' object not iterable exception. This is my code views.py import datetime from django.contrib import messages from django.shortcuts import render from forms.forms import * from django.core.mail import send_mail from django.http import HttpResponse from patients.models import * def doctor_view(request, id): patients = Patients.objects.get(id=id) if request.method == "POST": form = DoctorForm(request.POST) if form.is_valid(): f = form.save(commit=False) date = datetime.datetime.now() f.date_seen = date f.save() messages.info(request, 'patient profile was successfully updated !!!') else: form = DoctorForm(instance=patients) date = datetime.datetime.now() return render(request, 'doctors/templates/patient_registration.html', {'form': form, 'title': 'Patient Treatment', 'patients': patients, 'date': date, 'messages': messages}) ``` urls.py from django.urls import path from . import views urlpatterns = [ path('<int:id>/', views.doctor_view, name='doctor-views'), ]``` Exception Traceback Internal Server Error: /doctor/1/ Traceback (most recent call last): File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\SERU\Desktop\School Projects\DAS_project\doctors\views.py", line 42, in doctor_view {'form': form, 'title': 'Patient Treatment', 'patients': patients, 'date': date, 'messages': messages}) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\SERU\Desktop\School Projects\DAS_project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return … -
Generic detail view PostDetailsText must be called with either an object pk or a slug in the URLconf
I am stuck trying to figure out how to fix this error. I'm trying to list all available categories and to display post a single overview. I know what the error is referring to (path), but I don't understand how to fix it. Here is my main url.py file urlpatterns = [ path('', PostDetailsText.as_view(), name='post_more_details'), ] These are my views for lisitng and details: class CategoryListing(TemplateResponseMixin, View): model = Post template_name = 'publications/posts/listing_posts.html' def get(self, request, category=None): categories = Category.objects.annotate(total_posts=Count('posts')) posts = Post.objects.annotate(total_modules=Count('modules')) if category: category = get_object_or_404(Category, slug=category) posts = posts.filter(category=category) return self.render_to_response({'categories': categories, 'category': category, 'posts': posts}) class PostDetailsText(DetailView): model = Post template_name = 'publications/posts/posts_details.html' The urls of the app: urlpatterns = [ path('category/<slug:category>/', views.CategoryListing.as_view(), name='categories_listing'), path('<slug:slug>/', views.PostDetailsText.as_view(), name='post_details'), ] This is how it looks like my html for listing the items: <div class="contents"> <h3>Categories</h3> <ul id="modules"> <li {% if not category %}class="selected"{% endif %}> <a href="{% url 'post_more_details' %}">All</a> </li> {% for s in categories %} <li {% if category == s %}class="selected"{% endif %}> <a href="{% url 'categories_listing' s.slug %}"> {{ s.subject }} <br><span>{{ s.total_posts }} posts</span> </a> </li> {% endfor %} </ul> </div> <div class="module"> {% for post in posts %} {% with category=post.category %} … -
Webpack configuration for react and django app
I am planning to make a boilerplate in GitHub between React and Django To facilitate me later When I start a project I chose the connection method React as Django app django-admin startapp frontend The problem I am facing now is that I am using the Django templates. I cannot split packages using wepback because there must be {load static} {static ''index.js"} However, I cannot use Splitchuncks in configuring a webpack or HTML plugin to insert script tags into HTML. The entire code must be inside one js file and that too with CSS webpack.config.js const path = require("path"); const webpack = require("webpack"); // const TerserPlugin = require('terser-webpack-plugin'); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.css$/, use: [ devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", ], }, { test: /\.(ttf|eot|woff|woff2|jpg|jpeg|png|gif|mp3|svg|ico)$/, loader: "file-loader", options: { outputPath: path.resolve(__dirname, "./static/images"), }, }, ], }, optimization: { minimize: true, // splitChunks: { // chunks: 'all', // name: false, // }, }, plugins: [ new HtmlWebpackPlugin( Object.assign( {}, … -
Django- update a DateField model entry to be a string as a default
I have a function in my Django model: def add_default_date This function, if called from the view, checks to see if publish_date is None and if it is, I'd like to change publish_date to be text: "Date Needed". However right now when I do this I get an error: "'Date Needed' value has an invalid date format. It must be in YYYY-MM-DD format.". It appear that I'm trying to assign a string to a DateField but it's not working. Is there anyway to do this? Models.py: class Byte(models.Model): """Model for databyte content.""" publish_date = models.DateField(blank=True, null=True) def add_default_date(self): if self.publish_date is None: self.publish_date = "Date Needed" Views.py: bytes = Byte.objects.order_by( F('publish_date').desc(nulls_last=True) ) for b in bytes: Byte.add_default_date(b) b.save() -
Curl command doesn't work in config file on AWS
I have a Django web application that is deployed to AWS elastic beanstalk (Python 3.7 running on 64bit Amazon Linux 2/3.1.3). I am trying to run the following config file files: "/usr/local/bin/cron_tab.sh": mode: "000755" owner: root group: root content: | #!/bin/bash exec &>> /tmp/cron_tab_log.txt date > /tmp/date source /var/app/venv/staging-LQM1lest/bin/activate cd /var/app/current python manage.py crontab add exit 0 container_commands: cron_tab: command: "curl /usr/local/bin/cron_tab.sh | bash" This file placed in the .ebextentions folder. All other config files are working properly. However, this one is not working. Also, I have tried to run the container_commands code manually on SSH and it gives output such as below. curl: (3) <url> malformed I also checked the /tmp folder but there is no cron_tab_log.txt. I checked /usr/local/bin the cron_tab.sh is located there. I just want this Django-crontab run after the deploy and it doesn't work. How can I handle this issue? -
upgrade django2 to 3 DigitalOcean droplets missing css files
I just install fresh image of django from DigitalOcean droplets marketplace and its work perfectly but its version 2 so I try to upgrade it to 3 and everything went fine except admin page missing 2 file [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.css, line 0) [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.js, line 0) -
Django user model custom fields names
How to rename fields of the user model? I want to rename the fields first_name to firstName, last_name to lastName with AbstractUser class User(AbstractUser): email = models.EmailField('email address',unique=True) firstName = models.CharField("First Name", max_length=150) lastName = models.CharField("Last Name", max_length=150) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'username', 'firstName', 'lastName', ] The above code works, but it does not rename the fields what it does is add the fields firstName and lastName Any ideas or suggestions? -
how to create enable registered users to create their own staff user in django
How to enable registered users on my website to create their own staff users ? Their staff user should be able to login in registered users dashboard . I am very new to coding so please help , how should i move forward ? -
React - Can't get my Axios to POST to my backend URL? Backend URL's work just fine via tests
I'm testing out a new user registration form. I've used this exact same form set-up for my login page, it works just fine, users can login with their credentials and connect to the backend. However, this time when I try to reflect the same method onto my registration form, I'm getting a forbidden 403 error from django. I've tested out the URL path using Postman and Swagger, they both work fine (without headers). Which is why you see the 201 white response in my terminal above. The 403 only occurs when I try to register via my React Frontend app. Here is my Axios post request: const onSubmit = (data, e) => { console.log(data); axiosInstance .post(`user/register/`, { email: data.email, username: data.username, first_name: data.first_name, last_name: data.last_name, password: data.password, subscribed: data.subscribed, }) .then((res) => { history.push('/login'); console.log(res); console.log(res.data); }); }; Here is the code of my React registration form. export default function SignUp() { const { register, control, errors: fieldsErrors, handleSubmit } = useForm() const history = useHistory(); const initialFormData = Object.freeze({ email: '', username: '', first_name: '', last_name: '', password: '', subscribed: false, }); const [formData, updateFormData] = useState(initialFormData); const handleChange = (e) => { updateFormData({ ...formData, ...e, // Trimming any … -
How can you return a value according to the radio field selected?
I'm making a checkout page with radio selection to choose from stripe and paypal. When the user selects Stripe it should direct to the Stripe checkout and when the user selects Paypal, it should go to the paypal one. HTML: <form method="POST" class="post-form"> {% csrf_token %} <div class="col-md-12"> {% for value, name in form.fields.payment_option.choices %} <div class="radio"> <label><input type="radio" name=paymentMethod id="{{ name.id }}"class="mr-2">{{ name }}</label> </div> {% endfor %} </div> </div> <div class="form-group"> <div class="col-md-12"> <div class="checkbox"> <label><input type="checkbox" value="" class="mr-2"> I have read and accept the terms and conditions</label> </div> </div> </div> {% if name in form.fields.payment_option.choices == stripe %} <button type="submit" class="btn btn-primary py-3 px-4" action="{% url '' %}">Place an order</button> {% endif %} </form> urls.py: urlpatterns = [ path('', views.index, name='index'), path('shop/', views.shop, name="shop"), path('about/', views.about, name="about"), path('blog/', views.blog, name="blog"), path('contact/', views.contact, name="contact"), path('checkout/', views.checkout, name="checkout"), path('cart/', views.cart, name="cart"), path('product-single/<slug:slug>/', views.productpage, name="productpage"), path('add-to-cart/<slug:slug>/', views.add_to_cart, name="addtocart"), path('remove-from-cart/<slug:slug>/', views.remove_from_cart, name="removefromcart"), path('payment/<payment_option>/', PaymentView.as_view(), name='payment') ] -
Django, google app engine, bucket No 'Access-Control-Allow-Origin'
Hello i've a problem that i can't solve. Now i've a simple django project and i'm close to finishing. a few days ago i upload my static files and media files to google cloud sql-bucket. Normally everything was fine for media files but when i upload static files something started to happens. Here some of error messages(30+): Access to script at 'https://storage.googleapis.com/denka_metal_static_bucket/debug_toolbar/js/toolbar.js' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/denka_metal_static_bucket/debug_toolbar/js/toolbar.js net::ERR_FAILED Access to font at 'https://storage.googleapis.com/denka_metal_static_bucket/Fonts/jost/Jost-500-Medium.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Also normally django wasn't accept my static files because of they are in somewhere else but i loaded django-cors-headers (i don't know is it full name.) and django accept most of css docs. Here is my settings.py (I cut some parts when i paste here): ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'honeypot', 'ckeditor', 'ckeditor_uploader', 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'Product.apps.ProductConfig', 'captcha', 'admin_honeypot', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ( 'http://127.0.0.1:8000', 'http://localhost:8000', 'https://storage.googleapis.com', 'https://googleapis.com', ) CSRF_TRUSTED_ORIGINS = [ … -
Class based views
I'm experimenting with class based views as I've not worked with them yet. I'm also pretty new to Django. I'm having trouble correctly using slug or pk and setting up my URL's in my products app. My Project level urls.py: from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls', namespace='home')), path('products/', include('products.urls')), path('checkout/', include('checkout.urls')), ] urls.py(product app): from django.urls import path from .views import ItemDetailView urlpatterns = [ path('', ItemDetailView.as_view(), name='products'), ] views.py(products app): from django.shortcuts import render from django.views.generic import DetailView from home.models import Item def products(request): context = { 'items': Item.objects.all() } return render(request, "products/products.html", context) class ItemDetailView(DetailView): model = Item template_name = "products/product.html" I have tried adding <slug>/ to the products url pattern but that doesn't work. I'm pretty sure I need to adjust my url's but I'm not sure how. -
don't show checkbox type boolean on models.py
i have models item filed itm_stop: class item(models.Model): itm_stop=models.BooleanField(verbose_name='item stop',default=False) in file forms.py: from django import forms,modelsForm class itemsForm(modelsForm.Form): class Meta: model =item fields = "__all__" in file views.py : from .forms import itemsForm def items_create(request): if request.method == 'POST': form = itemsForm(request.POST, request.FILES) else: form = itemsForm() return render(request, 'items/items.html',{"items" :form}) in file Templates item.html: {% load widget_tweaks %} {% for field in items %} <!-- append to an attribute --> <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} When I do the presentation, I cannot display the checkbox, and it appears as an empty box on the page, and I did not find the reason for that