Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: save() missing 1 required positional argument: 'self' in djjango
my code: from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): print("usernmae taken") elif User.objects.filter(email=email).exists(): print("email taken") else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) User.save(); print("user created") else: print("passwords not matching") return redirect('/') else: return render(request,'register.html') my console log: File "E:\coding\fyp\travel\accounts\views.py", line 21, in register User.save(); TypeError: save() missing 1 required positional argument: 'self' [05/Apr/2020 11:49:59] "POST /accounts/register HTTP/1.1" 500 69154 E:\coding\fyp\travel>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 05, 2020 - 11:52:09 Django version 2.2.5, using settings 'travel.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ignore lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll -
RelatedObjectDoesNotExist: User has no seller
Here I am trying to save the Seller into the Order model after a Customer places a successful order. As the logged in User is a Customer so it shows RelatedObjectDoesNotExist: User has no seller. But I want to save the Seller after a Customer places an order, so that the Seller can be notified that the Seller has a new order. But in the Order Model where seller = models.ForeignKey(Seller, blank=True, null=True, on_delete=models.CASCADE), here it doesn't save the seller. 'cart views.py` def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart:cart') login_form = CustomerLoginForm() signin_form = CreateCustomerForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) address_qs = None customer = request.user.customer seller = request.user.seller if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj, customer, seller) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = "" del request.session['cart_id'] return redirect("cart:success") context = { 'object':order_obj, 'billing_profile':billing_profile, 'login_form':login_form, 'signin_form': signin_form, 'address_form':address_form, 'address_qs': address_qs, } return render(request, 'cart/checkout.html', context) accounts models.py … -
How do I make Django CRUD front-end easy to use like WordPress? Are there any libraries or plugins?
we are trying to create a crowdsourced open database on the temple. We have started using Django as the backend. One issue we have is the frontend where users will contribute is not as easy as WordPress. For example, while entering tags a popup opens when you want to create new(Whereas WordPress automatically cerates). Same with Images. Uploads one by one. So is there a frontend plugin or addition which will make it more user friendly. -
no such table: main.auth_user__old while saving tables in the section area
I am following the net ninja tutorial for Django and I ran into this problem in the admin section while saving the tables in the admin section area. -
How to bind form in Django when it has others parameters
I'm trying to perform .is_valid() after a POST request with my form. form = DrinkForm(request.POST) Like this, the "problem" is that this form has other parameters. forms.py: class DrinkForm(forms.Form): def __init__(self, language, account_id, configurations, *args, **kwargs): super(DrinkForm, self).__init__(*args, **kwargs) translation.activate(language) With this, I don't know how to make my form bound (and I can't find any guide or example about this case). When I print my form called in view with its regular parameters it's everything ok, but if I add request.POST I get nothing. form_ok = DrinkForm('english', request.session['account_id'], configurations) # OK form_not_ok = DrinkForm(request.POST) # Needs parameters form_how_to = DrinkForm('english', request.session['account_id'], configurations, request.POST) # How to? -
How to implement an object specific modal in Django?
I'm new to Django and I have a problem moving my stuff to the front end of my website. I want to do fantasy-style website. My main page will display a list of NHL players. These players will be picked by the user and added to their team in order . My problem is this: I want a popup-style modal to open when a user clicks a player on the main page. This modal would contain a confirmation before this specific player is added to the user's team. Here is my player model: class Player(models.Model): name = models.CharField(max_length=30) position = models.CharField(max_length=5) Here is my main page view: def main_page(request): players = Player.objects.all() my_dict = {"players":players} return render(request, 'my_app/main_page.html', context=my_dict) Here is my template for the main page: {% extends "my_app/base.html" %} {% block body_block %} <button onclick="document.getElementById({{player.name}}).style.display='block'" class="w3-button w3-black">Open Modal</button> <div class="w3-modal-content"> <div class="w3-container"> <span onclick="document.getElementById({{player.name}}).style.display='none'" class="w3-button w3-display-topright">&times;</span> <p>{{player.position}}</p> </div> </div> {% for player in players %} <tr> <th>{{player.name}}</th> <th onclick="document.getElementById({{player.name}}).style.display='block'" class="w3-button w3-black" width="100%">Open Modal</th> </tr> {% endif %} {% endblock %} As you can see, I would like the modal popup to display the player's position. Unfortunately, not only is the modal not working, I have no clue how … -
Advance String/JSON formatting using a multilevel JSON/dict/Template in python
I want to replace text in 1 JSON using the keys mapped from a second json. Both the JSONs are dynamic and first JSON can be modified to use keys from second JSON. text_to_replace = json.dumps([{"type": "data", "layerName": "THIS IS Mohit", "property": "Source Text", "expression": "time > 4 ? 'This is {groom.first_name}' : 'This is {groom.first_name}'", "composition": "01 Oliver"}, {"type": "data", "layerName": "THIS IS {bride.first_name}", "property": "Source Text", "expression": "time > 4 ? 'This is Aashi' : 'This is {bride.first_name}'", "composition": "02 Amelia"}, {"type": "data", "layerName": "January 2020", "property": "Source Text", "expression": "time > 4 ? '21st January 2021' : '21st January 2021'", "composition": "03 November"}, {"type": "data", "layerName": "JANUARY 2020", "property": "Source Text", "expression": "time > 4 ? '21st January 2021' : '21st January 2021'", "composition": "02 Date"}]) context = {'function_list': [ {'name': 'Xbbd', 'venue': 'Xbxb\nXnx', 'time': '06:00 AM', 'date': '19th April 2020', 'date_d_m_y_hyphen': '19-Apr-2020', 'timestamp': 1587234600.0, 'date_hindi': '19 अप्रैल 2020', 'date_hindi_A': 'रविवार', 'date_hindi_B': 'अप्रैल', 'effective_date': '19th Apr 2020', 'effective_day': 'Sunday', 'effective_time': '06:00 AM Onwards', 'effective_month': None}], 'primary': {'first_name': 'Bride Name', 'last_name': 'Gshs', 'fathers_name': 'Sbsb', 'mothers_name': 'Bsb', 'grand_fathers_name': 'Sbdb', 'grand_mothers_name': 'Sb', 'effective_name': 'Bride Name Gshs', 'effective_parents_message': 'Daughter of \nSbsb & Bsb', 'effective_grand_parents_message': 'Grand Daughter of \nSbdb & Sb'}, 'secondary': … -
Issue with Hiding Django SECRET_KEY Using environment variables
I am running my programs and Django Project on an AWS EC2 Ubuntu instance in a virtual environment. The django project is run on an apache server. For purposes of this question I will say that my secret key is 'AAAA'. I have an environment variable set ("SECRET_KEY"). It is properly setup, and when I put: import os print(os.environ['SECRET_KEY']) in the python shell, it prints the proper secret key, AAAA. Therefore, I know python is able to access the proper environment variable. In settings.py, when SECRET_KEY='AAAA', the project works, and everything executes properly. However when I change this to: SECRET_KEY=os.environ['SECRET_KEY'] the server doesn't work (500 Internal Server Error). Everything seems like it should work. Any suggestions or ideas on what I missed here? -
using a property method in list_filter in custom admin
I have a model like this: class CustomUser(AbstractUser): @property def is_paid(self): return self.apayment4thisuser.all().filter(expirydate__gt=timezone.now().date()).count()>0 in the customadmin I am able to add this under my list display, but it is throwing error when I add it to my list filter: class CustomUserAdmin(UserAdmin): model = CustomUser list_filter = ['app_user','is_paid'] list_display = ['id', 'username', 'email', 'is_paid', ] This is the error: ERRORS: <class 'users.admin.CustomUserAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'is_paid', which does not refer to a Field. I was wondering is there not any way to add this to list_filter? Thanks, -
Some of my tests are not running ok if I do it with Docker in Django Rest Framework
I have been developing a project without Docker, and I have integrated and to make sure everything is ok I have run my tests. It shocked me, almost half of my tests are not running ok. Most of them are testing detail api views. I will post the codes below. Please let met know if you can find something missing or hidden)) [This is the Sample Project] models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.CharField(max_length=255) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name serialisers.py class BookSerializers(ModelSerializer): class Meta: model = Book fields = ('id', 'name', 'author') views.py class BookListApiView(ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializers permission_classes = [AllowAny, ] class BookCreateApiView(CreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializers permission_classes = [AllowAny, ] class BookRetrieveUpdateDeleteView(RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializers permission_classes = [AllowAny, ] tests.py LIST_BOOK_API_URL = reverse('book:list') CREATE_BOOK_API_URL = reverse('book:create') DETAIL_BOOK_API_URL = reverse('book:detail', kwargs={'pk': 1}) class TestBookApiView(TestCase): def setUp(self): self.client = APIClient() def test_create_book_through_api(self): payload = { 'name': 'this is book', 'author': 'test author' } res = self.client.post(CREATE_BOOK_API_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) def test_listing_book_through_api(self): Book.objects.create( name='test', author='testing', ) res = self.client.get(LIST_BOOK_API_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertContains(res, 'test') def test_retreiving_book_through_api(self): Book.objects.create( name='test', author='testing', ) res = self.client.get(DETAIL_BOOK_API_URL) print(DETAIL_BOOK_API_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) urls.py [for book app] … -
Django AJAX - HttpResponse goes to new page
I'm using AJAX for the first time and I'm having an issue with what happens after the AJAX request. AJAX/JS code $('#post_form').on('submit', function(event){ updatePost(); }); function updatePost() { $.ajax({ url : this.href, type : "POST", data : { title : $('#id_title').val() , content : $('#id_content').val()}, dataType: "text", success : function(json) { console.log(json); editPost(); } }); }; Django View Code: if request.method == 'POST': post.title = request.POST.get('title') post.content = request.POST.get('content') post.save() return HttpResponse(json.dumps({'title' : post.title, 'content' : post.content}), content_type = "application/json") So, the code works and it reaches the view and does what I need it to do up to that point. However, instead of the HtppResponse being 'sent' to the AJAX success function it instead redirects the user to a blank page containing the JSON created in the Django view. -
Django channels websocket reconnect
I am building a messaging system in Django, using web-socket to receive the message. Here is my tryouts, from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("receive", event) message = event['text'] obj = await self.create_obj(message=message) print('Created...') async def websocket_disconnect(self, event): print("disconnected", event) @database_sync_to_async def create_obj(self, **kwargs): obj = ChatMessage.objects.create(message=kwargs['message']) return obj When I start a client app the web-socket is connected, and i can receive the message and i am able to store into the DB. connected {'type': 'websocket.connect'} WebSocket CONNECT /ws/message [192.168.0.101:50148] After some idle time, the web-socket disconnects automatically, Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at /Users/ajay/Desktop/workspace/projects/python/django/websock/venv/lib/python3.7/site-packages/channels/sessions.py:183> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x10b311510>()]>> for connection <WebSocketProtocol client=['192.168.0.101', 50148] path=b'/ws/message'> took too long to shut down and was killed. After disconnects, i am not able to receive the message, when i reload the client, web-socket is connected, is there any way to reconnect the we-socket automatically with out reloading the client. I request to guide me some suggestion to achieve this, it will be very helpful for me, Thanks in advance. -
Redirect from view function to DetailView
This example shows how to add forms dynamically to a formset. I wonder if the case #3 can be modified like so: I'd like to handle the Book creation by generic CreateView, after that proceed to the Author creation, which will be handeled by the view below and redirected to the DetailView after Author is created. Below is what I have so far. class BookCreateView(CreateView): model = Book form_class = BookModelForm success_url = reverse_lazy('store:create_book_with_authors') class BookDetailView(DetailView): model = Book context_object_name = 'book' def create_book_with_authors(request): template_name = 'store/create_with_author.html' if request.method == 'GET': bookform = BookModelForm(request.GET or None) formset = AuthorFormset(queryset=Author.objects.none()) elif request.method == 'POST': bookform = BookModelForm(request.POST) formset = AuthorFormset(request.POST) if formset.is_valid(): # here there is no point in saving the bookform since it was already saved by the CreateView, but I'm not sure how to reference to the previously saved Book instance. # book = bookform.save() for form in formset: author = form.save(commit=False) author.book = book author.save() return redirect(reverse('store:book_detail', kwargs={'pk':book.id})) return render(request, template_name, { 'formset': formset, }) -
NoReverseMatch Error in Django, can't pass id parameter
I'm trying to learn python / django but I keep running into this error when I try to add the ability for someone to be able to reply to an already existing entry on a website. It looks like I'm not passing anything for a parameter in a view but I can't figure out why as this same structure worked for another project I was doing from a book. (fyi this is my first post here, I've read a ton of other posts on this here and elsewhere and none of them have helped so far, sorry if any of this is dumb). Here's the error: Exception Type: NoReverseMatch at /instructors/instructors/1/ Exception Value: Reverse for 'new_inquiry' with arguments '('',)' not found. 1 pattern(s) tried: ['instructors/new_inquiry/(?P[0-9]+)/$'] urls.py: I'm getting the error from the last one, the 'new_inquiry' view url, but am including all just in case something could be related from django.urls import path from . import views app_name = 'instructors' urlpatterns = [ path('', views.index, name='index'), path('instructors/<int:instructor_id>/', views.inquiry, name='inquiry'), path('instructors/new_instructor/', views.new_instructor, name='new_instructor'), path('new_inquiry/<int:instructor_id>/', views.new_inquiry, name='new_inquiry'), ] views.py: Issue is with the new_inquiry function (I think). I just can't get it to pass the instructor_id parameter for some reason... from django.shortcuts … -
Celery Worker command 'method-wrapper' object has no attribute '__module__'
Currently trying to initiate a worker for my django app, unfortunately i'm receiving this error: PS C:\Users\User\Documents\Codes\highlightreel> celery -A highlightreel worker -l info Traceback (most recent call last): File "c:\program files\python38\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\program files\python38\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Program Files\Python38\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\program files\python38\lib\site-packages\celery\__main__.py", line 16, in main _main() File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 322, in main cmd.execute_from_commandline(argv) File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 495, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "c:\program files\python38\lib\site-packages\celery\bin\base.py", line 305, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 487, in handle_argv return self.execute(command, argv) File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 415, in execute return cls( File "c:\program files\python38\lib\site-packages\celery\bin\worker.py", line 223, in run_from_argv return self(*args, **options) File "c:\program files\python38\lib\site-packages\celery\bin\base.py", line 253, in __call__ ret = self.run(*args, **kwargs) File "c:\program files\python38\lib\site-packages\celery\bin\worker.py", line 253, in run worker = self.app.Worker( File "c:\program files\python38\lib\site-packages\celery\worker\worker.py", line 97, in __init__ self.on_before_init(**kwargs) File "c:\program files\python38\lib\site-packages\celery\apps\worker.py", line 93, in on_before_init trace.setup_worker_optimizations(self.app, self.hostname) File "c:\program files\python38\lib\site-packages\celery\app\trace.py", line 596, in setup_worker_optimizations app.finalize() File "c:\program files\python38\lib\site-packages\celery\app\base.py", line 538, in finalize _announce_app_finalized(self) File "c:\program files\python38\lib\site-packages\celery\_state.py", line 54, in _announce_app_finalized callback(app) File "c:\program files\python38\lib\site-packages\celery\app\__init__.py", line 59, in <lambda> lambda app: app._task_from_fun(fun, **options) File "c:\program files\python38\lib\site-packages\celery\app\base.py", line 452, in _task_from_fun '__header__': … -
how do I center the nav with 3 elements(lists) max in a row
I've tried multiple ways but couldn't center it without removing the padding This is what it looks like right now with my code: [1]: https://i.stack.imgur.com/sHEjj.png This is what it should look like: [1]: https://i.stack.imgur.com/yNiCz.png Thanks in advance! header nav ul { display: block; margin: 0 auto; width: fit-content; } header nav ul li { display: inline-block; float: left; list-style: none; padding: 10px 20px; } header nav ul li a { font-family: Segoe UI; color: #777777; font-size: 24px; } <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'movies' %}">Movies</a></li> <li><a href="{% url 'about' %}">About</a></li> {% if user.is_authenticated %} <li><a href="{% url 'my_account' %}">My Account</a></li> {% else %} <li><a href="{% url 'login' %}">Log in</a></li> <li><a href="{% url 'signup' %}">Sign up</a></li> {% endif %} </ul> </nav> -
Uploading multiple files in Django not working
I am trying to upload multiple files using Django. The idea is that while creating a blog post the user can also add images to the post. I am using Ajax to submit the blog post, however, it seems that after adding the image form the "submit" button doesn't work and my post those not get created. I have already built two models, Images and Post. Below are my codes related to this functionality. My project name is register and images are in an app called 'home': (If I remove the image upload functionality the post is created successfully, so the ajax is working correctly) my post_creat view in home app views: @login_required def post_create(request): data = dict() if request.method == 'POST': image_form = ImageForm(request.POST, request.FILES or None) images = request.FILES.getlist('image') form = PostForm(request.POST) if form.is_valid() and image_form.is_valid(): post = form.save(False) post.author = request.user post.save() for i in images: image_instance = Images(image=i,post=post) image_instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: image_form = ImageForm form = PostForm context = { 'form':form, 'image_form':image_form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my javascript code for handling the ajax request: $(document).ready(function(){ var ShowForm = function(e){ … -
Filtering Django View to a Specific Model Instance also written by the same User
This is probably a simple solution but its stumping me. Im new at Django and coding really. Thank you for you patience. I have a Profile model which is a OnetoOne relationship proxy model with an Abstract User. I use that to render a specific template choice with Profile Data. That works just fine. The problem comes in when I try to render the Inventory Model data which is also entered by the same user but is listed on a separate model and app. I am getting all of the Inventory when i list it which isn't surprising as I'm using a def get_context_data in the view with def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['profile'] = Profile.objects.all() context['inventory'] = Inventory.objects.all() return context I know the context['inventory'] is doing exactly what Im asking but i need it to filter to just the objects entered to the same items as entered by the user that made the Profile model .. and I am stumped. Both Models Below: class Profile(models.Model): """Additional User Profile info on a One to One relationship this tracks all the other info concerning the users and their websites.""" # TODO: Define fields here # add additional templates under templates/users. … -
Passenger support or documentation for Django >= 2.2
I am using a shared web host plan to deploy a Django-based website, the hosting service uses cPanel (version 86). I have successfully built the latest version of SQLite and set the LD_LIBRARY_PATH variable so that Python is actively using this version: $ python -c 'import sqlite3; print(sqlite3.sqlite_version)' 3.31.1 I have therefore no problem to run Django 2.2 and 3.0 projects on my server (eg. running python manage.py runserver in my virtual environment is running fine). I can also run python passenger_wsgi.py with no error. However, Passenger seems to fail to load the Django project as I get this error: I've searched the root of my server for this famous log file but did not find it, so I have no idea what the problem is. When uninstalling Django >= 2.2 and installing Django == 2.1.15 in the same virtual env, I get the proper Django page (eg. "The install worked successfully! Congratulations!"). So at this point it seems like the problem is coming from Passenger but I am clueless how-to configure it to be able to handle the latest Django versions. Any help appreciated! -
Specify settings file for Django deployment at GCP App Engine
Inside my Django project, my main app (where the settings.py file is located) is called "main/". But, I have deleted the settings.py file, now I have a directory called "settings/", and inside it, I have different configuration files, e.g., development.py, production.py, etc. How to specify which file Google Cloud Platform should use for my App Engine deployment? Thank you. -
Django Captcha Ask User To Enter The Next Letter / Number For Each Character Of Random / Specified Length Challenge
Code: def captcha_challenge(): challenge = u'' response = u'' for i in range(4): digit = random.randint(0,9) lower_upper_alphabet = string.ascii_letters random_letter = random.choice(lower_upper_alphabet) challenge += str(digit) response += str((digit + 1) % 10) return challenge, response This captcha code currently will display random 4 numbers and ask the user to enter the next number that comes after each number shown. Z would be A and single digit number 9 would be 0 Examples: Current Captcha shows: 1389 Current Solution: 2490 Desired Captcha Shows: 1zbg gua16k wd46ugcq32 Desired solution: 2ach hvb27l xe57vhdr43 My question is how do I get the captcha to show a random length challenge of 10 characters or less each page refresh with both letters and numbers? Where no matter what character is displayed, the user will have to enter the next letter or number that comes after that particular character to solve the captcha? -
ValueError Cannot query "customer1@gmail.com": Must be "Customer" instance
I am trying to save the customer to the Order Model, but the customer is not being saved, it shows customer1@gmail.com must be Customer instance. And also I want to save the seller to the Order model. Because, A product is related to a seller. When I order something, and after the order is saved, I should be able to see from which seller I bought that product from. But here I am not able to save the seller. cart views.py def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart:cart') login_form = CustomerLoginForm() signin_form = CreateCustomerForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) address_qs = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj, request) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = "" del request.session['cart_id'] return redirect("cart:success") context = { 'object':order_obj, 'billing_profile':billing_profile, 'login_form':login_form, 'signin_form': signin_form, 'address_form':address_form, 'address_qs': address_qs, } return render(request, 'cart/checkout.html', context) order models.py class OrderManager(models.Manager): def new_or_get(self, billing_profile, cart_obj, request): created … -
Searching class based views in Django
I'm trying to make a search option for my ecommerce app in Django. I'm using a ListView for showing my posts and paginate them: def search(request): qs = '' title_query = request.GET.get('q') if title_query != '' and title_query is not None: qs = qs.publicaciones.objects.filter(title__icontains=title_query) context = { 'queryset': qs, } class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 4 This is the relevant HTML: {% for q in queryset %} <div class="container"> <h1>{{ q.Título }}</h1> </div> <div class="container"> {{ q.Descripción }} </div> <div class="container"> <img class="item-img" src="{{ q.Fotos.url }}" width="250"> </div> {% endfor %} However, this codes just shows all the items, my goal is to filter them by the search obviously. It's also really strange that when I set the value for queryset to anything like 'foo', it will still display all the items. I'm compleatly lost. Any help would be appreciated. I already tried these, but didn't get any results: Django: Search form in Class Based ListView How to create a filter form for a (class based) generic object list in Django? -
html css file note displaying image using jinga format for django
my index.html: {% load static %} {% static "images" as baseurl %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css'%}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css'%}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %}"> <link rel="stylesheet" href={% static 'index.css"' %}> </head> <body> <div class="super_container"> <!-- Header --> <header class="header"> <div class="container"> <div class="row"> <div class="col"> <div class="header_content d-flex flex-row align-items-center justify-content-start"> <div class="header_content_inner d-flex flex-row align-items-end justify-content-start"> <div class="logo"><a href="{% static 'index.html' %}">Travello</a></div> <nav class="main_nav"> <ul class="d-flex flex-row align-items-start justify-content-start"> <li class="active"><a href="{% static 'index.html' %}">Home</a></li> <li><a href="{% static 'about.html' %}">About us</a></li> <li><a href="accounts/register">Register</a></li> <li><a href="{% static 'news.html' %}">News</a></li> <li><a href="{% static 'contact.html' %}">Contact</a></li> </ul> </nav> <div class="header_phone ml-auto">Call us: 00-56 445 678 33</div> <!-- Hamburger --> <div class="hamburger ml-auto"> <i class="fa fa-bars" aria-hidden="true"></i> </div> </div> </div> </div> </div> </div> <div class="header_social d-flex flex-row align-items-center justify-content-start"> <ul class="d-flex flex-row align-items-start justify-content-start"> <li><a href="#"><i class="fa fa-pinterest" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-twitter" … -
How to change order_by dynamically using django-tables2?
My table class looks pretty typical except that maybe it includes a before_render() function. What's great about before_render is that I can access self. This gives me access to dynamic information about the model I'm using. How can I access dynamic information (like from before_render) to change the order_by variable in the Meta class? def control_columns(table_self): # Changes yesno for all Boolean fields to ('Yes','No') instead of the default check-mark or 'X'. for column in table_self.data.table.columns.columns: current_column = table_self.data.table.columns.columns[column].column if isinstance(current_column,tables.columns.booleancolumn.BooleanColumn): current_column.yesno = ('Yes','No') class DynamicTable(tables.Table): def before_render(self, request): control_columns(self) class Meta: template_name = 'django_tables2/bootstrap4.html' attrs = {'class': 'custom_table', 'tr': {'valign':"top"}} order_by = 'index'