Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build object after serialize in Django
I am serializing the instance of a model in the following way. serialized_object = serializers.serialize ('json', [track,]) output [{"model": "blog.track", "pk": null, "fields": {"album": null, "name": "Song 1", "lyrics": "", "song": "Z.mp3", "url_download": null, "length": "00:00:12"}}] Then I save the serialized object, so that at the end of some tasks I can save it in the database. My question is how do I re-build the instance of the model from the serialized model. And how can I get the fields of the serialized model in the view? -
Adding comments in django
I am student and a beginner in Django. I just want to ask how I can convert this comment code from function view to class view. Also note that the book has a slug field. def BookDetail(request, id): most_recent = Book.objects.order_by('-timestamp')[:3] book= get_object_or_404(Book, id=id) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={ 'id': book.pk })) context = { 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) from the above code to the one below: class BookDetailView(DetailView): model = Book -
Custom signals in Python
I read the Django documentations about making my own signals but it is quiet difficult for me to grasp. Can you give me an example of making your own signal and give some details please? thank you in advance -
How to generate a CSV and then upload it to a remote server in Django?
This following link is somehow related but does not answer my question -> Django: generate a CSV file and store it into FileField. The question is that I have a query set like below: users = User.objects.raw('SELECT * FROM users') How should I generate a CSV object and then upload it into an S3 object storage server? The problem is that I don't know how to generate a CSV object on the fly. -
unique_together and M2M field
I have the following Model: class CodeSynonyms(models.Model): code = models.ForeignKey(Codes, on_delete=models.CASCADE) websites = models.ManyToManyField(Websites) synonym = models.Charfield(max_length=10) The idea is that Websites use the Synonyms for specific Codes. One Website can't have few Synonyms for a Code; various Websites can share the same Synonym for specific Code. The following won't work: class Meta: unique together = ('code', 'websites') " 'unique_together' refers to a ManyToManyField 'websites', but ManyToManyFields are not permitted in 'unique_together' " Is there a way to solve this keeping the M2M relation? It would be handy to have it -
Admin form for custom User in django
I'm writing my first project in django. I need to create few types of users with different fields. I've created Client class with 1-1 relation with User and trying to create admin form for it models.py class Client(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete="CASCADE") new_field = models.CharField("New field", max_length=30) And I'm trying to create form in django admin to manage Client instances with inlided User fields. admin.py class UserInline(admin.StackedInline): model = auth.models.User class ClientAdmin(admin.ModelAdmin): class Meta: model = Client fields = '__all__' class ExtendedClientAdmin(ClientAdmin): inlines = ClientAdmin.inlines + [UserInline] admin.site.register(Client, ExtendedClientAdmin) But I got following error: ERRORS: <class 'backoffice.admin.ClientInline'>: (admin.E202) 'auth.User' has no ForeignKey to 'backoffice.Client'. How should I create form for Client admin with inlined User fields? -
Create Custom JSON output from Django Model objects
I'm trying to output json data from my Question models. I can't seem to get it right. {"response_code":0,"results":[{"category":"Vehicles","type":"multiple","difficulty":"easy","question":"The Italian automaker Lamborghini uses what animal as its logo?","correct_answer":"Bull","incorrect_answers":["Bat","Horse","Snake"]},{"category":"Mythology","type":"multiple","difficulty":"medium","question":"Who was the Roman god of fire?","correct_answer":"Vulcan","incorrect_answers":["Apollo","Jupiter","Mercury"]},{"category":"General Knowledge","type":"multiple","difficulty":"medium","question":"After how many years would you celebrate your crystal anniversary?","correct_answer":"15","incorrect_answers":["20","10","25"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"hard","question":"Which of these online games was originally named LindenWorld in it&#039;s early development?","correct_answer":"SecondLife","incorrect_answers":["ActiveWorlds","IMVU","HabboHotel"]},{"category":"History","type":"multiple","difficulty":"hard","question":"When was the SS or Schutzstaffel established?","correct_answer":"April 4th, 1925","incorrect_answers":["September 1st, 1941","March 8th, 1935","February 21st, 1926"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"medium","question":"In the video game &quot;League of Legends&quot; which character is known as &quot;The Sinister Blade&quot;?","correct_answer":"Katarina","incorrect_answers":["Shaco","Akali","Zed"]},{"category":"Science & Nature","type":"multiple","difficulty":"easy","question":"What is the standard atomic weight of a Plutonium nucleus?","correct_answer":"244","incorrect_answers":["94","481","128"]},{"category":"Entertainment: Comics","type":"multiple","difficulty":"hard","question":"What is the real hair colour of the mainstream comic book version (Earth-616) of Daredevil?","correct_answer":"Blonde","incorrect_answers":["Auburn","Brown","Black"]},{"category":"Science & Nature","type":"multiple","difficulty":"hard","question":"What does the term &quot;isolation&quot; refer to in microbiology?","correct_answer":"The separation of a strain from a natural, mixed population of living microbes","incorrect_answers":["A lack of nutrition in microenviroments","The nitrogen level in soil","Testing effects of certain microorganisms in an isolated enviroments, such as caves"]},{"category":"Geography","type":"multiple","difficulty":"easy","question":"What is the capital of South Korea?","correct_answer":"Seoul","incorrect_answers":["Pyongyang","Taegu","Kitakyushu"]}]} Category, type and difficulty can be ignored for now. Models.py class Question(models.Model): question = models.CharField("Question",max_length=255,blank=True, null=True) correct_answer = models.CharField("Correct Answer",max_length=255,blank=True, null=True) class Incorrect(models.Model): incorrect_answers = models.CharField("Incorrect Answer",max_length=255,blank=True, null=True) question = models.ForeignKey(Question, on_delete=models.CASCADE,blank=True, null=True) I'm running on django 1.11 and … -
how to allow url only to be accessed from a specific page
I want users to get access to the payment page only if the buyer selected some prodcts to buy or if the delivery information form is valid.If users type like /home/shop/payement in the address bar then it should through some error message or anything like that views.py def items_buy(request): if not request.user.is_authenticated: messages.info(request, 'You have to logged in first.') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) sess = request.session.get("data", {"items": []}) if request.method == "POST": form = BuyerDeliveryForm(request.POST) if form.is_valid(): buyer = form.save(commit=False) buyer.save() buyer.product.set(Product.objects.filter(active=True, slug__in=sess["items"])) return redirect('shop:payment') else: form = BuyerDeliveryForm() return render(request, 'shop/delivery_form.html', {'form': form}) def payment(request): return render(request,'shop/payment.html') -
Why Django doesnt migrate my altered model?
Hi i have a django model as below: from django.db import models class ClientProfile(models.Model): id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=100,blank=False) lastname = models.CharField(max_length=100,blank=False) gender = models.CharField(max_length=6,blank=False) birthdate = models.DateField(blank=False) nationality = models.CharField(max_length=100,blank=False) education = models.CharField(max_length=100,blank=True) occupation = models.CharField(max_length=100,blank=True) i have created this model with email field initially. but then i decided to deduct it. now i get this error when i migrate: django.db.utils.OperationalError: near "AUTOINCREMENT": syntax error and then i deleted my database and migrated again and i get the same message again. I tried deleting my app view and then start from scrach(creating a new migration and creating a new superuser and then add the model again) and still got the same error. i even tried rollback to initial migrations and then migrate again but got the email field back again and the new migration didn't change it. what can i do? -
How to make editable fields in frontend for Django objects
I need to make objects editable in frontend by clicking on it and enable a form field to edit the text. i.e. in a ToDo-list which tasks can be edited by clicking on the task like shown in the following graphics: I am working with Django 2.x and unfortunately, I'm a little inexperienced. Is it a good practice to realize this with REST API and/or Angular/React? I would be glad about a few experiences, how something is feasible. -
Increment attribute of the object in django model
a = Article.objects.get(id=10) if I have a dict like this: d = {'like': a.likes, 'dislike': a.dislike} and the user will choose 'like', how can I increment a.likes += 1 and save it to model, and the same for 'dislike'? -
Parallel override of data when appending new data to instance in Django Rest Framework using PUT and PATCH
I'm developing a Web App for a uni project and it's about airports and carriers... My models are: class Carrier(models.Model): code = models.CharField(max_length=10, primary_key=True) name = models.TextField() def __str__(self): return self.name class Airport(models.Model): code = models.CharField(max_length=10, primary_key=True) name = models.TextField() carriers = models.ManyToManyField(Carrier, related_name='airports') def __str__(self): return self.name Serializers: class AirportListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='airport-detail') class Meta: model = models.Airport fields = ('code', 'name', 'url') class AirportDetailSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='airport-detail') class Meta: model = models.Airport fields = ('code', 'name', 'url', 'carriers') And I'm having problems with my update method I had to override it because for appending new data to the carriers array of an instance of an airport: def update(self, request, *args, **kwargs): instance = self.get_object() serializer = serializers.AirportDetailSerializer( instance=instance, data=request.data, context={'request': request} ) if serializer.is_valid(raise_exception=True): # Getting the user inputed carriers after it was validated by the serializer carriers = set(dict(request.data)['carriers']) # Adding new carriers to the current airport list of carriers without deleting the old ones for carrier in serializer.validated_data['carriers']: print(carrier) carriers.add(carrier) print('Carriers %s' % carriers) # Saving alterations to the db serializer.save(carriers=carriers) # Overriding the original data for more features data = serializer.data # Creating the carrier links data['carriers'] = ['http://%s/api/carriers/%s/' % (request.get_host(), carrier) for carrier in … -
Cannot assign "<QuerySet [<Contact: zak>]>": "Booking.contact" must be a "Contact" instance
I have a issu, I created a form where users can make a reservation (in detail view) of unique product.So one user can have multiples booking. The form which use email and username is in my detail.html with include variable {% include 'store/list.html' with list_title=name %} models.py from django.db import models class Contact(models.Model): email = models.EmailField(max_length=100) name = models.CharField(max_length=200) def __str__(self): return self.name class Marque(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class Model(models.Model): #Plusieurs models pour une marque reference = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) name = models.CharField(max_length=200) picture = models.URLField() marque = models.ForeignKey(Marque, on_delete=models.CASCADE) def __str__(self): return self.name class Booking(models.Model): #plusieurs réservation pour un contact created_at = models.DateTimeField(auto_now_add=True) contacted = models.BooleanField(default=False) marque = models.OneToOneField(Marque, on_delete=models.CASCADE) model = models.OneToOneField(Model, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) def __str__(self): return self.contact.name views.py: ... def detail(request, model_id): model = get_object_or_404(Model, pk=model_id) #marques = [marque.name for marque in model.marque.all()] #marques_name = " ".join(marques) if request.method == 'POST': email = request.POST.get('email') name = request.POST.get('name') contact = Contact.objects.filter(email=email) if not contact.exists(): #If a contact is not registered, create a new one contact = Contact.objects.create( email = email, name = name ) #If no album matches the id, it means the form must have … -
Disable health-check logging in AWS ELB Django Application
I have a Django application running on aws-elastic-beanstalk. I try to disable the logs from my health-checks. The health-checks are already routed to a seperate page. Elastic-beanstalk uses Apache + mod_wsgi. The following code is a solution that works with nginx servers. I try to create something similar for apache. ~/workspace/my-app/ |-- .ebextensions | `-- nginx | `-- conf.d | `-- myconf.conf #turn off access logs server { location /elb-status { access_log off; } } I found that conditional Logs are probably the appropriate way to do it with an Apache Server. -
Cannot assign "{}": "Cart.cart" must be a "Cart" instance
Please help me, i don't know what's wrong. I did everything by example. There was Django 1.6 and older. I have Django 2.1.5 And various problems appear. My forms.py from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) My Cart/views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST @csrf_exempt def CartAdd(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:CartDetail') def CartRemove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:CartDetail') def CartDetail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) If u need i can send u other files (cart.py, shop/views.py) -
Django Create View require a field
I have this model class Monument(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(_('nome'), max_length=150, unique=True, db_index=True) address = models.CharField(_('indirizzo'), max_length=255, null=False, blank=True) geo_coordinates = models.CharField(_('coordinate geografiche'), max_length=20, null=False, blank=True) description = models.TextField(_('descrizione'), blank=False, null=False) website_url = models.URLField(_('URL sito web'), max_length=200, null=True, blank=True) audioguide = models.FileField(_('audioguida'), upload_to='audioguide/', null=False, blank=False) opening_time = models.TimeField(_('orario apertura'), null=True, blank=True, default=now) closing_time = models.TimeField(_('orario chiusura'), null=True, blank=True, default=now) This is the view class MonumentCreateView(generic.CreateView): model = models.Monument fields = '__all__' template_name = 'dashboard/monuments_form.html' def get_context_data(self, **kwargs): context = super(MonumentCreateView, self).get_context_data(**kwargs) context['page_title'] = 'Aggiungi monumento' return context This is the template <form class="form-horizontal form-label-left" action="{% url 'dashboard:monuments-create' %}" method="post" novalidate>{% csrf_token %} {% for field in form %} <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.error }}</span> </div> <div class="item form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="{{ field.name }}">{{ field.label_tag }}{% if field.field.required %}(*){% endif %}</label> <div class="col-md-6 col-sm-6 col-xs-12"> {% render_field field class="form-control col-md-7 col-xs-12" %} </div> </div> {% endfor %} <div class="ln_solid"></div> <div class="form-group"> <div class="col-md-6 col-md-offset-3"> <a href="{% url 'dashboard:monuments-list' %}"><button type="button" class="btn btn-primary">Annulla</button></a> <button id="send" type="submit" class="btn btn-success">Salva</button> </div> </div> </form> The form is returned correctly, but when I fill in all the fields and proceed to send the form, it displays an "Field Required" … -
How to store multiple model objects in django admin
i want to store multiple products list into the Buyer Model.How can i do that ?? I got this error saying can not assign query set.: ValueError at /shop/items/buy/now/ Cannot assign ", ]>": "Buyer.product" must be a "Product" instance. models.py class Product(models.Model): name = models.CharField(max_length=250) image = models.ImageField(upload_to='products') seller = models.ForeignKey(User,on_delete=CASCADE) slug = AutoSlugField(populate_from='name') category = models.ForeignKey(Category,on_delete=CASCADE) description = models.TextField(blank=True,default="Description Field") brand = models.CharField(max_length=250) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=10,default=0.0,decimal_places=2) shipping_fee = models.DecimalField(max_digits=10,default=0.0,decimal_places=2) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Buyer(models.Model): full_name = models.CharField(max_length=250) phone = models.CharField(max_length=20) city = models.CharField(max_length=250,choices=city_choices) address = models.CharField(max_length=250,default="123Area , House#123 , Street#123") product = models.ForeignKey(Product,on_delete=CASCADE) def __str__(self): return self.full_name forms.py class BuyerDeliveryForm(forms.ModelForm): class Meta: model = Buyer fields = ['full_name','phone','city','address'] views.py def items_buy_now(request): if not request.user.is_authenticated: messages.info(request, 'You have to logged in first.') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) sess = request.session.get("data", {"items": []}) if request.method == "POST": form = BuyerDeliveryForm(request.POST) if form.is_valid(): buyer = form.save(commit=False) buyer.product = Product.objects.filter(active=True, slug__in=sess["items"]) buyer.save() return redirect('shop:payment') else: form = BuyerDeliveryForm() return render(request, 'shop/delivery_form.html', {'form': form}) def mycart(request): sess = request.session.get("data", {"items": []}) products = Product.objects.filter(active=True, slug__in=sess["items"]) if not products: return render(request,'shop/empty_cart.html') context = {"products": products, "categories": categories} return render(request,'shop/cart_item.html',context) … -
How to delete Django model without breaking tests?
I have simple model, let's say, from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') When i want to delete this, I removed all foreign key related fields, Deleted all references Create migrations Apply migrations and that was okay for working copy of my project. But when i want to run tests, migrations couldn't be done because some of the migrations in past has references to that model as foreign key. Is there anyway to delete a model without breaking migrations? I know, squashing is an option but i don't think it's the best for the issue and a bit overkill. -
How to access multiple values in request body of django?
I want to select multiple values for an attribute in my Django website. if request.method == 'POST': print(request.POST) print(request.POST['category']) The output of the above code is when I select the second and third category together is - <QueryDict: {'csrfmiddlewaretoken': ['HYArlTZpPYIDX404ImuX4UjzC03qaa3zTa18Wd7hVw2AYaMln8ZaVfaJ8TsNtbZp'], 'category': ['2', '3']}> 3 I am unable to understand what I am doing wrong. Please help me out. Thanks. -
Why does a Django forms.TextField take up so much space, even when the text input area is small?
I'm creating a Django form and when I change from a TextInput to a TextArea the html/css requires a lot more spacing around the element, here it is with TextArea: and here it is with a TextInput: I'm using Bulma css framework. and everything I've tried to make the TextField "fit" to use the area that is available has failed. The bulma column has display: flex, which cannot be altered either. How can I use the textarea while keeping a "tight" layout? edit: putting fixed height on the div works, but then it loses all responsibility, and the layout does not work. -
How to append list of objects in serialized data? in Django Rest framework
I have following output currently. { "carts": [ { "id": 1, "product_id": 1, "description": null, "default": "Yes" } ], "categories": [ { "id": 1, "name": "Indoor Muscle Training", "description": null }, { "id": 2, "name": "Outdoor Muscle Training", "description": null } ] } And I want to append few list of objects like below. These product need to be static right now. { "carts": [ { "id": 1, "product_id": 1, "description": null, "default": "Yes" } ], "categories": [ { "id": 1, "name": "Indoor Muscle Training", "description": null, "products":[ { "id":1, "name":"Product One" }, { "id":2, "name":"Product Two" } ] }, { "id": 2, "name": "Outdoor Muscle Training", "description": null, "products":[ { "id":1, "name":"Product One" }, { "id":2, "name":"Product Two" } ] } ] } Here's my current files views.py def home(request): if request.method == 'GET': default_cart = DefaultCart.objects.all() categories = Category.objects.filter(parent_id=0) serialized_default_cart = DefaultCartSerializer(default_cart, many=True) serialized_categories = CategorySerializer(categories, many=True) return Response({ 'carts':serialized_default_cart.data, 'categories':serialized_categories.data, }) serializers.py class DefaultCartSerializer(serializers. HyperlinkedModelSerializer): class Meta: model = DefaultCart fields = ( 'id', 'product_id', 'description', 'default' ) class CategorySerializer(serializers. HyperlinkedModelSerializer): class Meta: model = Category fields = ( 'id', 'name', 'description', ) These products need to be append a static values right now. Later I will … -
Need help understanding how to use slug in my urls.py
I sort of need help understanding my own code specifically the views.py. I'm trying to change url pattern for my TitleUpdateListView from using my Update models title field and using the slug field instead. views.py class TitleUpdateListView(ListView): model = Update context_object_name = 'updates' template_name = 'updates/title_updates.html' def get_queryset(self): title = get_object_or_404(Game, title=self.kwargs.get('title')) return Update.objects.filter(game=title).order_by('-date_published') def get_context_data(self, **kwargs): context = super(TitleUpdateListView, self).get_context_data(**kwargs) context['game'] = get_object_or_404(Game, title=self.kwargs.get('title')) return context class TitleUpdateAjaxListView(ListView): model = Update template_name = 'updates/updates_ajax.html' context_object_name = 'updates' paginate_by = 5 def get_queryset(self): title = get_object_or_404(Game, title=self.kwargs.get('title')) return Update.objects.filter(game=title, platform=Platform.objects.filter( id=self.kwargs.get('platform_id')).first()).order_by('-date_published') def get_context_data(self, **kwargs): context = super(TitleUpdateAjaxListView, self).get_context_data(**kwargs) context['game'] = get_object_or_404(Game, title=self.kwargs.get('title')) return context def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() context = self.get_context_data() return render(request, self.template_name, context) urls.py urlpatterns = [ # Update view for each game path('<str:title>/updates/', TitleUpdateListView.as_view(), name='title-updates'), # Adds the ability to sort by platform path('<str:title>/updates/<int:platform_id>/', TitleUpdateAjaxListView.as_view(), name='title-updates-ajax'), ] models.py class Update(models.Model): author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True,) # If user is deleted keep all updates by said user article_title = models.CharField(max_length=100, help_text="Use format: Release Notes for MM/DD/YYYY") content = models.TextField(help_text="Try to stick with a central theme for your game. Bullet points is the preferred method of posting updates.") date_published = models.DateTimeField(db_index=True, default=timezone.now, help_text="Use date … -
render_to_string gives error whereas render works
I am trying to render a response back to an Ajaz request. The view is reached in the python code, but if I try and render the response to string using render_to_string then I get an error stating: django.template.exceptions.TemplateDoesNotExist: If I run the render method with the same parameters then I don't get an error. The code for each looks like: html = render_to_string(request, 'planner/viewconnections.html', { 'routes' : routelist }) render(request, 'planner/viewconnections.html', { 'routes' : routelist }) Obviously the first one is what I want to run so I can obtain the raw html back to the AJAX success function. My templates configuration in settings.py looks like: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I have tried adding the template directory as below, but I still get the same error. ROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname((__file__)),"..")) # Other settings... TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, "planner/templates"), ) Can someone help? My search on this problem let me to add the TEMPLATE_DIRS in settings, but that didn't work. I don't understand why one render method can pick up the template, but the other doesn't. -
cannot assign queryset must be a instance
i am getting this value error ValueError at /shop/items/buy/now/ Cannot assign "QuerySet Product: mcloth2, Product: watch, Product: Watch": "Buyer.product" must be a "Product" instance. Request Method: POST Request URL: http://127.0.0.1:8004/shop/items/buy/now/ Django Version: 2.1.5 Exception Type: ValueError Exception Value: Cannot assign ", , ]>": "Buyer.product" must be a "Product" instance. buyer.product = product views.py def items_buy_now(request): if not request.user.is_authenticated: messages.info(request, 'You have to logged in first.') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) sess = request.session.get("data", {"items": []}) product = Product.objects.filter(active=True, slug__in=sess["items"]) if request.method == "POST": form = BuyerDeliveryForm(request.POST) if form.is_valid(): buyer = form.save(commit=False) buyer.product = product buyer.save() return redirect('shop:payment') else: form = BuyerDeliveryForm() return render(request, 'shop/delivery_form.html', {'form': form}) def cart(request,slug): product = Product.objects.get(slug=slug) initial = {"items":[],"price":0.0,"count":0} session = request.session.get('data',initial) if slug in session['items']: messages.error(request,'Already added.') else: session["items"].append(slug) session["price"] += float(product.price) if product.shipping_fee: session['price'] += float(product.shipping_fee) session["count"] += 1 request.session["data"] = session messages.success(request,'Added to Cart.') return redirect('shop:detail',slug) def mycart(request): sess = request.session.get("data", {"items": []}) products = Product.objects.filter(active=True, slug__in=sess["items"]) if not products: return render(request,'shop/empty_cart.html') context = {"products": products, "categories": categories} return render(request,'shop/cart_item.html',context) models.py class Buyer(models.Model): full_name = models.CharField(max_length=250) phone = models.CharField(max_length=20) city = models.CharField(max_length=250,choices=city_choices) address = models.CharField(max_length=250,default="123Area , House#123 , Street#123") product = models.ForeignKey(Product,on_delete=CASCADE) def __str__(self): return self.full_name class Product(models.Model): name = models.CharField(max_length=250) image … -
Django not applying the js and css ive linked
The following is the code for my projext which includes index.html, css , js , settings.py as well. I have properly made the folders as well in my project file, so its not an issue of source as well. I am trying to apply the pen from here: https://codepen.io/soju22/pen/ZPXLZe index.html <!DOCTYPE html> {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="{% static "clubapp/js/logmain.js" %}"> </script> <link rel="stylesheet" href="{% static "clubapp/css/yo.css" %}"/> </head> <body> <div id="info"> <h1>Tribute to Matthew Shlian</h1> <h2><em>Paper Artist</em> : Cutting Folding Gluing</h2> <p>This pen is inpired by <em><a href="https://www.instagram.com/p/BtLYfbOgR8v/" target="_blank">Unholy 132</a></em></p> <a class="link" href="https://www.mattshlian.com/" target="_blank"><i class="fa fa-link" aria-hidden="true"></i></a> <a class="link" href="https://www.instagram.com/matthewshlian/" target="_blank"><i class="fa fa-instagram" aria-hidden="true"></i></a> </div> </body> </html> CSS html, body { margin: 0; width: 100%; height: 100%; font-family: 'Montserrat', sans-serif; } canvas { position: fixed; width: 100%; height: 100%; } #info { position: absolute; width: 100%; top: 25%; z-index: 10; color: #fff; text-shadow: 2px 2px 2px #000; text-align: center; } a { color: #fff; } .link { display: inline-block; padding: 4px; margin: 0 0.5em; border-radius: 8px; background-color: rgba(255, 255, 255, 0.1); color: #fff; text-shadow: none; font-size: 24px; transition: all 0.4s; &:hover { color: #FF5649; background-color: rgba(255, 255, 255, 1); } …