Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get selected attributes as a serialized representation in DRF?
When I serialize data using this statement: serializer = serializers.MySerializer(members, many=True) return Response(serializer.data) It will return a list of serialized data as a response. But if I want to print only some attributes as a serialized representation,not all attributes, how to do that? -
why do I get such an error? if on ubuntu/apache in the OpenSSH client all this works
module 'clr' has no attribute 'AddReference' Traceback (most recent call last): File "/home/djangoexample4/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/djangoexample4/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/djangoexample4/mainapp/views.py", line 135, in index clr.AddReference('/home/djangoexample4/btclinux2/MyLibraryName/bin/Debug/net7.0/ubuntu.22.04-x64/MyLibraryName.dll') Exception Type: AttributeError at / Exception Value: module 'clr' has no attribute 'AddReference' in openSSH client all work it: monop -r /home/djangoexample4/btclinux2/MyLibraryName/bin/Debug/net7.0/ubuntu.22.04-x64/MyLibraryName.dll Assembly Information: MyLibraryName Version=1.0.0.0 Culture=neutral PublicKeyToken=null MyLibraryName.Class1 Total: 1 types. namespace MyLibraryName{ public class Class1 { public int method1() { return 777; } } } python3 >>>import clr >>>clr.AddReference('/home/djangoexample4/btclinux2/MyLibraryName/bin/Debug/net7.0/ubuntu.22.04-x64/MyLibraryName.dll') >>>from MyLibraryName import Class1 >>>variable = Class1().method1() >>>print (variable) 777 in openSSH client all work it: in django website no: pip uninstall clr pip uninstall pythonnet pip install pythonnet module 'clr' has no attribute 'AddReference' -
Data is shown before form submission in Django 4.1
community! My goal is to create an app, which takes some user input, does machine-learning stuff and shows the results. I want to know whether the result was correct for each prediction. That's why I'm trying to implement a feedback system, where a user could mark the answer as "correct" or "incorrect" if one wants to do so. To be exact, I have two buttons: "the prediction looks like true" and "the prediction was incorrect". After clicking on one of these buttons I have a pop-up dialog shown with 3 checkboxes, where a user can provide additional information (it is not required). forms.py with these checkboxes looks like this: from django import forms class checkboxForm(forms.Form): is_winner_reason_true = forms.BooleanField(required=False, label="The first place in importance coincides with reality", label_suffix='') is_top5_reason_true = forms.BooleanField(required=False, label="Top 5 includes friends with high importance", label_suffix='') is_other_reason_true = forms.BooleanField(required=False, label="Other", label_suffix='') class checkboxFormFalsePred(forms.Form): is_winner_reason_false = forms.BooleanField(required=False, label="The other person should come first in importance", label_suffix='') is_top5_reason_false = forms.BooleanField(required=False, label="Top 5 includes friends with low importance", label_suffix='') is_other_reason_false = forms.BooleanField(required=False, label="Other", label_suffix='') I want to get data from clicking on one of two buttons (the value will be either True or False) and then, if a user decided to … -
Generic detail view UserRegister must be called with either an object pk or a slug in the URLconf
I'm getting this error when trying to register to my to-do list web Generic detail view UserRegister must be called with either an object pk or a slug in the URLconf. views.py class UserRegister(CreateView): model = User form_class = UserRegisterForm template_name = 'users/form_register.html' redirect_authenticated_user = True success_url = reverse_lazy('tasks') # Forbid logged in user to enter register page def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(UserRegister, self).get(*args, **kwargs) # Send email verification def post(self, request, *args, **kwargs): self.object = self.get_object() form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your account' message = render_to_string('users/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('login') else: return self.form_invalid(form) urls.py urlpatterns = [ path('register/', UserRegister.as_view(), name='register'), path('login/', UserLogin.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('activate/<uidb64>/<token>/', ActivateAccount.as_view(), name='activate'), ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Maybe it got something to do with the models.py? But to be honest I don't really know what else to put there. Keep in mind I have two apps, the user app for registration and login and whatnot, and the tasks app for displaying tasks, creating, deleting task, etc. -
How to reuse properties from table with django?
oke. I have one table. like: class AnimalGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to="photos/groups") class Meta: verbose_name = "animalgroup" verbose_name_plural = "animalgroups" def __str__(self): return self.group_name And this are animal groups. Like: mammals fish reptils But then I hava a subgroup where a user can enter the same properties as by AnimalGroup. And the AnimalGroup can have multiple subgroups. Like: mammals: cats, dogs, cattles. And then you have the animal it self: cats: siamese cat, ragdoll, etc. My question is: how can I resuse this properties for the three objects? So AnimalGroup subgroup animal So that a user can enter in the admin panel of django: mammals fish reptils and then can enter cats and choose from dropdown mammals. Because all the objects: AnimalGroup subgroup animal have in common the fields: name description images -
can solve this error ? ( NoReverseMatch )
I'm ratherly amatour in django and cant solve this problem, error: NoReverseMatch at /blog/ Reverse for 'single' with keyword arguments '{'pid': ''}' not found. 1 pattern(s) tried: \['blog/(?P\<pid\>\[0-9\]+)\\Z'\] urls.py : from django.urls import path from blog.views import \* from django.conf.urls.static import static app_name= 'blog' urlpatterns = \[ path('',home,name='home'), path('\<int:pid\>',single, name='single'), \] views.py : from django.shortcuts import render from blog.models import Post import datetime def single(request,pid): single_post= Post.objects.filter(pk=pid) def counting_single_views(n): n.counted_views += 1 n.save() counting_single_views(single_post) context = {'single_post':single_post} return render(request,'blog/blog-single.html',context) def home(request): now = datetime.datetime.now() posts= Post.objects.filter(published_date__lte= now) context={'posts':posts} return render(request,'blog/blog-home.html',context) blog-home.html : {% for post in posts %} \<a href="{% url 'blog:single' pid=post.pk %}"\>\<h3\>{{post.title}}\</h3\>\</a\> \<p class="excert"\> {{post.content}} \</p\> {% endfor %} i tried with id instead of pk , but no differ, -
Django Variations not displayed
In order to list my variations_value i render data into context but when i pass the object to the frontend it's recognised as a queryset but i can't use data from it Model variation_category_choice = ( ('color', 'color',), ('size', 'size',), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=100, choices=variation_category_choice) variation_value = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now=True) def __unicode__(self): return self.product View def product_detail(request, category_slug, product_slug): try: single_product = Product.objects.get(category__slug=category_slug, slug=product_slug) in_cart = CartItem.objects.filter(cart__cart_id=_cart_id(request), product=single_product).exists() variations = Variation.objects.filter(product=single_product) except Exception as e: raise e context = { 'single_product': single_product, 'in_cart': in_cart, 'variations': variations } return render(request, 'store/product_detail.html', context) HTML <h1>{{variations.variation_value}}</h1> -
How can I make the selection value in the model form Django based on the value selected above?
Good day! I have a model table in order to add data to this model. [Citizen_2] At me in the field the country is selected by the user. The form then records the city based on the selected country value. You need to save them in the [Citizen_2] table model so that the city corresponds to its country in the corresponding fields. I've been thinking about how to do this for a week now. I would be very grateful for any hints. I would like users to enter their country of residence first, it's like a simple one-field form. And then a form of two fields - where it is proposed to select the country of residence from the value already entered in the (name_country) field. For example, I have users added three countries there. Then they add the cities - for those respective countries. In the drop-down form field, select a country and write down your city there. And send the data to the model table. It is necessary that the data be saved in such a way that the city corresponds to the country to which the user wrote it down in the form. This is then used … -
Django & postgress sometime result into empty resultset
I have a table name finance_details. When I query using invoice_id_id = value and is_paid = False. Data exist in table but resultset is empty. Below code finance_details = FinanceIORDetails.objects.filter(invoice_id=sample_string, is_paid=False).first() if not finance_details: Can anyone pls help as this is happening on production. Data exists in table but resultset is empty -
How to add a checkbox column in your Django template
I have a Django application, I want to show pandas dataframe in my template, so I parse it using df.to_html() and pass it in the render, and show it in my template using <table>{{data|safe}}</table>, my data is displayed as I expect, but I want some modification, I want an extra column in my data frame, each cell in that column will have a checkbox, user can check/uncheck it. I want to get information that which cells are checked so I display some more information about those rows. What I have: What I want: -
How to parse request.body for multipart file in django
I have used below code to post data to url public void updateLogo(String clientKey, MultipartFile file) { MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("file", file.getResource()); Settings prevData = repo.findFirstByClientKey(clientKey); WebClient webClient = WebClient.builder().baseUrl("http://localhost/") .defaultHeader(HttpHeaders.AUTHORIZATION, String.format("Token %s", userToken)).build(); Mono<SettingsLogo> resObj = webClient.post().uri("api/upload-logo") .contentType(MediaType.MULTIPART_FORM_DATA).body(BodyInserters.fromMultipartData(builder.build())) .retrieve().bodyToMono(SettingsLogo.class) .onErrorResume(WebClientResponseException.class, ex -> { logger.error("Exception", ex); return Mono.empty(); }); } On Django post function class UpdateJiraAppLogo(APIView): def post(self, request, *args, **kwargs): print('POST', request.POST) print('BODY', request.body) print('FILES', request.FILES) logo = request.body now = timezone.now() logo_name = "logo_" + str(now.strftime('%d_%m_%Y') + "_" + now.strftime('%H%M%S')) + ".png" try: with open("media/logos/" + logo_name, "wb+") as f: f.write(logo) f.close() except Exception as e: print(e) Following is printed POST <QueryDict: {}> BODY b'--3oqd3VUazPhxbazUKCTiNsp2MeoS9RgQqbQLnj7X\r\nContent-Disposition: form-data; name="file"; filename="clock.png"\r\nContent-Type: image/png\r\nContent-Length: 1959\r\n\r\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00x\x00\x00\x00x\x08\x03\x00\x00\x00\x0e\xba\xc6\xe0\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00u0\x00\x00\xea`\x00\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x01\xefPLTE\x00\x00\x00\xe399\xde11\xde33\xdc33\xdd44\xdd33\xdd33\xdd33\xdd33\xdd33\xde44\xdf@@\xff\x00\x00\xdb55\xdc33\xdd33\xdd33\xdd33\xdd44\xde44\xdb11\xde77\xdc22\xde44\xdd33\xdd22\xde22\xdc..\xdb$$\xde22\xdd33\xdd33\xdd33\xdd22\xdc44\xe633\xdf33\xdc33\xdd33\xde44\xdd55\xdd33\xdd33\xdd33\xdd55\xdc33\xde33\xdc44\xdd33\xdb11\xe399\xde33\xdd33\xdc22\xdb11\xdd33\xdd33\xff\x00\x00\xde11\xdd22\xdd33\xdd33\xdd33\xdd33\xde44\xbf@@\xdd44\xd5++\xdc55\xdd33\xdb77\xe022\xdd33\xdc33\xdd33\xde44\xdd33\xdd44\xdd33\xdd33\xdc44\xdd33\xdd33\xdd33\xde33\xdd33\xcc33\\x00\x00\x00%tEXtdate:create\x002019-06-02T16:58:33+00:00.c\xfc\x1c\x00\x00\x00%tEXtdate:modify\x002019-06-02T16:58:33+00:00_>D\xa0\x00\x00\x00\x00IEND\xaeB`\x82\r\n--3oqd3VUazPhxbazUKCTiNsp2MeoS9RgQqbQLnj7X--\r\n' FILES <MultiValueDict: {}> the file is saved but it is corrupted. How to save file when file is received in request.body rather than FILES or POST? -
django.db.utils.IntegrityError: and django.db.utils.OperationalError:
raise integrityerror( django.db.utils.integrityerror: the row in table 'hazeapp_orderitem' with primary key '1' has an invalid foreign key: hazeapp_orderitem.product_id contains a value '5' that does not have a corresponding value in hazeapp_newarrival.id.enter image description here I am trying to build 2 different models that include different product with their prices, name etc and render those two model products in two different template using for loop. But while creating an OrderItem model which includes both above foreign model leads to integrity error mostly. The code i tried was: class NewArrival(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): collection = models.ForeignKey(Collection, on_delete=models.SET_NULL, blank=True, null=True) newarrival = models.ForeignKey(NewArrival, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = 0 if self.collection: total += self.collection.price * self.quantity if self.newarrival: total += self.newarrival.price * self.quantity return total -
get foreign key related data in django using filter
This is the model : class Requirement(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey( User,on_delete=models.CASCADE, related_name = 'user' ) assigned_user = models.ForeignKey( User,related_name = "assigned",on_delete=models.CASCADE, ) I am running this query: requirementsOb = Requirement.objects.filter(user = currentUser) Where currentUser is logged in user. The result returns multiple requriements. I also want to get all user related data. How can i get user related data? -
Getting 'No field found in Account with column name ""' when creating data for project using django-multitenant library
I'm trying to create a data migration script to insert initial data I have a migration file as below Account = apps.get_model("quickstart", "Account") Account.objects.using(db_alias).bulk_create([ Account(name="johndoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="USA")), Account(name="jilldoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="USA")), Account(name="milldoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="USA")), Account(name="velidoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="Turkiye")), Account(name="alidoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="Turkiye")), Account(name="pierredoe", domain="domain", subdomain="subdomain", country=Country.objects.get(name="France")), ]) When I execute ./manage migrate I got the error below Traceback (most recent call last): File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/manage.py", line 22, in \<module\> main() File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(\*args, \*\*cmd_options) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(\*args, \*\*options) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(\*args, \*\*kwargs) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self.\_migrate_all_forwards( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in \_migrate_all_forwards state = self.apply_migration( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/tutorial/quickstart/migrations/0002_initial_data.py", line 95, in forwards_func TenantNotIdModel(tenant_column=1, name="TenantNotIdModel 1"), File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django_multitenant/mixins.py", line 58, in __init__ super(TenantModelMixin, self).__init__(\*args, \*\*kwargs) File "/home/gurkanindibay/tenants/tests/django-multi-tenant/tutorial/venv/lib/python3.9/site-packages/django/db/models/base.py", line 470, in __init__ self.\_state = ModelState() File … -
Django redirecting
I can't figure out why my redirection after paying doesn't work. I'm trying to display the thank_you template once the user has paid via Paypal. My code all works other than the final render of the thank_you template (I receive the email and see the 'Made it' print statement). Urls: from django.urls import path from . import views app_name = 'checkout' urlpatterns = [ path('', views.checkout, name='checkout'), path('thank_you', views.thank_you, name='thank_you'), path('order_success', views.order_success, name='order_success'), ] Views.py: import json from django.shortcuts import render, redirect, reverse, HttpResponseRedirect from django.http import JsonResponse from django.contrib import messages from django.urls import reverse from profiles.models import UserProfile from products.models import Product from django.views.decorators.http import require_POST from .models import Order, OrderDetail from django.core.mail import send_mail from the_rescuers.settings import DEFAULT_FROM_EMAIL from templated_email import send_templated_mail from .forms import OrderForm def checkout(request): bag = request.session.get('bag', {}) if not bag: messages.error(request, "There's nothing in your bag at the moment") return redirect(reverse('products:products_list')) order_form = OrderForm() bag_products = [] for item_id, quantity in bag.items(): product = Product.objects.get(pk=item_id) name = product.name id = product.id bag_products.append({'name': name, 'id': id, 'quantity': quantity}) bag_products = json.dumps(bag_products) # Attempt to prefill the form with any info the user maintains in # their profile if request.user.is_authenticated: profile = UserProfile.objects.get(user=request.user) order_form … -
Why my base.html page not showing in my website, only showing the code like{% extends 'base.html' %}
enter image description herethis is index.html page enter image description here Why the code showing -
Using Django ChoiceField gives a Value Error
I try to create dynamic choice. I fill choices with unit_list. Data to unit_list loading from API (units). I set the choices dynamicly in the constructor. But when I try to save a new form, it gives 'value error'. Have a nice day. class Announcement(models.Model): title = models.CharField(max_length=200, verbose_name=_('İlan Başlığı')) unit = models.IntegerField(null=True,blank=True) def announcement_new(request): response = requests.get('http://127.0.0.1:8001/api/units/list/') units = response.json() unit_list=[] for unit in units: unit_list.append(((int(unit.get('id'))), str(unit.get('name')))) ann_form = AnnouncementForm(unit_list) if request.method == 'POST': ann_form = AnnouncementForm( request.POST) if ann_form.is_valid(): ann_instance = ann_form.save(commit=False) ann_instance.save() return redirect('ann') else: print('Hata: ',ann_form.errors) else: context = { 'ann_form':ann_form, } return render(request,'pages/ann/ann_new.html',context) class AnnouncementForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "", })) unit = forms.ChoiceField( required=False, widget=forms.Select(attrs={ "class": "form-control form-select select2", }),) def __init__(self, unit_list, *args, **kwargs): super(AnnouncementForm, self).__init__(*args, **kwargs) self.fields['unit'].choices = unit_list class Meta: model = Announcement fields = "__all__" -
The view users.views.view didn't return an HttpResponse object. It returned None instead
I'm making a to-do list web with my friend. So, I have created the register function with email authentication, and it works fin. I pushed it to the GitHub and my friend pulled it and tried it in his laptop. But when he clicks "register" he got this error The view users.views.view didn't return an HttpResponse object. It returned None instead. We literally have the same code since he pulled the code from my repository, we both user virtual environment, installing from the same requirements.txt, and we both uses WSL2. This is the code views.py class UserRegister(CreateView): form_class = UserRegisterForm template_name = 'users/form_register.html' redirect_authenticated_user = True success_url = reverse_lazy('tasks') # Forbid logged in user to enter register page def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(UserRegister, self).get(*args, **kwargs) # Send email verification def post(self, request, *args, **kwargs): form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your account' message = render_to_string('users/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('login') else: form = UserRegisterForm() form_register.html -- Register --> <section> <div class="register-card"> <h2>Register for an account</h2> <form method="POST"> {% csrf_token %} <div class="txt_field"> <input type="text" … -
AttributeError at /register/ 'User' object has no attribute 'is_authenticed --- when i check user is auth
i want create function when user is authenticed -- redirect to home but is not authenticed show page register +++ in views from django.shortcuts import render, redirect from .models import customer from .forms import customer_form from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate from django.contrib.auth import login as login_auth from django.contrib.auth import logout from django.contrib.auth.decorators import login_required def register(request): if request.user.is_authenticed(): return redirect('/') else: form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form' : form} return render(request, 'register.html', context) +++ path from django.urls import path from . import views path('register/', views.register, name="register"), i want create function when user is authenticed -- redirect to home but is not authenticed show page register -
django.db.utils.IntegrityError: and django.db.utils.OperationalError:
raise IntegrityError( django.db.utils.IntegrityError: The row in table 'hazeapp_orderitem' with primary key '1' has an invalid foreign key: hazeapp_orderitem.product_id contains a value '5' that does not have a corresponding value in hazeapp_newarrival.id. django.db.utils.OperationalError: no such column: hazeapp_orderitem.collection_id class NewArrival(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): collection = models.ForeignKey(Collection, on_delete=models.SET_NULL, blank=True, null=True) newarrival = models.ForeignKey(NewArrival, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = 0 if self.collection: total += self.collection.price * self.quantity if self.newarrival: total += self.newarrival.price * self.quantity return total -
how to solve Import error for zinnia package for django v 3.2 and python 3.8(python_2_unicode_compatible import for zinnia v 0.20)?
trying to add zinnia to my django project django 3.2 python 3.8 zinnia 0.20 but shows File "/home/sayone/Documents/learning/virtuals/fastkart/lib/python3.8/site-packages/zinnia/models/init.py", line 2, in from zinnia.models.author import Author File "/home/sayone/Documents/learning/virtuals/fastkart/lib/python3.8/site-packages/zinnia/models/author.py", line 6, in from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (/home/sayone/Documents/learning/virtuals/fastkart/lib/python3.8/site-packages/django/utils/encoding.py) is there any other version of zinnia supporting django 3.2. -
'method' object is not subscriptable, usando request.GET en django [closed]
estoy viendo un tutorial de Django soy bastante nuevo en esto, por lo que no entiendo porque me sale ese error, no sé si quizá sea la versión de Django ya que el tutorial es de 2021. Help me !!! **Este es el formulario, nada tan complicado: ** <!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.0"> <title>Document</title> </head> <body> <form action="/buscar/" method="GET"> <input type="text" name="prd"> <input type="submit" value="Buscar"> </form> </body> </html> Este es mi view: def buscar(request): if request.GET["prd"]: #mensaje = "Articulo buscado: %r " %request.GET['prd'] product = request.GET["prd"] art = Articulo.objects.filter(nombre__icontains=product) return render(request, "resultado_busqueda.html", {"art":art, "query":product}) else: mensaje = "No escribio nada" return HttpResponse(mensaje) -
How to make an attribute read-only in serializers in DRF?
I have a serializer. class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass My model class is: class MyClass(models.Model): employee = models.ForeignKey("Employee", on_delete=models.CASCADE) work_done = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want employee attribute to be read-only and should only show this value in it's field: employee = Employee.objects.get(user=self.request.user) How can I do this in serializers? -
Problem to run python commands in Pycharm
I am trying to run the server in my Django project, but I found this problem, I just look my envirol path, it is all ok. Run my server, and all the Python commands. -
django- how can login page with Custom User without UserCreationForm?
models.py class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class pal1Form(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model=CustomUser fields=['username','email','password'] def save(self): user = super().save(commit=False) user.is_student = True user.save() return user class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm,pal1Form def add_form(request): form = palForm(request.POST, request.FILES) form1=pal1Form(request.POST) if request.method == "POST": form = palForm(request.POST , request.FILES) form1=pal1Form(request.POST) if form.is_valid() and form1.is_valid() : try: form.save() form1.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html",context={"form":form}) else: form=palForm() form=pal1Form() return render (request,"home/pal-form.html",context={"form":form,"form1":form1}) def login(request): form=pal1Form(request.POST) if request.method == 'POST': form=pal1Form(request.POST) if form.is_valid(): user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password'], ) if user is not None: login(request, user) return redirect("menu") else: messages.error(request,"Invalid username or password.") return redirect(login") return render( request, 'login.html', context={'form': form}) I'm trying a lot login page with multiple user page but login is not open so How can i login in custom user page? What was the problem? Can anyone help me?