Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting an error 'MultiValueDictKeyError' at /store/AddProduct' . how do I solve it without using request.POST.get()
I am getting an error 'MultiValueDictKeyError' at /store/AddProduct' 'desc' in Django project. I search for the solution on the internet and I end up on request.POST.get() but I want to know why it giving me an error, I tried request.POST['desc'] before and it's work for my user login project. why now it's giving error here is my system info: Django Version: 3.0.4 Python Version: 3.8.2 here is view.py from django.shortcuts import render from .models import Gender, Category, SubCategory, Product, Company db_gender = Gender.objects.all() db_category = Category.objects.all() db_subCategory = SubCategory.objects.all() db_product = Product.objects.all() db_company = Company.objects.all() def add_product(request): if request.method == 'POST' : name = request.POST['name'] descp = request.POST['desc'] price = request.POST['price'] offer_valid = request.POST['offer_valid'] offer_value = request.POST['offer_value'] company = request.POST['company'] quantity = request.POST['quntity'] category = request.POST['category'] sub_category = request.POST['sub_category'] size = request.POST['size'] color = request.POST['color'] return render(request, 'checkout.html', {'db_category': db_category, 'db_subcategory': db_subCategory}) else: return render(request, 'checkout.html', {'db_category': db_category, 'db_subcategory': db_subCategory}) it's not showing error for name = request.POST['name'] & company = request.POST['company'][here is a image]1 but it's showing errror for all fields here is my checkout.html file i downloaded this template file from https://colorlib.com/wp/template/estore/ <section class="checkout_area section_padding"> <div class="container"> <div class="billing_details"> <div class="row"> <div class="col-lg-8"> <h3>Product Details</h3> <form class="row contact_form" … -
Django: Set cookie value by clicking url then use it in a view?
I would like the user to be able to click on a url in a drop down menu to select their store, have the selection data (store id) stored in a cookie, then use the data in the cookie to re-load the page. The page should load reporting for the selected store. Before the user selects the page will show data for the "default store". I'm thinking I need something like a "selected store" variable? The view builds an iframe and needs the store id as one of the parameters. My app has an organization model, when a user is created an organization is set for them. Organizations can have stores. models.py class Org(models.Model): name = models.CharField(blank=True, max_length=100) client_id = models.IntegerField() default_store = models.OneToOneField('Store', on_delete=models.SET_NULL, null=True,blank=True, related_name='+') def __str__(self): return self.name class Store(models.Model): name = models.CharField(blank=True, max_length=100) org = models.ForeignKey('Org', on_delete=models.CASCADE) store_id = models.IntegerField(null=True, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) org = models.ForeignKey('Org', on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() I'm using the below in my template to generate links for the stores that an org has. When the user clicks the link I … -
What is the Meaning Of '@' before A function In Python 3? [duplicate]
I searched for the meaning of @ when it comes before a function in Python and I couldn't find a helpful thing. For example, I saw this code in Django: @login_required ...and this in the goto-statement package: @with_goto What does it mean? -
scraping and graphing views over time
Context: I'm messing around in Django I have a working webscraper that can get the link, title and number of views from a youtube video, and add this information to an sqlite database. What id like to be able to do is run this say once every hour and be able to display a graph of the views over time. Right now I only have one table in my database, which may be fine for one video but im assuming if i want to track multiple videos id need a different model. My best guess for how to make this scale would be to have a table for just the videos i want to monitor and then each scraping event log the id of the video, the datetime and the views in another table. But if im scraping a bunch of videos data id be storing basically the same datetime every batch (as long as it takes less than an hour per batch) I would appreciate it if you could point me in the correct direction for the following issues: Is that two table data model correct/scalable enough? Easy way to do change over time math/ graph with the data? … -
Editable 'About us' page. Best approach?
I want the client to be able to edit their 'About us' page as they could with Wordpress. If I make a model named AboutPage just to hold the paragraph for the client to edit that would seem strange because then there could be multiple instances. I know you can overwrite the save method but I'm wondering if there's a better approach. -
Using variable in django queryset in a filter or empty the filter
Question 1. how could I use a variable in this queryset, def function(request): qset1 = BigTable.objects.values( 'deb_nr_f__dcountry__wcode_f__code', 'deb_nr_f__dcountry__wcode_f__code_name', ).filter(id_nr_f__ie_code__unomer_f__nomer=iteration_result, ) I mean something like that def function(request): x1 = 'id_nr_f__ie_code__unomer_f__nomer' qset1 = BigTable.objects.values( 'deb_nr_f__dcountry__wcode_f__code', 'deb_nr_f__dcountry__wcode_f__code_name', ).filter(x1 = iteration_result, ) Question 2. How can I empty the filter with a varianbe, so the the filter in the query does not filter the records. I mean something like that def function(request): x1 = 'id_nr_f__ie_code__unomer_f__nomer' x2 = True qset1 = BigTable.objects.values( 'deb_nr_f__dcountry__wcode_f__code', 'deb_nr_f__dcountry__wcode_f__code_name', ).filter(x1 = x2, ) Thank you. -
django_tables2 is not a register tag library error
I am trying to install django_tables2 but when I used it in the templates, it gives me this error: 'django_tables2' is not a register tag library. Any idea as to what is wrong. Installed app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tables2', options: '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', view.py: from .get_data import get_data from .tables import SummaryTable def get_variables(request): data = get_data() table = SummaryTable(data) context = {'table': table} response = render(request, 'index.html', context) return response templates: {% extends 'base_template.html' %} {% load django_tables2 %} {% load static %} <!-- HEAD --> {% block head %} {% endblock %} <!-- END HEAD --> {% block page_content %} {% render_table table %} {% endblock %} {% block scripts %} {% endblock %} -
how to inherit alternative constructor
hi stack overflow community. i am trying to inherit alternative constructor from my parent class and add one more argument in my alternative constructor in anthoer clss but i can't figure out how to do it. # Python Object Oriented Programming import datetime class Employee: num_of_emps = 0 # Class Variable raise_amount = 1.02 # Class Variable def __init__(self, FirstName, LastName, salary): self.FirstName = FirstName self.LastName = LastName self.salary = int(salary) self.email = FirstName + "." + LastName + "@email.com" Employee.num_of_emps += 1 # Class Variable def FullName(self): return "{} {}".format(self.FirstName, self.LastName) def apply_raise(self): self.salary = int(self.salary * self.raise_amount) @classmethod def set_raise_amount(cls, amount): cls.raise_amount = amount @classmethod def from_string(cls, emp_str): first, last, salary = emp_str.split("-") return cls(first, last, salary) @staticmethod def is_workday(day): if day.weekday() == 5 or day.weekday() == 6: return False else: return True class Developer(Employee): def __init__(self, FirstName, LastName, salary, prog_lang): super().__init__(FirstName, LastName, salary) self.prog_lang = prog_lang @classmethod def from_string(cls, dev_str): first, last, salary, prog_lang = dev_str.split("-") return cls(first, last, salary, prog_lang) -
passing Java script variable to Django
i wanna pass js var (tasks) to my django view as follow but out put is NONE. I've also tried tasks=request.POST('a[]') but it says that 'QueryDict' object is not callable. this is my html code: <head> <title> JavaScript | Set the value of an input field. </title> set value {% csrf_token %} click to set </p> <script> var a= ["Saab", "Volvo", "BMW"]; function gfg_Run() { var tasks = 2; $.ajax({ type: 'POST', url: 'main/momentconnections/bfp', data: {'tasks[]': tasks}, }); } </script> and this is my view: def testdel(request): if request.method == 'POST': tasks = request.POST('tasks[ ]') print("hello") print("count status ", tasks) print (type(tasks)) else: print('shit') return render(request, 'testdel.html') but out put for tasks is NONE. can anyone help me with this issue? -
How to assign ForeignKey value to the logged in user name in django?
I have two models NotesModel that has two fields userFromModel which is a one to one field to the django built in User model from django.contrib.auth.models , and a name field which is just a CharField and a Notes model that has several fields related to my notes app like title,matter etc, it also has a notesOf field that has ForeignKey relation with the NotesModel. when a user register/logins this Note app and try to add new note, i was expecting the notesof foreignkey field to have the value of registered/signed in username or say when person john sign in and create a new note,the i was able to create a new note object of Notes model,but the notesof field of the Notes model is not having the loggedin or say the person who created that note,i was expecting the forgienkey to have the person who is saving the note. views.py def newNotePage(request): form = NewNote user = request.user if request.method == 'POST': form = NewNote(request.POST) if form.is_valid(): obj = NotesModel.objects.get(userFromModel_id=user.id) #i tried this below code to create notesof field to the user obj.notes_set.create(notesOf=user) #but the result was empty see the attachment image form.save() return redirect('welcome') context={'form':form} return render(request,'todoapp/new_note.html',context) models.py … -
Python Django Admin not showing CSS
I was working with Django latest version by watching a tutorial on YT, but for some reason, my admin page isn't coming how it has to. It does not have a style or CSS. -
Django login button turned to be logout after user logged in
I want to create a button which can switch between login/out The button part on home.html: <li class="nav-item text-white"> {% if request.user.is_authenticated %} <a class="nav-link text-black font-weight-bold" href="{% url 'home' %}">Logout</a> {% else %} <a class="nav-link text-black font-weight-bold" href="{% url 'home' %}">Login</a> {% endif %} </li> But I have no idea how to set with my views.py as it only show logout on home.html def login_views(request): next = request.GET.get('next') form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, "login.html", context) def home(request): return render(request, 'home.html') -
How to return data from databse in Django?
BACKGROUND INFO Currently I am making a project in Django (Online system for students and teachers), I have finished frontend, but I have run into a problem with backend. So when I try to export data from one of the models, it returned none. CODE Relevant part of the models.py: from django.db import models class Ustanova(models.Model): skola = models.CharField(max_length = 10) programu = models.CharField(max_length = 50) slika = models.CharField(max_length = 1000) def __str__(self): return self.skola + '-' + self.program_u class Razred(models.Model): ustanova = models.ForeignKey(Ustanova, on_delete = models.CASCADE) programr = models.CharField(max_length = 50) razredr = models.CharField(max_length = 10) is_take = models.BooleanField(default = False) def __str__(self): return self.razred_r + '-' + self.program_r Relevant part of views,py: def _class_chooser(request, name): ustanova = get_object_or_404(Ustanova, skola = name) razred = Razred.objects.filter(razredr__startswith = name).all() context ={ "ustanova" : ustanova, "razred": razred, } url is in format: path('<str:name>/', views._class_chooser, name ="class_chooser"), So www.example.hr/students/XVG/ is page for students of XVG (class chooser page). And let's say that data is html file is represented with ul/li: <ul> {% for i in ustanova.razred_set.all %} <li><a href ="{% url 'students:class_menu' razred.razredr %}"> {{ razred.razredr}} - {{ razred.programr }}</a></li> {% endfor %} </ul> ISSUE Now we are coming to the issue, in … -
Django: Book name and image is not displayed
Base.html file. The could was properly working before bootstrap theme {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static '/books/style.css' %}" > <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'books:index' %}">The Bookstore</a> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Books </a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="{% url 'books:book-add' %}"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Add Book </a> </li> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> Logout </a> </li> </ul> </div> </div> </nav> {% block body %} {% endblock %} </body> </html> This is a index html file used to display book name and the name of the book is not displayed instead it displays {{book.name}} and not displaying book_image as well. The database is created and stored than too it is not displaying. index.html {% extends 'books/base.html' %} {% block body %} <link rel="stylesheet" href="books/style.css"> <div class=" col-md-12 jumbotron"> <h1>The Bookstore</h1> <p>Collection of all popular books</p> </div> <div class=" col-md-10 jumbotron jumbotron-special" name="fig"> <div class="col-md-12 span-2"> <h2>Popular Books</h2> </div> </div> <ul> {% for book in object_list … -
get updated object with ajax
get updated object with Ajax i get objects with Ajax but i need to update Objects before send zoomEstate = [] for foo in estate: if foo.lat >= lat - 0.1 and foo.lat <= lat + 0.1: if foo.long >= lng - 0.1 and foo.long <= lng + 0.1: username = {"username": foo.user.username} for i in username: setattr(foo, i, username[i]) foo.save() zoomEstate.append(foo) print(zoomEstate[0].username) estate_json = serializers.serialize('json', zoomEstate) estate_list = json.loads(estate_json) return HttpResponse(json.dumps(estate_list)) i can get updated object with print in view but after send i don't see username in template console -
Django ManyToManyField query equalivent to a list
I have a list of objects and a model includes ManyToManyField of this object. I'd like to get objects who have the same list of objects in this field. that's means __in won't work because he will do OR between the objects in the list and not AND. I was trying using the AND Q Lookup, but it didn't work (after checking the .query text, it seems that he doing the AND inside the field object, instead of the object itself, so obviously the field object id don't have two different ids..) here's the interceptor I played with results_query_set[0] <Results: Results object (2)> results_query_set[0].users.all() <QuerySet [<User: test_user>, <User: test_user_2>]> users [<User: test_user>, <User: test_user_2>] users_q <Q: (AND: ('users', <User: test_user>), ('users', <User: test_user_2>))> results_query_set.filter(users=users[0]) <QuerySet [<Results: Results object (2)>]> results_query_set.filter(users=users[1]) <QuerySet [<Results: Results object (2)>]> results_query_set.filter(users_q) <QuerySet []> results_query_set.filter(Q(users=users[0]) & Q(users=users[1])) <QuerySet []> and the result results_query_set.filter(users_q).query.__str__() reproduce is 'SELECT "results_table"."id", "results_table"."date", "results_table"."lookup", "results_table"."value" FROM "results_table" INNER JOIN "results_table_users" ON ("results_table"."id" = "results_table_users"."widgetresults_id") WHERE ("results_table_users"."user_id" = 1 AND "results_table_users"."user_id" = 2) I can chain .filter for each user, but of course, I'd like to make one query instead of queries by the numbers of my input. -
How to use video in django?
can anyone suggest me how to use video in django application? I tried different ways but didn't work. <source src="/home/sahil/Desktop/LearnHtmlCss/MyLearnHtml/media/DanceMonkey.mp4"type="video/mp4"> </video>``` even i used ```{% media 'DanceMonkey.mp4' %}``` I have setup my media files in seetings.py ```Media_Dir = os.path.join(BASE_DIR,'media') MEDIA_ROOT = [Media_Dir,] MEDIA_URL = '/media/'``` under my urls.py ```+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)``` -
Django Form ClassBasedView
I want to give context to template without form fill(if user only check a page).How can i make this views.py def ContactView(FormView): template_name = 'decision/residentialInteriors.html' form_class = EmailForm success_url = 'decision/residentialInteriors.html' success_message = "Письмо успешно отправлено" def form_valid(self, form, rmslg, stslg): email = form.cleaned_data['email'] send_mail('Caparol_Center_Spb', 'Теперь вы будете получать лучшие предложения шоу-рума', email, [email, ], fail_silently=False,) success_message = self.get_success_message(form.cleaned_data) if success_message: messages.success(self.request, success_message) Customer.objects.create(email=email, room=rmslg, style=stslg) all_rooms = Room.objects.all() selected_room = Room.objects.get(slug=rmslg) styles = selected_room.styles.all() style = Style.objects.get(slug=stslg) return redirect(reverse('decision/residentialInteriors.html', {"style": style, "all_rooms": all_rooms, "styles": styles, "selected_room": selected_room})) urls.py app_name = 'decision' urlpatterns = [ path('livingrooms///', ContactView.as_view(), name='style'), ] -
Django's Generic Relationship VS Django REST
In order to keep two of my Apps decoupled I'm wondering which one would be best approach. In one hand, I could try to implement this using Django's Generic Relationships or using Django REST and thus creating an API for each of those Apps. I'm really trying to grasp points positives and negatives for each aproach. Could someone contribute with thoughts? -
Associating user with List View Django Rest Framework
Making an app that displays tax deductions for logged in users. How do I display a list for deductions that specific user has created? This is what I've come up with so far but it only is a detail view. Can't seem to find any methods that allow this for class based views, so I'm assuming that this must be done with function based views. Please correct me if I am mistaken. views.py @api_view(['GET']) def api_list_deduction_view(request): account = request.user deduction = Deduction(author=account) if request.method == "GET": serializer = DeductionSerializer(deduction, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Deduction(models.Model): title = models.CharField(max_length=50, null=False, blank=False) description = models.TextField(max_length=5000, null=False, blank=False) amount = models.IntegerField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(null=True, upload_to=deduction_image_file_path) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How to setup celery as daemon
I am faced with necessity to setup celery as daemon for my django project on Ubuntu 16.04 server while doing it I met several misunderstandings which I will describe in my question. I know that by the rules of Stack asked should should ask only one clear question but I will ask several in one question because first question come from second etc. For tune celery as daemon I decide to use SystemD. In documentation Demonization celery provide a guide but it isn't so clear as I want maybe it's because I am beginner. My first question is: should I setup separately celery and celerybeat? Here is documentation provided example of configuration [Unit] Description=Celery Service After=network.target [Service] Type=forking User=celery Group=celery EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/opt/celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target All my misunderstandings relate to this piece of code and next question is: What user and group I should specify in Service part of configuration? in documentation example above celery specified for user and group but when I checked users … -
What's the difference between RabbitMQ and Pusher?
I'm building a django webapp where i need to stream some stock market trades on a webpage in real time. In order to do that, i'm searching for various approaches, and i found about Pusher and RabbitMQ. With RabbitMQ i would just send the message to RMQ and consume them from Django, in order to get them on the web page. While looking for other solutions, i've also found about Pusher. What it's not clear, to me, is the difference between the two, technically. I don't understand where would i use Rabbit and where would i use Pusher, can someone explain to me how are they different? Thanks in advance! -
Delete user when profile and Company has deleted
I have the following model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bedrijf = models.ForeignKey(Bedrijf, on_delete=models.CASCADE) class Bedrijf(models.Model): bedrijfsnaam = models.CharField(max_length=30, null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: n = Bedrijf.objects.create(bedrijfsnaam="Gaarne_bedrijfsnaam_instellen") n.save() Profile.objects.create(user=instance, bedrijf=n) I want to delete the User when Bedrijf has been deleted. With this config the profile will be deleted but not the User. What is the solution? -
Aggregate by max of another field
Hey I have a model named Visit. With fields date, person, id. I want to get all persons who do not have visits in last three months. Can you help me, please? What I have so far. Results are not what I wanted to see. visits_anotated = Visit \ .objects \ .only('id', 'date', 'person') \ .values('id', 'date', 'person') \ .annotate(latest_visit=Max('date')) \ .filter(latest_visit__lte=datetime.datetime.now() - datetime.timedelta(weeks=14)) -
how to check whether a user is logged in in django?
I know about request.user.is_authenticated() but i created a custom user(model) and created login page for it now how can we know if the user is logged in?