Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToManyField field: render formset in template
There are two models with a many to many relationship like this: class Client(models.Model): first_name = models.CharField( max_length=50, ) last_name = models.CharField( max_length=50, ) class Event(models.Model): event_name = models.CharField( max_length=50, ) start = models.DateTimeField() end = models.DateTimeField() clients = models.ManyToManyField( Client, db_table='ClientsAttendingEvent', blank=True, ) I want to create 2 templates with basic forms. A "create_event.html" page, and an "edit_event.html" page. Assuming really simple forms like: class EventForm(ModelForm): class Meta: model = Event fields = ['all'] class ClientForm(ModelForm): class Meta: model = Client fields = ['all'] I am struggling a lot with the view. def UpdateEvent(request, EventID): obj = get_object_or_404(Event, pk=EventID) form = SessionsForm(instance=obj) clients_formset = inlineformset_factory(parent_model=Event, model=Client, fields=('first_name', 'last_name',)) if request.method == 'POST': form = EventForm(request.POST, instance=obj) clients_forms = clients_formset(request.POST) if form.is_valid() and clients_forms.is_valid(): final_form = form.save(commit=False) final_form.save() form.save_m2m() return HttpResponseRedirect(reverse('homepage', kwargs={'EventID': EventID})) return render(request, './forms/edit_event.html') Problem: Here I tried various solutions using formset_factory and inlineformset_factory. But I usually get "X has no ForeignKey to Y" or "No fields with name ... ", and so on. Basically I don't get how to use formset factories with a m2m field instead of foreign keys or a dedicated m2m model. Using dot-Notation, "through" and other attempts didn't succeed either. Desired outcome: Having … -
Why serializer.is_valid() is always false in this scenario?
I'm try to Update this model in Django rest-api but I don't get any idea why serializer is always not valid when I try to Update; models.py class Profile(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, to_field='email') gender = models.CharField(max_length=20, null=True, blank=True) blood_group = models.CharField(max_length=20, null=True, blank=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE, to_field='short_name', null=True, blank=True, default="CSE") program = models.CharField(max_length=20, null=True, blank=True) student_id = models.CharField(max_length=20, null=True, blank=True) phone = models.CharField(max_length=20, null=True, blank=True) photo = models.ImageField(upload_to='Student/Profile/Profile_Photos/', null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) current_semester = models.CharField(max_length=20, null=True, blank=True) level = models.IntegerField(null=True, blank=True) term = models.IntegerField(null=True, blank=True) sec = models.CharField(max_length=20, null=True, blank=True) sub_sec = models.CharField(max_length=20, null=True, blank=True) complete_cr = models.FloatField(null=True, blank=True) sgpa = models.FloatField(null=True, blank=True) cgpa = models.FloatField(null=True, blank=True serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' views.py class ProfileUpdateView(generics.UpdateAPIView): model = Profile serializer_class = ProfileSerializer permission_classes = [IsAuthenticated] parser_classes = (MultiPartParser, FormParser) def post(self, request): token = request.headers.get("Authorization").split(" ")[-1] print(token) try: token_obj = get_object_or_404(Token,key = token) user = token_obj.user data =Profile.objects.get(user=user) serializer = ProfileSerializer(instance = data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response({"invalid"}) except: return Response({'failed': _('bad request'),},status = status.HTTP_406_NOT_ACCEPTABLE) Already 12hrs pass. But still, I didn't get any solution or explanation. Thanks in advance... -
formset in create view not adding new forms and not working with crispy
My code is : views.py: class OrderCreate(CreateView): model = Order template_name = 'order_create.html' form_class = orderForm def get_context_data(self, **kwargs): context = super(OrderCreate, self).get_context_data(**kwargs) context['formset'] = orderDetailForm() context['order_form'] = orderForm() return context def post(self, request, *args, **kwargs): formset = orderDetailForm(request.POST) order_form = orderForm(data=request.POST) if formset.is_valid() and order_form.is_valid(): return self.form_valid(formset, order_form) def form_valid(self, formset, order_form): order = order_form.cleaned_data['order'] instances = formset.save(commit=False) order.created_by = self.request.user order.save() for instance in instances: instance.save() content = {"name": order.created_by, "id": order.pk} send_gmail_message(['philippe@gustafoods.com', 'doro@gustafoods.com'], content) return reverse_lazy("procurement:order_detail",kwargs={'pk':self.object.pk}) def get_success_url(self): return reverse_lazy("procurement:order_detail", kwargs={'pk': self.object.pk}) models: class Order(models.Model): STATUS_TYPES = (('draft', _('draft')), ('pending', _('pending')), ('quote', _('quote requested')), ('ordered', _('ordered')), ('received', _('received')), ('BO', _('back order')), ('cancelled', _('cancelled'))) URGENT_LIST = (('Very Urgent', _('Very Urgent (less than a day)')), ('Urgent', _('Urgent (before 48 hours)')), ('Normal', _('normal (a week)')), ('Other', _('Other (need search)')), ) status = models.CharField('Status', max_length=20, choices=STATUS_TYPES, default='pending') urgent = models.CharField('Urgent', max_length=20, choices=URGENT_LIST, default='Normal') date_created = models.DateField(_('requested'), auto_now_add=True, help_text=_('Date when order was created')) date_ordered = models.DateField(_('ordered'), blank=True, null=True, help_text=_('Date when order was placed')) date_validation = models.DateField(_('validated'), blank=True, null=True, help_text=_('Date when order was validated')) date_received = models.DateField(_('received'), blank=True, null=True, help_text=_('Date when product was received')) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=False, db_index=True, verbose_name='requested by', related_name='requests', help_text=_('user who created this order')) comment = models.TextField(_('comments & … -
Indirect way of usine Model.objects.all() in a formset
I'm using something like this to populate inlineformsets for an update view: formset = inline_formsetfactory(Client, Groupe_esc, form=GroupEscForm, formset=BaseGroupEscInlineFormset, extra=len(Groupe.objects.all())) (Basically I need as many extra form as there are entries in that table, for some special processing I'm doing in class BaseGroupEscInlineFormset(BaseInlineFormset)). That all works fine, BUT if I pull my code & try to makemigrations in order to establish a brand new DB, that line apparently fails some django checks and throws up a "no such table (Groupe)" error and I cannot makemigrations. Commenting that line solves the issues (then I can uncomment it after making migration). But that's exactly best programming practices. So I would need a way to achieve the same result (determine the extra number of forms based on the content of Groupe table)... but without triggering that django check that fails. I'm unsure if the answer is django-ic or pythonic. E.g. perhaps I could so some python hack that allows me to specific the classname without actually importing Groupe, so I can do my_hacky_groupe_import.Objects.all(), and maybe that wouldn't trigger the error? -
chart.js Line chart doesn't display line past a certain point in the chart
For some reason, my line chart isn't correctly displaying the lines past a certain point in the dataset and I can't figure out the reason why this is the case. I have another chart which loads basically the same dataset and that one is displaying just fine (only difference is the line chart has a fill, bordercolor and tension attributes). <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> const data_bar_chart = { labels: {{ labels | safe }}, datasets: {{ data_list | safe}} }; const config_bar_chart = { type: 'bar', data: data_bar_chart, options: { plugins: { title: { display: true, text: 'Bar Chart - Stacked' }, }, legend: { position: "top", align: "start" }, responsive: false, scales: { xAxes: [{ stacked: true, ticks: { padding: 20 } }], yAxes: [{ stacked: true, }], }, } }; const data_line_chart = { labels: {{ labels | safe }}, datasets: {{ data_list_line_chart | safe}} }; const config_line_chart = { type: 'line', data: data_line_chart, options: { plugins: { title: { display: true, text: 'Line Chart' }, }, legend: { position: "top", align: "start" }, responsive: false, scales: { xAxes: [{ ticks: { padding: 20 } }], }, } }; window.onload = function() { var ctx_bar_chart = document.getElementById('bar-chart-stacked').getContext('2d'); window.myPie = … -
Django how to pass context or model objects in base.html without pass views in url
I know I can pass context using somethings like this in base.html class MyViews(request): #my code..... context= {#my context} return render(request, 'base.html', context) then pass the views in url. But is there any to pass context in base.html without using url?? any idea?? I also tried this 'context_processors': [ ... # add a context processor 'my_app.context_processor.my_views', ], #getting this error No module named 'contact.context_processor' -
How to add a photo to an object ? Django REST
I have person model: class Assistant(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() photo = models.ImageField(upload_to='photos/') using Django REST how a photo was loaded from https://thispersondoesnotexist.com when creating a new assistant I understand that you need to override the create method how to do it in the best way? ss -
Overwriting django Integer choices output in graphene
I'm working with graphene and graphene-django and I have a problem with a IntegerField with choices. graphene create an Enum and the output is "A_1" if the value is 1; "A_2" if the value is 2 and so on. Example: # model class Foo(models.Model): score = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5))) # query query { foo { score } } # response { "data": { "foo": { "source": "A_1" } } } How I can overwrite this output? (ps: I've copied the question from an old post but there is no any proper comment for today, because it is from 4,5 years ago. I've had exactly the same problem today) Thanx -
[Python:Django]AttributeError
I am following django tutorial but i am stuck in part 4. When i try to run server i get error "AttributeError: module 'polls.views' has no attribute 'ResultsView'" My code: polls/views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from .models import Question, Choice from django.template import loader from django.urls import reverse def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list } return render(request, 'polls/index.html', context) def detail(request, question_id): question =get_object_or_404(Question, pk=question_id) return render(request, "polls/detail.html", {'question':question}) def results(request, question_id): response = "You are looking at results of question %s" return HttpResponse(response % question_id) #render(request, 'polls/results', {"question_id": question_id}) #HttpResponse(response % question_id) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question' : question, "error_message" : "You didn't select a choice'", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=[question.id])) # Create your views here. polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns=[ path("", views.index, name="index"), path("<int:question_id>/", views.detail, name="detail"), path("<int:pk>/results/", views.ResultsView.as_view(), name="results"), path("<int:question_id>/vote/", views.vote, name="vote"), ] polls/results.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text}} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li> {% endfor %} <ul/> </ul> <a href … -
SMTP mail getting bounced using Heroku, Django and Outlook (goDaddy)
So I'm having some issues with sending emails using SMTP with Django, Heroku and a GoDaddy (office 365) email. My email setup is as such: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = HOSTUSER EMAIL_HOST_PASSWORD = LOCALPASSWORD EMAIL_PORT = 587 EMAIL_USE_TLS = True If I send a standard test e-mail LOCALLY (i.e. by running my app locally) like this: import django django.setup() from django.conf import settings from django.core.mail import send_mail send_mail( subject = 'That’s your subject', message = 'That’s your message body', from_email = settings.EMAIL_HOST_USER, recipient_list = [some_email_address,], fail_silently = False ) It works just fine. Also, I am able to send e-mails as normal through my Outlook webmail. However, when I launch this app to Heroku and try to send a test e-mail, I get a bounce-back to my webmail that looks like this: Remote Server returned '550 5.7.708 Service unavailable. Access denied, traffic not accepted from this IP. For more information please go to http://go.microsoft.com/fwlink/?LinkId=526653 AS(8561) [CWXP265MB3078.GBRP265.PROD.OUTLOOK.COM]' Received: from CWLP265MB3922.GBRP265.PROD.OUTLOOK.COM ([fe80::f472:c360:b020:723b]) by CWLP265MB3922.GBRP265.PROD.OUTLOOK.COM ([fe80::f472:c360:b020:723b%6]) with mapi id 15.20.4308.022; Thu, 8 Jul 2021 16:29:32 +0000 MIME-Version: 1.0 Content-Type: text/plain Date: Thu, 8 Jul 2021 16:29:32 +0000 Message-ID: 162576177199.10.1317079512283763999@7b074c75-3c7b-4c2c-9dc4-caf0ce6cbd26.prvt.dyno.rt.heroku.com So it seems to me that the IP address assigned to … -
PasswordResetForm special usage HTML email template not rendering
my email template (see code below) does not render. You can imagine that reset_password_after_slack_registration is allowing me on pressing a button to send an user a email to reset his password with another message than the standard password reset message (see below). But it is not rendering and e.g. the are still showing up. Any ideas on how to fix? Thanks!! from django.contrib.auth.forms import PasswordResetForm def reset_password_after_slack_registration(email, from_email, template='users/slack_account_password_reset_email.html'): """ Reset the password for an user """ form = PasswordResetForm({'email': email}) form.is_valid() return form.save(from_email=from_email, email_template_name=template) The template looks like this: {% autoescape off %} Hi {{ user.first_name }}, <br> <br> You have requested to set an account for your XYZ account that you have been using via Slack so far.<br> For your XYZ account {{ user.email }}, you can <a href="https://example.com/accounts/google/login/">Sign in with Google</a> or set a a password, by clicking the link below:<br> https://example.com{% url 'slack_account_password_reset_confirm' uidb64=uid token=token %} <br><br> If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. <br><br> All the best,<br> Your XYZ team {% endautoescape %} And the URLs look like this: # Slack Accounts path('slack/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/slack_account_password_reset_confirm.html'), name='slack_account_password_reset_confirm'), -
How to retrieve an image from static folder using javascript and django
I have trouble trying to get an image from static folder. When I pass the image in the html it works. here is my code <div id="dirs" class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="{% static 'PERDNI/09401576.jpg' %}" class="card-img" alt="..."/> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">Datos personales</h5> <p class="card-text">This is a wider card.</p> </div> </div> </div> </div> This is the generated html in the browser inspector: In other hand, when I generate the html from a javascript file, it doesn't work, The image doesn't appear but the other part of the html yes. Here is my code var datahtml='<div class="row no-gutters"><div class="col-md-4">'; datahtml+='<img src="{% static ' datahtml+="'PERDNI/09401576.jpg'" datahtml+=' %}" class="card-img" alt="My image"/>' datahtml+='</div><div class="col-md-8"><div class="card-body">' datahtml+='<h5 class="card-title">Card title</h5>' datahtml+='<p class="card-text">Hello</p>' datahtml+='</div></div></div>' document.getElementById("dirs").innerHTML=datahtml This is the other generated html in the browser inspector: What would be the problem, I was thinking in the quotes however I tried in many ways and It haven't worked yet. Thanks in advance. -
Django-ckeditor Error code: exportpdf-no-token-url
I try to add ckeditor 6.1 to my form allow user to post an article. I followed a video on youtube to install and setting, I successfully add a new post using ckeditor in django admin page. But in html page, the richtext field shows but with below error. When I just render the page with GET method (have not submit the form yet), in console I always get the error : ckeditor.js:21 [CKEDITOR] Error code: exportpdf-no-token-url. and Submit also doen't work. I am new with django, this is a final shool project. I don't need to export to PDF, how can I just disable? or any idea, please help, I have stuck here for a few days. class Article(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name='post_user') title = models.CharField(max_length=150) body = RichTextUploadingField(blank=True, null=True) class Post_Form(ModelForm): class Meta: model = Article exclude = ['user'] widgets = { 'title': TextInput(attrs={'class': 'form-control', 'id': 'title' }), 'body': Textarea(attrs={'rows':10, 'cols':40}), } views.py def write_post(request): form = Post_Form(request.POST) return render(request, 'write_post.html', { 'form': form, }) setting.py CKEDITOR_CONFIGS = { 'default': { 'height': 800, 'width': 1000, }, } CKEDITOR_UPLOAD_PATH = "uploads/" html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <div type=submit class="btn … -
Using F() expression in Django update method
I have a Django model called Tree representing tree objects and it contains x and y coordinate fields of type FloatField. I am trying to call Django's update method to initialize a PointField called coordinates for each tree object with the following command: Tree.objects.all().update(coordinates=Point(F('x'), F('y'))) If I understood correctly from the documentation, I would need to use the F() expression to access the fields of each tree object at the database level. However, this does not work and results in the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/src/app/app/tree_api/management/commands/update_coords.py", line 47, in handle Tree.objects.all().update(coordinates=Point(F('x'), F('y'))) File "/usr/local/lib/python3.8/site-packages/django/contrib/gis/geos/point.py", line 35, in __init__ raise TypeError('Invalid parameters given for Point initialization.') TypeError: Invalid parameters given for Point initialization. What I'm trying to achieve could be done using the following raw SQL query: UPDATE tree_column_name SET coordinates = ST_GeomFromText('POINT(' || x || ' ' || y || ')'); Is it possible to initalize the PointField from x … -
referencing Django changing static images paths
I have a line of code <img src="{% static 'mysite/plots/' %}{{ plot }}" alt="Stock price vs. predictions graph" style="width: 600px; height: 450px;"> where I want to display images based on a variable called plot that I pass from my views.py. For example, this variable could be 'AAPL.PNG' or 'TSLA.PNG', whatever the image name is, I am sure that I have it stored at my static/mysite/plots/ directory because when I access these paths directly with {% static 'mysite/plots/AAPL.PNG' %} it works. I have also tried: src="{% static 'mysite/plots/{{ plot }}' %}" src="{% static 'mysite/plots/'(plot) %}" src="{% static 'mysite/plots/' + plot %}" -
django-rest-framwork Got AttributeError when attempting to update a value
There is an error "Got AttributeError when attempting to get a value for field learner on serializer LearnerAddressSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the Learner instance.\nOriginal exception text was: 'Learner' object has no attribute 'learner'." I don't know how to solve this error. models.py class LearnerAddress(Address): learner = models.ForeignKey('learner.Learner', on_delete=models.CASCADE, related_name="learner_address") views.py def patch(self, request, learner_id): ......... ......... if key == 'address_details': address_serializer = LearnerAddressSerializer(instance=instance, data=value, partial=True) address_serializer.is_valid(raise_exception=True) address_serializer.save() response_data['address'] = address_serializer.data serializer.py class LearnerAddressSerializer(serializers.ModelSerializer): class Meta: model = LearnerAddress fields = '__all__' The above error occurs when I try to update data, also tried many=True. I am a beginner in Django, so I also need a little bit of description , expecting immediate help also. json input: "address_details": { "name":"name" } -
Why will my django model data not display in html
Following this tutorial, I am creating a simple ecommerce website. I have data stored in a Django model, and I am calling it in my view, but it will not display in my html. Basically, I want it to create one of the boxes bellow for every donation in the donation model, but it will not work. Can someone please help me? I know this seems like an easy fix, I just can't wrap my head around it. My code is down bellow. View: def availablesupplies(request): donations = Donation.objects.all() context = {'donations':donations} return render(request, 'availablesupplies.html') Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) location = models.CharField(max_length=50, blank=True, null=True,) description = models.TextField() datedonated = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML: <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{% static 'images/gooddeedplaceholderimage.png' %}"> <div class="box-element product"> <h6><strong>Product</strong></h6> <hr> <button class="btn btn-outline-secondary add-btn">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"><strong>$20</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} -
git: 'remote-https' is not a git command. See 'git --help'
I have been trying to clone my repository and it shows the following error:- git: 'remote-https' is not a git command. See 'git --help' Here is my:- Clone from https://github.com/NavyaThakur/django-project1 To directory C:\Users\91933\github\django-project1 I tried reinstalling github desktop but no use. Please help me through this -
Push failed to Heroku - Python Django
I was trying to deploy my django app on heroku, I did not create a virtual environment, and this is my first time doing it. When I tried to push to heroku I got error after installing all packages -: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_b0d1f9a6/manage.py", line 22, in <module> main() File "/tmp/build_b0d1f9a6/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in exists return os.path.exists(self.path(name)) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py", line 38, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable … -
Django administration error after changing the model
good morning, I have a problem with a django app deployed as a web app on Microsoft Azure. Basically after adding an imageField to a model, when from administration I enter in the modification of one of those objects (related to that model) I get the following error: No module named 'backend' Request Method: GET Request URL: http://......myurl...../adminforsuperuser/auth/tenants/tenant/4791c751-bc04-4bb5-aa9f-82732b7c3217/change/ Django Version: 2.2.8 Exception Type: ModuleNotFoundError Exception Value: No module named 'backend' Exception Location: in _find_and_load_unlocked, line 953 Python Executable: /opt/python/3.6.12/bin/python3.6 Python Version: 3.6.12 Python Path: ['/opt/python/3.6.12/bin', '/tmp/8d942cfe6a508ea', '/tmp/8d942cfe6a508ea/antenv3.6/lib/python3.6/site-packages', '/opt/python/3.6.12/lib/python36.zip', '/opt/python/3.6.12/lib/python3.6', '/opt/python/3.6.12/lib/python3.6/lib-dynload', '/opt/python/3.6.12/lib/python3.6/site-packages'] Server time: Fri, 9 Jul 2021 12:04:19 +0000 More details about the error: image The field I add to the model: logo= models.ImageField(upload_to=path_and_rename, default='tenant_logos/default_logo.png') Practically the fact that in edit must also show me the form to change the image (and the path of the image currently saved in that object) breaks the whole page. The strange thing is that it works locally! They, local and prod, have the same apps installed: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', .....my app here... , ] Thank you! -
facing two problem when I was giving image path on src in JS file then show error, second when I was click on image the click even not fire
I am fetching table heading column name dynamically using Ajax. I want to give icon on first column heading. the problem is, I am giving path src="{% static 'image/upArrow.png'%}" but it's not working on getData.js file, when I am giving same path on home.html then image icon show on html, I define in {% load static %} on Js but still not work. second problem, I click on error image icon then click event not fired, when i gave the static table heading column name then its work properly. I am using django for backend getData.js file where fetching data function execTable(data){ var table_header = document.getElementById('exce-header') var table=document.getElementById('exce-table') console.log("keyyy : ",Object.keys(data[0])) key = Object.keys(data[0]) console.log('valueee : ',data[0][key[0]]) for (let i=0;i<key.length;i++){ var header; if(i==0){ header = ` <th> <img src="{% static 'image/upArrow.png'%}" id="up_Arrow" class="toggle_child" style="visibility: visible" /> ${key[i]} </th> `} else { header = ` <th> ${key[i]} </th> `} table_header.innerHTML+=header } } home.js file where click event wrote. var test_bool= true; $('.toggle_child').on('click', function(event) { test_bool = !test_bool if(test_bool == false){ document.getElementById("c-table-3").style.height ="30px"; } else{ document.getElementById("c-table-3").style.height ="129px"; } }); home.html file where display file data <div class="panel" id="c-table-3"> <div class="table-data" > <table > <thead class="accordion"> <tr id="exce-header"> </tr> </thead> <tbody id="exce-table" > … -
How to pass an HTTP request as a parameter of a python function?
I'm calling a python function and passing an HTTP request as a parameter but it's not working. I created the function in a View and called it in another, but the parameter fails. Here's the function I'm calling def load_colmeias(request): apiario = request.GET.get('apiario') if apiario != "": colmeias = Colmeia.objects.filter(apiario=apiario) return render(request, 'colmeias_choices.html', {'colmeias': colmeias}) else: return render(request, 'colmeias_choices.html') Here I call her load_colmeias(request) But the following error occurs NameError: name 'request' is not defined I already imported the "urlib" and "requests" libraries but it always gives the same error: AttributeError: module has no attribute 'GET' Can someone help me ?? I'm new to Python/Django and I'm still learning how to do things -
How to validate a formset in dajngo
I am using formset to input my data into the database but for some reason it just doesn't validate, whenever I test in the terminal and call the .is_valid() It just returns false no matter what I try. Here's the code in my views.py and forms.py . Any help will be much appreciated! # Advanced Subjects (Advanced Biology) def form_5_entry_biology_view(self, request): current_teacher = User.objects.get(email=request.user.email) logged_school = current_teacher.school_number students_involved = User.objects.get(school_number=logged_school).teacher.all() data = {"student_name": students_involved} formset_data = AdvancedStudents.objects.filter(class_studying="Form V", combination="PCB") student_formset = formset_factory(AdvancedBiologyForm, extra=0) initial = [] for element in formset_data: initial.append({"student_name": element}) formset = student_formset(request.POST or None, initial=initial) print(formset.is_valid()) context = { "students": students_involved, "formset": formset, "class_of_students": "Form V", "subject_name": "Advanced Biology", } return render(request, "analyzer/marks_entry/marks_entry_page.html", context) And here is my forms.py class AdvancedBiologyForm(forms.ModelForm): student_name = forms.CharField() class Meta: model = ResultsALevel fields = ('student_name', 'advanced_biology_1', 'advanced_biology_2', 'advanced_biology_3',) -
how to return queryset by ajax data
I want to make a modal window but I intend to make it shorter, so I'm looking for ajax. When button clicked, POST id parameter to Django by ajax. I made with class=popup-click, id=post.id (post is a query from django model Post) Make a queryset in django by using ajax data. it maybe like 'Post.objects.get(id = (ajax data)). Using this queryset to dispose of a modal window. but I'm not familiar with ajax. so yet the POST method is errored. Help me, bro. -
django: FooSearchListView' object has no attribute 'object_list'
I am using Django 3.2 and django-taggit 1.4 I have a model Foo defined like this: /path/to/myapp/models.py class Foo(models.Model): title = models.CharField() story = models.CharField() caption = models.CharField() tags = TaggableManager() I am trying to write a search for Foo objects matching one or more tags, using CBV. Here is my code: /path/to/myapp/views.py class FooSearchListView(ListView): model = Foo slug_field = 'query' context_object_name = 'foo_list' paginate_by = 3 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) return context def post(self, request, *args, **kwargs): query_original = request.POST.get('search_terms', None) page = request.POST.get('page', 1) q_filter = Q() if query_original: keywords = [x.strip() for x in query_original.lower().split(',')] title_match = reduce(operator.or_, (Q(title__icontains=word) for word in keywords)) story_match = reduce(operator.or_, (Q(story__icontains=word) for word in keywords)) captions_match = reduce(operator.or_, (Q(caption__icontains=word) for word in keywords)) tags_match = reduce(operator.or_, (Q(tags__name__icontains=word) for word in keywords)) q_filter = title_match | story_match | captions_match | tags_match foos = Foo.objects.filter(q_filter).distinct().order_by('-date_added') context = self.get_context_data(*args, **kwargs) context['keywords'] = keywords return render(request, 'search_items.html', context=context) /path/to/my/app/urls.py urlpatterns = [ # ... path('search/', FooSearchListView.as_view(), name='foo-search'), # ... ] I don't like the way I have structured the code, because I am not able to override methods like get_queryset(), etc. and all of the logic is just in the post() …