Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
why am I getting status code error while registering user through django rest framework
I am developing an authentication system for User registration through Django restframework. I have followed youtube link to configure serialzers. Since the Tutor is not using class based views, So, I didn't follow that part. I have written own class based view for ListCreateAPIView. serializers.py from rest_framework import serializers from .models import NewEmployeeProfile class RegistrationSerializers(serializers.ModelSerializer): ''' We need to add the password2, as its not the part of the NewEmployeeProfile model. So, we need to make it manually. ''' password2 = serializers.CharField(style={'input_type: password'}, write_only=True) class Meta: model = NewEmployeeProfile fields = ('email', 'first_name', 'last_name', 'employee_code', 'contact', 'dob', 'password', 'password2') extra_kwargs = { 'password': {'write_only': True} } def save(self, **kwargs): """ before we save the new user, we need to make sure that the password1, and password2 matches. In order to do that, we need to override the save() method. """ account = NewEmployeeProfile( email=self.validated_data['email'], first_name=self.validated_data['first name'], last_name=self.validated_data['last name'], employee_code=self.validated_data['employee code'], contact=self.validated_data['contact'], dob=self.validated_data['dob'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': f'password must match..'}) account.set_password(password) account.save() return account views.py class UserRegisterView(ListCreateAPIView): create_queryset = NewEmployeeProfile.objects.all() serializer_class = RegistrationSerializers(create_queryset, many=True) permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = RegistrationSerializers(data=request.data) if serializer.is_valid(): newUser = serializer.save() serializer = … -
How to save predict model's results to database? Django
I made a predict model in my django project. Now I want to save the ptrdicted results to the UserResults table. But I don't know how to do. I'd be appreciated if you could give me some advices. Here is my models.py: from django.db import models from django.contrib.auth.models import User class UserResults(models.Model): results = models.IntegerField(blank=True) expect = models.IntegerField(blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.owner below is the views.py: from django.shortcuts import render from django.http import HttpResponse import pandas as pd import joblib def home(request): return render(request, "DeployModel/predict_home.html") def result(request): predict_modal = joblib.load('DeployModel/loan_model.pkl') temp = {} temp['ApplicantIncome'] = request.GET['ApplicantIncome'] temp['CoapplicantIncome'] = request.GET['CoapplicantIncome'] temp['LoanAmount'] = request.GET['LoanAmount'] temp['Loan_Amount_Term'] = request.GET['Loan_Amount_Term'] temp['Credit_History'] = request.GET['Credit_History'] temp['Married_Section'] = request.GET['Married_Section'] temp['Gender_Section'] = request.GET['Gender_Section'] temp['Edu_Section'] = request.GET['Edu_Section'] temp['Employed_Section'] = request.GET['Employed_Section'] temp['Property_Section'] = request.GET['Property_Section'] td = pd.DataFrame({'x':temp}).transpose() # print(temp) ans = predict_modal.predict(td)[0] return render(request, "DeployModel/predict_result.html", {'ans':ans}) Let me know if you need any more details. Thank you! -
Django template - for loop and then if statement
I have this loop: <div class="product-gallery-preview order-sm-2"> {% for images in Artikel.productimages_set.all %} {% if images.Position == 1 %} <div class="product-gallery-preview-item active" id="gallery{{ images.Position }}"> {% else %} <div class="product-gallery-preview-item" id="gallery{{ images.Position }}"> the problem is that all div classes are active I think because it's true for the first picture which is found. Is it possible to go in the loop check all pictures if it is in Position 1 and just output the div box I tried to print? -
How to post a delete request to django?
I am try ing to make a blog using django and reactjs. I am having a problem that when i send a delete request to server it responses me a text: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to localhost:16/Blog/1/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Can anyone help me ? Thank You ! this is my project source code https://github.com/KhanhGamer1601/React-Frontend-Blog https://github.com/KhanhGamer1601/Django-Backend-Blog -
How to make alert message disappear in Django
This is in my base html. How do i make the alert message only show for 5 seconds and automatically close? {% if messages %} {% for message in messages %} <div class = "alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %}