Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
too many redirect issue, if the URL doesn't end by slash
I'm working on a small project using Django Rest Framework, everything is going well, I have just a small issue about the URLs, if the user enters the URL in the browser without slash / at the end. he get redirected too many times to login page like that /login/login/login/login/login how can I fix that This is my code : from django.urls import path from list.api.views import ListView from rest_framework import routers router = routers.DefaultRouter() router.register(r'list', ListView, basename="list") urlpatterns = router.urls This is my settings.py : LOGIN_URL = 'account/login/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' -
jQuery autcomplete Django forms
I have integrated the jQuery autocomplete in Django and it works on the frontend side. The goal is to let users filter the data with the input. Is there any way to integrate jQuery-autocomplete with the django forms? If not, how hard is it to write the html code for the forms to connect it back to views.py? Is there any templates for such basic forms? (My only "form field" is a name) -
Django same username in different organizations
I am building an API with Django rest, and I am dealing with a situation where I have to authenticate users with the same username but in different organizations and I have no idea how to do it, any suggestions ?? I would be grateful. -
How can show the vendors againt the product id in django
At this time i am select the vendor through the category id, but i want to show the vendor against the product when i place the order. Then all vendor against that product should show, but i don't know how can i do that. Because without passing the product_id it's impossible.How can i pass the product id in place order button View.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): allOrder = OrderProduct.objects.all() categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') product = Product.objects.filter(category_id=categoryId) args = {'categories': categories, 'product': product, 'allOrder': allOrder} return render(request, self.template_name, args) def post(self, request): productobj = self.request.GET.get('SelectProduct') if productobj: messages.info(request, productobj) try: data = self.request.POST.get orderProducts = OrderProduct( product_id=productobj, description=data('description'), quantity=data('quantity'), ) orderProducts.save() return redirect('orderProduct') except Exception as e: return HttpResponse('failed{}'.format(e)) class All_Vendor(TemplateView): template_name = 'purchase/allVendor.html' def get(self, request, *args, **kwargs): try: categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') vendors = Vendor.objects.filter( vendorcategory__category_id__exact=categoryId ) args = {'categories': categories, 'selectedCategory': categoryId, 'vendors': vendors} return render(request, self.template_name, args) except Exception as e: return HttpResponse('failed{}'.format(e), 500) Template Order product {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} … -
How to fix the issue 'add_students_by_manager' object is not iterable
I am trying to display some data in my templates by passing it as context. I noticed that the problem actually has to do with outputting the result on the template. how can i fix this please. models.py class add_courses(models.Model): Course_Name = models.CharField(max_length=200, blank=True) student = models.ManyToManyField(add_students_by_manager, blank=True) def __str__(self): return self.Course_Name class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) def __str__(self): return self.student_name views.py def assignment_page(request): if request.method == "POST": get_course_name = request.POST.get('get_course_name') stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get) for all_stu_details in stu_course_all_stu: for stu_details in all_stu_details.student.all(): print(stu_details.student_ID) # THIS PRINTS OUT ALL THE student_id context3 = {"stu_course_all_stu": stu_course_all_stu} return render(request, 'assignment_page.html', context3) else: return redirect('/') assignment_page.html {% for m in stu_details %} <div class="card mb-3 ml-5" style="max-width: 840px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="/media/uploads/student_user.png" class="rounded profile-pic mt-2 ml-5 mb-2" alt="user" height="120" width="140"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">Student ID : {{m.student_ID}}</h5> <h5 class="card-title">Student Name : {{m.student_name}}</h5> <form action="{% url 'stu_id_details' %}" method="POST">{% csrf_token %} <div class="form-group"> <input type="hidden" name="get_id_stu_details" value="{{m.student_ID}}" class="form-control" id="exampleInputPassword2"> </div> <button type="submit" class="btn btn-outline-success btn-sm">See Student Details</button> </form> </div> </div> </div> </div> {% endfor %} -
How to update the html table <td> by press button and get the info from python script
I want to make a website that gets data from the python code below, that when I press the button that will update each of HTML table -
Getting error while giving command-pip install virtualenvwrapper-win
ERROR: Exception: Traceback (most recent call last): File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 548, in site_packages_writable return all( File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "C:\Users\Stc\AppData\Roaming\Python\Python38\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\program files\python38\Lib\site-packages\accesstest_deleteme_fishfingers_custard_lvqv1z' -
django NoReverseMatch at /account/dashboard/1/
I have a problem when I want to visit the user dashboard. On each article there is a link to the user profile, however, when I click on the link I'm getting NoReverseMatch. I was doing troubleshoots for days but I'm not able to fix the problem. Any help on how to fix this error is more than welcome, thank you! article.html: <a href="{% url 'guest_user' pk=article.author.pk %}"><h6> {{ article.author.profile.username}}</h6></a> accounts>views: @login_required def guest_dashboard(request, pk): user_other = User.objects.get(pk = pk) already_followed = Follow.objects.filter(follower = request.user, following = user_other) if guest_dashboard == request.user: return HttpResponseRedirect(reverse('dashboard')) return render(request, 'account/dashboard-guest.html', context = {'user_other' : user_other, 'already_followed' : already_followed}) articles>View: def article_detail(request, pk): article = Article.objects.get(pk=pk) comment_form = CommentForm() already_liked = Likes.objects.filter(article=article, user=request.user) likesCounter = Likes.objects.filter(article=article).count() if already_liked: liked = True else: liked = False if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.article = article comment.save() return HttpResponseRedirect(reverse('article_detail', kwargs={'pk':pk})) return render(request, 'article/single-article.html', context={'article':article, 'comment_form':comment_form, 'liked': liked,'likesCounter':likesCounter,'already_liked':already_liked}) article>URLs: path('<pk>', article_detail , name = 'article_detail'), account>URLs: path('account/dashboard/', dashboard, name = 'dashboard'), path('account/dashboard/<pk>/', guest_dashboard, name = 'guest_user'), -
Django Channels sleep
i have two group sends that i want to sleep between them, my code: await self.channel_layer.group_send( str(self.game_link), { "type": "group_message", "text": json.dumps(answer_data), } ) await asyncio.sleep(5) await self.channel_layer.group_send( str(self.game_link), { "type": "group_message", "text": json.dumps(data), } ) what ends up happening is that both send at the same time after sleep ends. how can i get around this? -
Is there any way to limit the choices displaying in autocomplete fields in Django admin based on the foreign key just selected in another field?
I encounter a problem when using the autocomplete fields in Django admin. #model.py class Party(models.Model): pass class Address(models.Model): party = models.ManyToManyField(Party,through='MailAddress') class MailAddress(models.Model): party = models.ForeignKey(Party,on_delete=models.CASCADE) address = models.ForeignKey(Address,on_delete=models.CASCADE) class Mail(models.Model): party = models.ForeignKey(Party,on_delete=models.CASCADE) mail_list = models.ForeignKey(MailAddress,on_delete=models.CASCADE) #admin.py class AddressInline(admin.TabularInline): model = Address.party.through class PartyAdmin(admin.ModelAdmin): inlines = [AddressInline] class MailAddressAdmin(admin.ModelAdmin): search_fields = ['address'] class MailAdmin(admin.ModelAdmin): autocomplete_fields = ['mail_list'] My question is whether I can make the autocomplete field display MailAddress field for the selected Party only? Thanks. -
How to return a form result set using MySQL in PhpMyAdmin to a Python Web Application
Apologies for the novice MySQL question, I need some guidance. I am working on a project with several Python/Django programmers building a web app. The web app uses MySQL database on the backend, and I access it using XAMPP and PhpMyAdmin. We need to create several reports for the web app, to be displayed in the web page and available to print. These reports are generally in table format. I wanted to develop a stored procedure to return a table resultset, based on the parameters entered in the developers forms, but I am hitting a wall finding resources on writing this out. Is this not possible? Can a MySQL stored procedure, or other function, return a table as a result set? Is there a way I could do this with a temp table or views instead? If not, then can anyone advise on an alternative to complete these reports, please. Thank you for any feedback you can provide on this topic, in advance! -
Django Advanced Tutorial: How to write reusable apps - cannot find /polls/index.html, polls/question_list.html, TemplateDoesNotExist:
I am new to Django and still a beginner at Python. The tutorial I'm following is here: https://docs.djangoproject.com/en/3.1/intro/reusable-apps/#installing-reusable-apps-prerequisites I am trying to follow the Django tutorials but it was not very clear where exactly I should be placing my /django-polls/ folder when removing /polls/ from /mysite/. I have looked at other similar questions here, but none of them solved the issue for me. I am able to run the python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz line when I am inside of my directory right above /mysite/. Here is roughly what my current directory layout looks like: django-tutorial |- /django-polls | |- /dist | |- /... | |- /polls | |- /...#all relevant polls files from previous tutorials |- LICENSE |- MANIFEST.in |- setup.cfg |- setup.py |- /mysite | |- /mysite | |- /templates | |- manage.py My INSTALLED_APPS looks like this: INSTALLED_APPS = [ 'polls.apps.PollsConfig', # The path to the PollsConfig so it can be included 'django.contrib.admin', # The admin site. 'django.contrib.auth', # An authentication system. 'django.contrib.contenttypes', # A framework for content types. 'django.contrib.sessions', # A session framework 'django.contrib.messages', # A messaging framework 'django.contrib.staticfiles', # A framework for managing static files ] I also tried it with just 'polls', instead … -
Add related models to UpdateView Django
I have a Product model with Product Stock and ProductImage as related models to Product model. I want to make an DashboardProductUpdateView that shows all of these fields. However when I pass in the Product model into the UpdateView then it only shows the [name, price, description] fields but I want to be able to update the ProductStock and ProductImage as well. Is there a way to do this? Thank you in advance! Models class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=55) price = models.FloatField() description = models.TextField(max_length=255) .... class ProductStock(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, related_name="stock") quantity = models.PositiveIntegerField() .... class ProductImage(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images") image = models.ImageField(upload_to="product_images/") default = models.BooleanField(default=False) .... Views class DashboardProductUpdateView(UpdateView): model = Product template_name = "dashboard/products/update_product.html" fields = "__all__" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["product_stock"] = ProductStock context["product_image"] = ProductImage return context def get_success_url(self): return reverse_lazy("dashboard_product_list") -
Different user with more fields in the same model in Django
I am planning to use a same user model for two different users with some additional fields in one model. Is it possible to do this in Django? If it is possible, how can I do it? -
How to access webcam in web application
I am making a project on onine exam proctoring system in django. When the candidate starts the exam the webacm should start for monitoring the candidate. I am done with the web application part. But facing issues in integrating proctoring part. Is it possible to do real-time proctoring part using javascript or is there any other library which can use for it. -
I dont know how to pass two queryset parameters into one URL
I really struggled to explain my problem and the only way I found it would be possible is - through screenshots as I have a lot of code and I am not sure what is really needed here. So if you want any code, tell me I will add. The numbers on the pictures indicate the order. Choosing the category Selecting the category it redirects me to - /products_list?category=(that category_id) Filtering through brand in that category Now please pay attention to the URL and what happens after I have chosen the brand I want to filter with. Back on the first page Problem is here: Now I am back on the first page, where are all the products but I wanted it to stay on that URL where are that kind of category products. What I wanted to happen? Instead of it taking me to the page where are ALL the products and then doing the filtering, I want it to stay on that category page and return the filtered products there. The brand dropdown menu also should only show that category products that I am in, not all. -
How to get date value from django form and store it in variable in views.py
I am creating tweetscrapper website and I want to let the user to fetch tweet by certain date so I want user to select date through datepicker ... I have created datepicker but I don't know how to pass that date value into views.py forms.py from django import forms class DateForm(forms.Form): date2 = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M']) class Date1Form(forms.Form): date3 = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M']) check.html <div class="container"> <form class="input-group" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} {{forms|crispy}} <button class="btn btn-success">Get Date</button> </form> </div> <!--<input id="datetimepicker" type="text">--> <script> $(function () { $("#id_date2").datetimepicker({ format: 'd/M/Y H:i', }); }); <script> $(function () { $("#id_date3").datetimepicker({ format: 'd/M/Y H:i', }); }); views.py class Check(View): def get(self,request): form = DateForm forms = Date1Form args = {"form": form, "forms": forms} return render(request, 'tweetScrapper/check.html', args) def post(self,request): if request.method == 'POST': form = DateForm(request.POST or None) if form.is_valid(): data = form.cleaned_data["date2"] print("date",data) return render(request,'tweetScrapper/check.html') -
Is there a way to get selected choices from a checkbox in django
I am trying to get all the selected checkbox values and save them in a database but I only get the last value in the selected checkboxes saved into the database. My views: def vote(request, position_id, voting_id): voter = Voter.objects.get(pk=voting_id) school = Voter.objects.filter(pk=voting_id).values('school') print(school) position = get_object_or_404(Delegate, pk=position_id) candidates = DelegateCandidate.objects.filter(position=position_id) print(candidates) try: selected_choice = position.delegatecandidate_set.get(pk=request.POST['choice']) except (KeyError, Candidate.DoesNotExist): return render(request, 'landing/delegates_detail.html', { 'position': position, 'error_message': "You didn't select a Choice." }) else: print(selected_choice) print(selected_choice.voted_by.all()) for aspirant in candidates: if voter in aspirant.voted_by.all(): #if voter in selected_choice.voted_by.all(): print("THIS DOES") return render(request, 'landing/vote_declined.html', {'voting_id': voting_id}) else: print("THIS DOESN'T") selected_choice.voted_by.add(voter) selected_choice.votes += 1 selected_choice.save() return render(request, 'landing/vote_confirmed.html', {'voting_id': voting_id}) From the print commands in my view, this is what I get <QuerySet [{'school': 'Computing and Informatics'}]> <QuerySet [<DelegateCandidate: Junior Chris>, <DelegateCandidate: Jane Doe>, <DelegateCandidate: Brian Smith>, <DelegateCandidate: John Doe>, <DelegateCandidate: Mary Smith>, <DelegateCandidate: Billy Dan>]> Brian Smith <QuerySet []> THIS DOESN'T Anyone got an idea on how to achieve this? -
Receiving "No Module named ''taggit" in Django3
New to django, attempting to add tagging functionality to a blog application. Installed using pip3 install django-taggit validated using pip freeze Django==3. django-taggit==1.2.0 Then added taggit to Installed_APPS in settingss.py Django then responds with ModuleNotFoundError: No module named 'taggit ' -
is there a method to save data from forms django?
file models.py : class Author(models.Model): full_name = models.CharField(max_length=255, default='', blank=True, null=True) origin = JSONField(null=True) file forms.py class AuthorForm(forms.ModelForm): full_name = forms.CharField( required=False, widget=forms.TextInput( attrs={'placeholder': '?', 'class': "input-xs form-control"} ) ) class Meta: model = Author fields = ('full_name') file views.py : def author(request): if request.method == 'POST': form = AuthorForm(request.POST) if form.is_valid(): form.save() return redirect(reverse(list_author)) i want to fill up the "origin" field just in "if form.is_valid():" , how can i do this , we must create a form field ? or we can fill up directly in if loop? -
Django Heorku deployment get favicon ico
I am trying to deploy on heroku for free, i have setup all the environment variables and database. still i am getting error: Here is the log 2 021-04-04T15:46:48.443699+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=mighty-wildwood-75189.herokuapp.com request_id=0dbaac06-d215-4d8a-8491-8ab177831733 fwd="103.205.134.230" dyno= connect= service= status=503 bytes= protocol=https 2021-04-04T15:46:55.001404+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/admin/" host=mighty-wildwood-75189.herokuapp.com request_id=57fc5331-a628-4331-85d1-28f4da4aab8a fwd="103.205.134.230" dyno= connect= service= status=503 bytes= protocol=https 2021-04-04T15:46:55.498674+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=mighty-wildwood-75189.herokuapp.com request_id=b6ec6c86-45b3-4fd7-8b7f-1a1f6910602f fwd="103.205.134.230" dyno= connect= service= status=503 bytes= protocol=https 2021-04-04T15:47:01.000000+00:00 app[api]: Build succeeded 2021-04-04T15:48:08.864007+00:00 app[api]: Set DEBUG config vars by user 2021-04-04T15:48:08.864007+00:00 app[api]: Release v7 created by user x@gmail.com 2021-04-04T15:48:28.000000+00:00 app[api]: Build started by user x@gmail.com 2021-04-04T15:49:02.067722+00:00 app[api]: Deploy 9b0cbe8e by user x@gmail.com 2021-04-04T15:49:02.067722+00:00 app[api]: Release v8 created by user x@gmail.com 2021-04-04T15:49:16.000000+00:00 app[api]: Build succeeded 2021-04-04T15:51:08.610236+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/admin/" host=mighty-wildwood-75189.herokuapp.com request_id=63286f44-2f68-4409-a55a-1221027a2abe fwd="103.205.134.230" dyno= connect= service= status=503 bytes= protocol=https 2021-04-04T15:51:08.961566+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=mighty-wildwood-75189.herokuapp.com request_id=6f87fe2d-9508-4f2c-9c97-436ebe0fb02e fwd="103.205.134.230" dyno= connect= service= status=503 bytes= protocol=https Anyone know about the issue? what is the possible of getting this error? -
Is it possible to build an app like Uber with just Python and Django? [closed]
Is it possible to build an app like Uber with just Python and Django ? -
Como manter ativo uma checkbox após atualização?
Tenho um site responsivo no qual inclui um js para alterar o tema do site, de dark para light. Porém, fiz uma checkbox para atualizar os dados, e quando atualizo o site, imediatamente ela volta para a "original", queria saber como manter o dado do checkbox mesmo após atualição de paginas. Esse é o js : const chk = document.getElementById('chk'); chk.addEventListener('change', () => { document.body.classList.toggle('dark'); }); -
Is Django model ordering also an indexing?
Per the Django docs, ordering is "The default ordering for the object, for use when obtaining lists of objects". This is great, but I don't see anything about indexing the database with this ordering. Does Django add an index with this ordering as well? Or should I add indexes under ordering as well? That just seems redundant though. -
migration issue, django.core.exceptions.FieldDoesNotExist: lightspeed.inventoryimagehistory has no field named 'imageID'
I'm having issues with this Django project, when I try to run migrations got the following message: base dir path C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop Traceback (most recent call last): File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 141, in handle loader.project_state(), File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\loader.py", line 324, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 326, in state_forwards raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: lightspeed.inventoryimagehistory has no field named 'imageID' this is the class for InventoryImageHistory class InventoryImageHistory(models.Model): ImageID = models.IntegerField(db_index=True, unique=True, null=False, primary_key=True) history = ListField(DictField()) objects = models.DjongoManager() these are the migration files: Any help with this will be really appreciated, best regards