Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
name 'validated_data' is not defined
I am trying to serialize multiple images posted for article in JSON format in DRF class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): images = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('id','author','caption','images') def create(self, validated_date): images = self.context['request'].FILES.getlist('images') articlefinal = Article.objects.create(**validated_data) for image in list(images): m2 = ArticleImages(article=articlefinal, images= image) m2.save() return articlefinal But i am getting an error that is saying articlea = Article.objects.create(**validated_data) NameError: name 'validated_data' is not defined Does anybody know why? -
Query in query in django?
I'm trying to achieve a query but I'm just unable to do it. I have 3 entities here: Clients: class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) Courses: class Course(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" name = models.CharField("Nombre del curso", null=False, default="", max_length=200) Consumptions: class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) course = models.ForeignKey(Course, verbose_name=("Curso"), null=True, default=None, on_delete=models.SET_DEFAULT) I want to get a list with the 10 most sold courses for the client that visit the page. I want to show the client the name of the course and the number of consumptions that he has done with that course. In every consumption there is a course and a client associated. Could someone give me a hand? -
How to create two object instances from two different models with a single POST request?
I am learning the Django-Rest Framework. I want to create an object instance for both my Story model and my File model with a single post request. So the incoming data contains a title and a file. I want then to create a story object with a title and the image field contains a reference (fk) to the id of the file instance. In the File model a own instance of File is created with the incoming file data. # File Model class File(models.Model): file = models.FileField(upload_to='audio_stories/', null=True, default='some_value') # Story Model class Story (models.Model): title = models.CharField(max_length=100,blank=True) image = models.ForeignKey(File,on_delete=models.CASCADE, blank=True, default=None) # Story Serializer class StoryCreateUpdateSerializer (serializers.ModelSerializer): image = serializers.FileField() class Meta: model = Story fields = ('title','image') def create(self, validated_data): image = validated_data.pop('image') title = validated_data.pop('title') image_instance = File.objects.create(file=image) story_instance = Story.objects.create(title=title, image=image_instance) return story_instance # File Serializer class TestFileSerializer (serializers.ModelSerializer): class Meta: model = File fields = ('__all__') If I send the formdata via Postman to my server it responses with "image": ["This field is required."]. If this is an obvious mistake, I apologize in advance. I am grateful for any clarification. -
Django - Implement "Remember me" after login
Could you please point me to the right direction of how to implement Remember me in my website. I read a couple of articles of how to implement but i'm more confused than point me to the right direction. I've configured the following: forms.py first_name = forms.RegexField(regex=r'^[a-zA-Z]+$', max_length=30, label=_("first name"), error_messages={'invalid': _("Wrong First Name, use only letters")}) last_name = forms.RegexField(regex=r'^[a-zA-Z]+$', max_length=30, label=_("last name"), error_messages={'invalid': _("Wrong Last Name, use only letters")}) email = forms.EmailField(required=True) remember_me = forms.BooleanField(required=False) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] views.py def loginPage(request): if request.user.is_authenticated: return redirect('index') else: if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') remember_me = request.POST.get('remember_me') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('index') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'members/login.html', context) login.html <div class="form-group custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="remember_me" id="remember_me"> <label class="custom-control-label" for="remember_me">Remember me</label> <a class="tdu btn-fpswd float-right" href="#">Forgot Password?</a> </div> Of course above code doesn't work. Thank you! -
Factory Boy: how to set conditional SubFactory() attribute depending on params
I got a Customer model which is related to a Company model. I'd like to give my factory the possibility to use a given company (if I need several customer from the same company). I thought to use the inner class Params to achieve that, but I got an issue using LazyAttribute and SubFactory together. Here is my factory: class CustomerFactory(UserFactory): """ To be valid, customer needs to belong to one of these groups: - manager - regular This can be achieved using the `set_group` parameter. Example: manager = CustomerFactory(set_group=manager_group) """ @lazy_attribute def _company(self): if self.use_company: return self.use_company else: return SubFactory('rdt.tests.factories.CompanyFactory') class Meta: model = Customer class Params: use_company = None @post_generation def set_group(self, create, extracted, **kwargs): if extracted: self.groups.add(extracted) I thought to use the factory as: c1 = factories.CustomerFactory(use_company=my_company) c2 = factories.CustomerFactory() I got ValueError. It seems I can't get the parameter value 'use_company' in the factory. Anyway my factory throws a ValueError. -
DRF-extensions queryset use select_related,show different sql result,
I try to use DRF-extensions for the caches. but same queryset ,Will produce different sql query time, my code: view.py queryset = Users.objects.select_related('location', 'status', 'department', 'position', 'payper') no DRF-extensions# # # # # # # # # # # # # # # # # # # # def list(self, request, *args, **kwargs): result: use DRF-extensions# # # # # # # # # # # # # # # # # # # @cache_response(timeout=60 * 60, key_func=StaffListKeyConstructor()) def list(self, request, *args, **kwargs): result: is this a bug ?How can i fix it, thanks -
Return nested JSON from Models with relations in Django
models.py (simplified) class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_books(self): return Book.objects.filter(author=self.pk) class Book(models.Model): name = models.CharField(max_length=255) pages = models.IntegerField() author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return f'{self.name} from {self.author}' class Paragraph(models.Model): name = models.CharField(max_length=255) book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f'{self.name} from {self.book}' I want to return all the instances in a json file with this structure: [ { "name": 'Dumas', "books": { "name": "The count of Montecristo", "paragraphs": { "name": "paragraph_name_1", }, { "name": "paragraph_name_2", }, { "name": "The three Musketeers", "paragraphs": { "name": "paragraph_name", }, ] What I tried: serializers.py class AuthorSerializer(serializers.ModelSerializer): books = serializers.CharField(source='get_books', read_only=True) class Meta: model = Author fields = ['name', 'books'] This add the books key but the value is the string representation of the istances of Book (of course), how I make the value being the serialized istances of Book? I have created a BookSerializer. Notes: I know that I can created a nested json by creating a serializer for Paragraph with depth = 2 but this will include fields I don't want (like pages in Book) and the json structure will be totally different. -
How to Render Django ForeignKey relation on Datatables Serverside
Im stuck for days, im using plugin django-datatables-view and I need to render ForeignKey related value in serverside datatables, it's like: {{data.pasien_id.name}} in typical django template. but that way not work with serverside datatables, and there is no documentation anywhere to achieve that. the code shown below. Models.py class Pasien(models.Model): nama = models.CharField(max_length=40, null=True) class Log_book(models.Model): pasien = models.ForeignKey(Pasien, on_delete=models.PROTECT, null=True) Views.py class logbook_json(BaseDatatableView): model = Log_book columns = ['id', 'pasien_id'] order_columns = ['id','pasien_id'] def render_column(self, row, column): if column == 'id': return escape('{0}'.format(row.id)) else: return super(logbook_json, self).render_column(row, column) def filter_queryset(self, qs): filter_customer = self.request.GET.get('search[value]', None) if filter_customer: customer_parts = filter_customer.split(' ') qs_params = None for part in customer_parts: q = Q(id__icontains=part) | Q(pasien_id__icontains=part) qs_params = qs_params | q if qs_params else q qs = qs.filter(qs_params) return qs templates.html datatables load, <script class="init" type="text/javascript"> $(document).ready(function () { $('#responsive-datatablex').DataTable({ // ... searching: true, processing: true, serverSide: true, stateSave: true, "ajax": "{% url 'logbook_json' %}", }); }); </script> -
Why after moving a .js script from html to .js file, it does not load the values?
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code: $("#id_subtag-tags").change(function () { var tagId = $(this).val(); // get the selected tag ID from the HTML input console.log(tagId); $("#displaytags").html(''); $.ajax({ // initialize an AJAX request url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/) data: { 'tags': tagId // add the tag id to the GET parameters }, success: function (data) { // `data` is the return of the `load_subtags` view function $("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server } }); }); There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug. The error I receive is: GET failed, ajax_load_subtags 404 (Not Found), url.py: path('myapp/post/ajax/ajax_load_subtags', load_subtags, name='ajax_load_subtags'), -
generate client_secret for sign in with apple using python 2.7 and django 1.9, giving me " JWSError: Could not deserialize key data"
login.py how i geberate client secret def generate_apple_client_secret(): secret = settings.SOCIAL_AUTH_APPLE_PRIVATE_KEY year = new_date_time.now().year month = new_date_time.now().month day = new_date_time.now().day now = int(datetime.datetime(year, month, day).strftime('%s')) headers = {"alg": 'ES256', "kid": settings.SOCIAL_AUTH_APPLE_KEY_ID} claims = { "iss": settings.SOCIAL_AUTH_APPLE_TEAM_ID, "iat": now, "exp": now + int(datetime.timedelta(days=180).total_seconds()), "aud": "https://appleid.apple.com", "sub": settings.CLIENT_ID } client_secret = jwt.encode( headers=headers, claims=claims, key=secret, algorithm='ES256' ) return client_secret Internal Server Error: /ar/api/social-login/ Traceback (most recent call last): File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 285, in post user = self.login_with_apple(ser.instance.token) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 474, in login_with_apple client_secret = generate_apple_client_secret() File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 649, in generate_apple_client_secret headers=headers, claims=claims, key=secret, algorithm='ES256' File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jwt.py", line 64, in encode return jws.sign(claims, key, headers=headers, algorithm=algorithm) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jws.py", line 50, in sign signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key) File "/home/omar/PycharmProjects/Aswaq/venv/local/lib/python2.7/site-packages/jose/jws.py", line 172, in _sign_header_and_claims raise … -
Bitbucket-Pipeline: How to automatically build and deploy a Django app docker image to Heroku or VPS
I'm new to docker and bitbucket pipelines so things a bit confusing at the moment when it comes to the practical implementation. I am looking for an existing walk-through (in a forum, book, article etc) about: "Bitbucket-Pipeline: How to deploy a docker image to Heroku" or, even better a source dealing with: "step by step: how to dockerize and deploy your django app via bitbucket pipelines to heroku and vps" I found one online using "Springbook" link and a shell script but I couldn't generalise it into django and docker-compose. Some posts say you cannot use docker-compose in bitbucket, and do I need to use a shell script? Any type of help or direction would be much appreciated at this stage of learning. -
Uncaught TypeError: $(...).select2 is not a function--Slect2 not working
I have include below listed js file in the head tag on an html page(index.html), after loading that page on a button click I append an html page to the current page(index.html) which contain an select box. but when i call select2 in his appended page am getting below error, Uncaught TypeError: $(...).select2 is not a function Please help to sove the issue. <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="{% static 'reports/assets/plugins/bootstrap/popper.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/chartjs/chart.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/apexcharts/dist/apexcharts.min.js' %}"></script> <script src="{% static 'reports/assets/plugins/toastr/toastr.min.js' %}"></script> <script src="{% static 'reports/assets/js/lime.min.js' %}"></script> <script src="{% static 'reports/assets/js/pages/dashboard.js' %}"></script> <script src="{% static 'reports/assets/js/chart.js' %}"></script> <script src="{% static 'reports/assets/js/pages/charts.js' %}"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.18/af-2.3.0/b-1.5.2/b-colvis-1.5.2/b-flash-1.5.2/b-html5-1.5.2/b-print-1.5.2/cr-1.5.0/fh-3.1.4/r-2.2.2/datatables.min.js"></script> <!-- needed to use moment.js for our date sorting--> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <!-- <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js" ></script> --> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" ></script> <script src="{% static 'js/form_validate/jquery_validate.js' %}"></script> select2 initialized in the appended page, $(document).ajaxComplete(function() { $("select").select2(); }); Also this iisue was not there when am using select box directly in the main page itself. -
How to display a single form with Foreign Key and choices in a Django Form?
My goal is display a form with all theses fields, I'm stuck to display city and description field from City model, the first one needs to display a select box with all cities choices and the other just a text field. So, I need to display a form with this format: city (With selected box from all choices) description date status CITIES_CHOICES = (('RJ', 'Rio de Janeiro'), ('NY', 'New York'), ('PIT', 'Pittsburgh')) class City(models.Model): city = models.CharField(max_length=50, choices=CITIES_CHOICES) description = models.TextField() def __str__(self): return self.city class Checkin(models.Model): destination = models.ForeignKey(City, on_delete=models.SET_NULL) date = models.DateTimeField() status = models.BooleanField() I had create a form using Modelform but how can I display the fields from City model instead display de city object properly? Any idea where I need to go now? forms.py class DocumentForm(forms.ModelForm): class Meta: model = Checkin -
Use Prometheus next to Django and Gunicorn socket
I've deployed a Django project using gunicorn and Nginx following the Digital Ocean tutorial. Now, I'm trying to add Prometheus to monitor the performance of my application, but I'm not sure how to access the /metrics endpoint because using as a target ['localhost/metrics'] or ['localhost:8000/metrics'] values does not work. Can anyone help me, please? -
How to filter dates by range in Django Admin
class ExampleFunction(admin.ModelAdmin): list_display = ('user', 'date', 'task') list_filter = ('date',) The problem is that the builtin date filter don't let me insert a custom date, just pick some preset values like: Today, Last 7 days, ... -
Why did my Django app stop building in App Engine environment
Recently my app's deployment has stopped building and I cannot figure out why. My app is a simple app that does some calculations, I've followed deployment instructions and have the same settings from GC tutorial here. I am successfully pushing deployments but I think it is not building and launching Django. I have the Cloud Build API enabled. Any ideas on troubleshooting this would be appreciated -
I am facing issue to check answer and update user score card. my question(Objective or Descriptive type)
I am rendering one by one question from DB and using pagination for next(skip). In this model in add question ,customer and attempt question. Scoreboard models is class QuizTakers(models.Model): customer = models.ForeignKey(User, verbose_name=_("Customer"), null=True, on_delete=models.SET_NULL) questions = models.ForeignKey(Questions, verbose_name=_("Question"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("quiz"), on_delete=models.CASCADE) attempt = models.PositiveIntegerField() total_correct = models.PositiveIntegerField() question_type = models.TextField(blank=True) flag_question = models.TextField(blank=True) create_date = models.DateTimeField(_("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField(_("Last update timestamp"), auto_now=True) question quiz view is: Maybe I am doing wrong in my view file because when i hit on post request then quiz page refresh and question start again.Please advise how to check every pagination next on answer and update on score board. def Quizsession(request): quiz = Quiz.objects.get(pk=request.session['quiz']) queries = [Q(topics__id=value.id) for value in quiz.topic.all()] query = queries.pop() for item in queries: query |= item ques_query = Questions.objects.filter(query).order_by('?')[:quiz.no_of_question] questions = ques_query count=questions.count() # PAGINATION =============================== page = request.GET.get('page', 1) paginator = Paginator(questions, 1) try: questions = paginator.page(page) except PageNotAnInteger: questions = paginator.page(1) except EmptyPage: questions = paginator.page(paginator.num_pages) context={ 'object_list': questions, 'page_obj': questions, 'count': count } if request.method =='POST': return redirect(reverse_lazy('forntend_panel:customer_quiz_start')) return render(request, 'test.html', context) -
Django-oscar manage users via dashboard
I'm not able on a fresh project with django-oscar to manage users using the dashboard(editing/deleting) - as superadmin I'm able only to see user details and also send reset password email. I didn't find any information about this. Also, I checked Django Oscar Dashboard User app and I don't see any view for this purpose. It's an easy way to handle editing/deleting users via the oscar dashboard? I can see the solution as creating a custom view for that but then I think having it just in the Django Admin will more efficient :) -
Authentication Creditial were not provided error in Django
I'm pretty new in django, especially django rest framework. so i tried to follow some instruction in the internet. but when I test it using Postman, it gives an error that says "detail": "Authentication credentials were not provided." in the json file. so what did I do wrong to be exact? -
Django : Type Error 'NoneType' object is not subscriptable
im making a product checkout page and im trying to access my cart items from the following util.py file. I have seen that lot of sites saying that the 'NoneType' object is not subscriptable error, means that i attempted to index an object that doesn't have that functionality. But i cant figure out what is wrong. The error occurs in the cartData function views.py from .utils import cartData def checkout(request): #call method from utils.py data =cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = { 'items': items, 'order': order, 'cartItems': cartItems } return render(request, 'store/checkout.html', context) utils.py def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] for i in cart: # check if product exists try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'product': { 'id': product.id, 'name': product.name, 'price': product.price, 'imageURL': product.imageURL, }, 'quantity': cart[i]['quantity'], 'get_total': total } items.append(item) if product.digital == False: order['shipping'] = True except: pass return{'cartItems': cartItems, 'order': order, 'items': items} def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, … -
Filter unique data in Django
Im having a trouble how to filter unique value in Django, let say I have this data from my database and I just want to filter the unique value Expected output should like this, and to filter this data to my select option China Denver Manila Tokyo Japan Usa Australia Brazil views.py def sample(request): country= Country.objects.all() formats = {'filter':country} return render (request,'sample.html',formats ) Is there any expert know about this? -
How to get and return a model instance by id using Django ModelForm when there is too many instances?
I have a ModelForm for an Inline and I am trying to accept an id of an instance and then get the instance and 'return it to the field' as the field is a ForeignKey field. I cannot use (Model)choicefield as there are thousands of instances which means it takes ages to load. Neither I can take for example a slice of the most recent objects and choose from those as it results in a cannot filter the queryset once a slice has been taken error. I have tried working around with the save method but I couldn't make it so far. (but it is my bet that this will be the way to go) I would like the form to take three ids and then get those instances by model.objects.get(id=id) and then somehow create a new instance. the code looks as follows; class AgregatorCrossSaleProductForm(forms.ModelForm): IsShown = forms.BooleanField(required=False) ParrentProductId = forms.IntegerField() ChildProductId_id = forms.IntegerField() CrossSaleProductTypeId = forms.IntegerField() class Meta: model = AgregatorCrossSaleProduct exclude = [] class AgregatorCrossSaleProductInline(admin.TabularInline): model = AgregatorCrossSaleProduct form = AgregatorCrossSaleProductForm ... Any tip would be much appreciated. Thank you in advance -
AttributeError 'tuple' object has no attribute 'get'
I have a Django application. But i have an error which i have been struggling with for some time now. Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response Traceback django has provided me : File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\ProgramData\Anaconda3\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: My View File : https://hasteb.in/ayafusug.py -
Cannot assign "<Customer: Customer object (2)>": "Order.customer" must be a "Product" instance
I am building an e-commerce website using django.Whenever i try to fill the checkout form and submit the form it shows me this error: "Cannot assign "<Customer: Customer object (2)>": "Order.customer" must be a "Product" instance." I am really confuse here I got stuck here Here is my Views.py for checkout : class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) #print(fname, phone, address, products, cart, customer) for product in products: order = Order(customer=Customer(id=customer),product=product,fname=fname, price=product.price,phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart') Here is my Models.py: from django.db import models import datetime # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name @staticmethod def get_categories(): return Category.objects.all() class Brand(models.Model): name= models.CharField(max_length=100) def __str__(self): return self.name def get_brands(): return Brand.objects.all() class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default='UNCATEGORIZED') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default='NoBrand') price = models.FloatField() @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_products_by_category(category_id): if category_id: return Product.objects.filter(category=category_id) else: return Product.get_all_products() @staticmethod def get_brands_by_products(brand_id): if brand_id: return Product.objects.filter(brand=brand_id) else: return Product.get_all_products() @staticmethod def get_products_id(ids): return Product.objects.filter(id__in=ids) class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100, default=1) … -
Why js script does not load ajax response? [duplicate]
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code: $("#id_subtag-tags").change(function () { var tagId = $(this).val(); // get the selected tag ID from the HTML input console.log(tagId); $("#displaytags").html(''); $.ajax({ // initialize an AJAX request url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/) data: { 'tags': tagId // add the tag id to the GET parameters }, success: function (data) { // `data` is the return of the `load_subtags` view function $("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server } }); }); There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug. The error I receive is: GET failed, ajax_load_subtags 404 (Not Found),