Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mySQL - Web application only with private users
I am attempting to make a web app, where there is a login system and then once you have logged in you can add things to your personal list. I'm new to mySQL and website creation, so I'm a little confused on how to do this. I need a user database: users id username name email password 1 john123 john john@gmail.com password 2 jenna23 jenna jenna@gmail.com password3 But I also need a database the hold the data of the users. John's data looks like this: item-name type image cat animal cat.jpg cheeto food cheeto.jpg But Jenna's data looks like: item-name type image dog animal dog.jpg grapes food grapes.jpg I don't plan on the users being able to share data with each other like a blog post type system at least at this point. Right now I just want users to be use this site as a way to store their personal items. Should each user have their own table? Or should I just put all of their data in one database, but couldn't that mess up somehow? -
Scrapy ImportError: cannot import name 'HTTPClientFactory' from 'twisted.web.client' (unknown location)
Previously when I run this command in VSCode terminal, i didnt get any error. scrapy crawl ma -a start_at=1 -a end_and=2 -a quick_crawl=false But now, i don't know why it get this error 2022-07-20 10:10:14 [log.log_scrapy_info] INFO : Scrapy 2.2.1 started (bot: regulation_crawler) 2022-07-20 10:10:14 [log.log_scrapy_info] INFO : Versions: lxml 4.9.1.0, libxml2 2.9.14, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.4.0, Python 3.8.10 (default, Jun 22 2022, 20:18:18) - [GCC 9.4.0], pyOpenSSL 22.0.0 (OpenSSL 3.0.5 5 Jul 2022), cryptography 37.0.4, Platform Linux-5.15.0-41-generic-x86_64-with-glibc2.29 2022-07-20 10:10:14 [log.log_scrapy_info] DEBUG : Using reactor: twisted.internet.epollreactor.EPollReactor 2022-07-20 10:10:14 [crawler.__init__] INFO : Overridden settings: {'AUTOTHROTTLE_DEBUG': True, 'AUTOTHROTTLE_ENABLED': True, 'BOT_NAME': 'regulation_crawler', 'DOWNLOAD_DELAY': 0.5, 'FEED_EXPORT_INDENT': 4, 'LOG_FILE': '', 'LOG_FORMAT': '%(asctime)s [%(module)s.%(funcName)s] %(levelname)s : ' '%(message)s', 'LOG_LEVEL': 10, 'NEWSPIDER_MODULE': 'regulation_crawler.crawler.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['regulation_crawler.crawler.spiders'], 'USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) ' 'Gecko/20100101 Firefox/84.0'} 2022-07-20 10:10:14 [telnet.__init__] INFO : Telnet Password: 42678d057d4fa701 2022-07-20 10:10:14 [warnings._showwarnmsg] WARNING : /home/fhadli/.cache/pypoetry/virtualenvs/regulation-crawler-_1wB9V_j-py3.8/lib/python3.8/site-packages/scrapy/extensions/feedexport.py:210: ScrapyDeprecationWarning: The `FEED_URI` and `FEED_FORMAT` settings have been deprecated in favor of the `FEEDS` setting. Please see the `FEEDS` setting docs for more details exporter = cls(crawler) 2022-07-20 10:10:14 [middleware.from_settings] INFO : Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.feedexport.FeedExporter', 'scrapy.extensions.logstats.LogStats', 'scrapy.extensions.throttle.AutoThrottle', 'regulation_crawler.crawler.extensions.statsd.CrawlerStatsdExporterExtension'] 2022-07-20 10:10:14 [__init__._load_handler] ERROR : Loading "scrapy.core.downloader.handlers.http.HTTPDownloadHandler" for scheme "http" Traceback … -
How to save form instance created using sessionwizard class in django?
I want to save the created objects, but I can't get it to work. I can successfully fill out the form and submit it, but no data is saved in the database. Any suggestions as to what I'm doing incorrectly? I tried using form_data[0].save but it threw 'dict' object has no attribute 'save' views from django.shortcuts import render from formtools.wizard.views import SessionWizardView from django.core.files.storage import FileSystemStorage from .forms import ( WithdrawForm1, WithdrawForm2, ) from django.conf import settings import os class WithdrawWizard(SessionWizardView): template_name = 'withdraw.html' form_list = [WithdrawForm1, WithdrawForm2] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'media_root')) def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, 'done.html', {'data': form_data}) Template {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content %} <div class="row d-flex justify-content-center" style="height: 50vh;"> <div class="col-md-6"> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post" enctype=multipart/form-data>{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ … -
Div Columns not aligning correctly in Django/Python
I'm following along a tutorial and, unfortunately, his code editor automatically indented everything when he copied/pasted a new <div> (Sigh) (In the second pic I cut off the top where it has LOGO in the top right on accident in the screenshot) This is what it currently looks like This is what it should look like Room.html File {% extends 'main.html' %} {% block content%} <div class="room-container"> <div> <style> .room-container( display: grid; grid-template-columns: 3fr 1fr; ) </style> <div class="room-container"> <div> <h1>{{room.name}}</h1> <p>{{room.description}}</p> <div class="comment-wrapper"> <h3> Conversations </h3> <hr> {% for message in room_messages %} <div> <a href="{% url 'delete-message' message.id %}">Delete</a> <small>@{{message.user}} {{message.created|timesince}} ago </small> <p>{{message.body}}</p> <hr> </div> {% endfor %} </div> <div> {% if request.user.is_authenticated %} <div class="comment-for"> <form method="POST" action=""> {% csrf_token %} <input type="text" name="body" placeholder="Comment here.." /> </form> </div> </div> </div> {% endif %} <div> <h3>Participants</h3> <hr> {% for user in participants %} <div> <p>@{{user.username}}</p> </div> {% endfor %} </div> </div> {% endblock %} Main.html file <!DOCTYPE html> <html> <head> <meta charset='utf-9'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>StudyBud</title> <meta name='viewport' content='width=device-width, initial-scale=1'> </head> <body> {% include 'navbar.html' %} {% if messages %} <ul class="messages"> {% for message in messages %} <li></li>{{ message }}</li> {% endfor %} </ul> {% … -
Not able to delete whole object from CART model in django
Using ajax I am sending a post to delete a cart item but for some reason it delete's product quantity from and the object there with foreign key due to which it sends an error because I am using property to return total cost. Here is my model and code. Error that I am getting unsupported operand type(s) for *: 'NoneType' and 'int' ''' class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) product_quantity = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) @property def total_cost(self): return self.product_quantity * self.product.product_price ''' Here is my views.py ''' def removeitemfromcart(request): if request.method == "POST": product_id = int(request.POST.get('product_id')) if Cart.objects.filter(user=request.user, product_id=product_id): cartitem = Cart.objects.get(product_id=product_id, user=request.user) cartitem.delete() return JsonResponse({'status': 'Deleted Successfully'}) return redirect('/') ''' Here is the object that got deleted Cart item that I tried to delete -
Django and Querysets redundancy - Making more efficient?
So I've been working on this piece of code and since I only have the view to play with, I was wondering if there are inputs to making this more efficient (specially the user_total_xx parts). Background: I have already accomplished this using raw SQL queries but I'm trying to convert it, trying to make it efficient and learning along the way. Would love some experts to chime in since I'm very new to this. @action(detail=True, methods=['GET'], url_path='', url_name='') def reporting(self, request, *args, **kwargs): request_body = json.loads(request.body) user_id = request_body['user_id'] start = request_body['start'] end = request_body['end'] vendor_name = request_body['vendor_name'] org_id=request_body['org_id'] billing_frequency = request_body['billing_frequency'] c1=Q(user=user_id) c2=Q(vendor__name=vendor_name) c3=Q(id=org_id) c4=Q(billing_frequency=billing_frequency) all_reports = Task.objects.filter(start__gte=start, start__lte=end) #all tasks within given dates if not user_id: if not vendor_name: if not billing_frequency: query = all_reports.values() user_total_bill = all_reports.annotate(b_tot=Sum(F('hours') * F('bill_rate'))).aggregate(total=Sum('b_tot')).values() user_total_pay = all_reports.annotate(p_tot=Sum(F('hours') * F('pay_rate'))).aggregate(total=Sum('p_tot')).values() return JsonResponse(list(chain(query, user_total_bill, user_total_pay)), safe=False) #all user data else: vendors = Vendor.objects.filter(c4).values('name', 'billing_frequency') vendor_user=Vendor.objects.filter(c4).values_list('id') #vendor id's for given billing freq query = all_reports.filter(vendor_id__in=vendor_user).values() #user data user_total_bill = query.annotate(b_tot=Sum(F('hours') * F('bill_rate'))).aggregate(total=Sum('b_tot')).values() user_total_pay = query.annotate(p_tot=Sum(F('hours') * F('pay_rate'))).aggregate(total=Sum('p_tot')).values() return JsonResponse(list(chain(vendors, query, user_total_bill, user_total_pay)), safe=False) else: # vendor_user=Vendor.objects.filter(c2).values_list('id') #vendor info # query = Task.objects.filter(vendor_id__in=vendor_user).values() vendors = Vendor.objects.all().values('name', 'billing_frequency') query = all_reports.filter(c2).values() user_total_bill = query.annotate(b_tot=Sum(F('hours') * F('bill_rate'))).aggregate(total=Sum('b_tot')).values() user_total_pay … -
My action button is causing 404 not found
Here is my Base.html <div class="container"> <div class="center"> <form action='simple_test'> <button id="simple_test" class="button-3d"> Generate</button> </form> </div> </div> Here is my View.py from django.http import HttpResponse from django.shortcuts import render from datetime import datetime from django.template import loader from django.core.files import File from .unun import some_func import random import os def index(request): strinput = {} glued, oldgued = some_func() strinput['IntPassHMTL'] = 433 strinput['StrPassHMTL'] = glued strinput['BeforeGlued'] = oldgued return render(request,'index.html', strinput ) def simple_test(request): strinput = {} # glued, oldgued = some_func() strinput['IntPassHMTL'] = 433 strinput['StrPassHMTL'] = "glued" strinput['BeforeGlued'] = "oldgued" print("Words?") return HttpResponse("This is a fake 404!") Here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), print("simple_test", views.simple_test), path('', views.index, name="index"), ] First of all please do not downvote because I am trying to learn and I understand many people have asked the same or similar questions however, I still have so much to learn and I tried to apply these solutions to my codes and they still do not work right for me not sure what I am missing, and that is why I am here, please help me. -
Django Queryset + looking for all objects that have ALL values in an array in a many-to-many relationship
I am hard coding it here, but in reality this array can have between 1 and 99 values looking_for = ['blue', 'red', 'green'] objects = MyObj.objects.filter(colors__name__in=looking_for) will give me all the objects that have ONE of the colors in ['blue', 'red', 'green'] But I want the objects that have ALL the colors objects with the names mentioned in the array. I want AND not OR. Could not find how to do that. any ideas? -
Django admin edit only field?
I have a model that I only want to use one row of its table. So, on admin, I would like to remove the list and add pages, and only edit the existing object. The model is this: from django.db import models class BannerImg(models.Model): img = models.ImageField(upload_to="banners") banner = models.ForeignKey("app.Model", verbose_name=(""), on_delete=models.CASCADE) class Banner(models.Model): pass Basically, the Banner(pk=1) will be loaded by the frontend to display a landing page hero slider. I want multiple images, but also want them to be on the same admin form, so one could order, add or remove images from the same place. Of course having to Banner objects, wouldn't make sense in this case. I can use inline fields to do the form, but how can I achieve the pages functionality (going directly to edit)? Thanks! -
test return redirect("account_login") in django use pytest
i using pytest and coverage for testing django project But I don't know how to test the else block that has return redirect("account_login") and fix the red part that says coverage. In your opinion, how can I write a test for that else piece and fix the red part that says coverage? views.py @verified_email_required def profile_view(request, username): # We check if the user is logged in? if request.user.is_authenticated: try: profiles = Profile.objects.all()[:4] # get user profile by username profile = Profile.objects.get(user__username__iexact=username) user = User.objects.get(username=username) user_following = following(user) user_followers = followers(user) logged_in_user_following = following(request.user) logged_in_user_followers = followers(request.user) # if user not found raise 404 error except ObjectDoesNotExist: raise Http404 # context data context = { "user": user, "profile": profile, "profiles": profiles, "following": user_following, "followers": user_followers, } return render(request, "user_profile/profile.html", context) # if a user is not login in redirecting to login page else: return redirect("account_login") test_view.py @pytest.mark.django_db class TestProfileView: @pytest.fixture def user(self): user, created = User.objects.get_or_create( # created user username="test_username", first_name="test_first_name", last_name="test_last_name", email="test@test.com", is_active=True, is_superuser=False, ) ( user_email_address, created, ) = EmailAddress.objects.get_or_create( # user email confirmation email=user.email, user=user ) user_email_address.verified = True user_email_address.primary = True user_email_address.save() return user def test_profile_view_when_user_is_authenticated_return_correct_profile( self, user, client ): client.force_login(user) # user logged in response = … -
How do I mirror Django's email validation on the front end
I am using the user registration url from django rest auth: urlpatterns = [ #... path("registration/", include("dj_rest_auth.registration.urls")), #... ] This route includes email validation. However, I would like to prevalidate addresses before I send them to the server. Using a simple regex on the front end allows addresses through that dj_rest_auth doesn't: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) Will allow, for example, a@b.c which django will reject. I would like to match the server side validation as closely as possible with javascript. What regex does dj_rest_auth use? -
For creating app to upload and dislpaly images i am getting, ModuleNotFoundError: No module named 'posts.url'
created Django project called django_project and a new app called posts. (.venv) > django-admin startproject django_project . (.venv) > python manage.py startapp posts django_project/settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "posts", # new ] python manage.py migrate posts/models.py from django.db import models class Post(models.Model): title = models.TextField() cover = models.ImageField(upload_to='images/') def __str__(self): return self.title config/settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media" (.venv) $ mkdir media (.venv) $ mkdir media/images posts/admin.py from django.contrib import admin from .models import Post admin.site.register(Post) python manage.py makemigrations Migrations for 'posts': posts/migrations/0001_initial.py - Create model Post python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, posts, session s Running migrations: Applying posts.0001_initial... OK (.venv) > python manage.py createsuperuser (.venv) > python manage.py runserver "Till here the code worked fine" config/urls.py from django.contrib import admin from django.conf import settings # new from django.urls import path, include # new from django.conf.urls.static import static # new urlpatterns = [ path("admin/", admin.site.urls), path("", include("posts.urls")), # new ] if settings.DEBUG: # new urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) posts/urls.py from django.urls import path from .views import HomePageView urlpatterns = [ path("", HomePageView.as_view(), name="home"), ] posts/views.py from django.views.generic import ListView from .models import Post class HomePageView(ListView): … -
Django models. How do I make "add new" filed in Django?
I am trying to make an OfferUp-like web app using Django Framework. Everything has been going great until I ran into a problem. How could I make it so that users can upload multiple pictures, instead of just one using the models.ImageField() function? You know? We might have users that only have 5 pictures to upload, while another user might have 8. How could I make it so that users can upload into the database as many pictures as they want? -
TypeError for aggregate queryset value in JsonResponse along with other queryset without loop?
I am trying to pass the value of b_tot along with my other queryset in JsonResponse. Is there a different way to get this result? all_reports = Task.objects.filter(start__gte=start, start__lte=end) query = all_reports.values() user_total_bill = all_reports.aggregate(b_tot=Sum(F('hours') * F('bill_rate'))) return JsonResponse(list(chain(query, user_total_bill['b_tot'])), safe=False) and getting the error return JsonResponse(list(chain(query, user_total_bill['b_tot']))) TypeError: 'float' object is not iterable I have to do calculations based involving hours and bill_rate for multiple users that match the input criteria. I cannot change the models so have to work in the view only. What else I tried: json dump and serialize.serializer. Any help would be appreciated, TIA -
How display data on a map using django , leaflet and AJAX
How display data on a map using django , leaflet and AJAX? At what level of even_map.html and how should I add the loop that allows to retrieve the coordinates of the events to be able to add and display markers on the map? Below are my programs. I have no error but the markers are not displayed on the map. #models.py class Evenement(models.Model): name = models.CharField(max_length=20) date = models.DateField() time=models.TimeField() longitude = models.FloatField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) geom = models.PointField(srid=4326, null=True, blank=True,) @property def geom(self): return (self.longitude, self.latitude) def __str__(self): return self.name #views.py def evenement_map(request): all_evenements = Evenement.objects.all() return render(request, 'even_map.html', {'all_evenements': all_evenements}) def EvenementData(request): name = serialize('geojson', Evenement.objects.all()) return HttpResponse(name,content_type='json') #urls.py app_name="evenement" urlpatterns = [ path('evenement_register/', views.evenement_register,name="even_register"), path('evenement/', views.EvenementData, name= 'evenement'), path('evenement_map/', views.evenement_map,name="even_map"), ] #forms.py class evenement_form(forms.ModelForm): class Meta: model=Evenement fields='__all__' widgets={ 'date': DatePickerInput(format='%d/%m/%y'), 'time': TimePickerInput(), 'geom': LeafletWidget(attrs={}), } labels={ 'name': _("Name:"), 'date':_("Date :"), 'time': _("Time :"), 'longitude':_("Longitude :"), 'latitude':_("Latitude :"), 'geom':_("Localisation :"), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('name', css_class='form-group col-md-2 mb-0'), Column('date', css_class='form-group col-md-2 mb-0'), Column('time', css_class='form-group col-md-2 mb-0'), Column('longitude', css_class='form-group col-md-2 mb-0'), Column('latitude', css_class='form-group col-md-2 mb-0'), css_class='form-row' ), Submit('submit', 'Register') ) <!---even_map.html--> <!DOCTYPE html> {% load … -
What is the best way to implement these models?
I am trying to create a social media app where users can sign up, make posts, view others post, like and unlike other Users posts. What would be the best way to implement the models for the like and unlike feature? Initially, I created a post model in a post app and two models: like and unlike in a reactions app. Do you think this is a good idea? -
CSS3/HTML Divs are mismatched somewhere
I'm following along a tutorial and, unfortunately, his code editor automatically indented everything when he copied/pasted a new <div> (Sigh) I assumed I would be able to fix it, however, I'm clearly an idiot. (In the second pic I cut off the top where it has LOGO in the top right on accident in the screenshot) This is what my site looks like This is what I would like it to look like {% extends 'main.html' %} {% block content%} <div class="room-container"> <div> <style> .room-container( display: grid; grid-template-columns: 3fr 1fr; ) </style> <div class="room-container"> <div> <h1>{{room.name}}</h1> <p>{{room.description}}</p> <div class="comment-wrapper"> <h3> Conversations </h3> <hr> {% for message in room_messages %} <div> <a href="{% url 'delete-message' message.id %}">Delete</a> <small>@{{message.user}} {{message.created|timesince}} ago </small> <p>{{message.body}}</p> <hr> </div> {% endfor %} </div> <div> {% if request.user.is_authenticated %} <div class="comment-for"> <form method="POST" action=""> {% csrf_token %} <input type="text" name="body" placeholder="Comment here.." /> </form> </div> </div> </div> {% endif %} <div> <h3>Participants</h3> <hr> {% for user in participants %} <div> <p>@{{user.username}}</p> </div> {% endfor %} </div> </div> {% endblock %} -
Get files local server with django-heroku
I'm developing a project using django, and I'm thinking of deploying my app on heroku, but it doesn't store images and files, and I'd like to store them on a server on my local machine, is there any way or tutorial I can follow ? -
Django for multiplayer games website (poker)
I am creating a poker card game website with javascript, I was wondering if it is possible to make it a multiplayer game and run it live with django as backend (django is the only backend frame work i know, i made many projects but never worked with sockets or channels this is my first project ) -
BLOB/TEXT column 'x' used in key specification without a key length
I am getting hung up on this error. I have moved from SQLLite to MySQL with PythonAnywhere for my Django webapp. When running my migrate command I am getting the following error: BLOB/TEXT column 'Connector' used in key specification without a key length This is the models.py class POS_Accounts(models.Model): Connector = models.CharField(max_length = 100, blank=True) StoreName = models.TextField(blank=True) AccountUsername = models.TextField(blank=False) ExpirationDate = models.DateTimeField(null=True, blank=True) MerchantId = models.TextField(blank=False, max_length=100) AccessToken = models.TextField(blank=False) RefreshToken = models.TextField(blank=False) -
Django: I am getting "ValueError: needs to have a value for field "id" before this many-to-many relationship can be used."
I am trying to write a function record_post that saves a Post with the following model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.CharField(max_length=1000) date_created = models.DateTimeField() platforms = models.ManyToManyField(Platform) And here is the record_post function: def record_post(user, body=None, platforms=None): post = Post( user=user, body=body, date_created=timezone.now(), ) # Add platforms facebook = Platform.objects.get(name="Facebook") if "facebook" in platforms: post.platforms.add(facebook) post.save() return post However, when I run the function I get the following error: ValueError: "<Post: 53>" needs to have a value for field "id" before this many-to-many relationship can be used. -
Avoid database hits when requests are only GET (using django-cachalot)
Django==4.0.6 django-cachalot==2.5.1 Models: from django.db import models from django.urls import reverse class Poll(models.Model): name = models.CharField(max_length=200) def get_absolute_url(self): return reverse("poll", kwargs={'pk': self.id}) def __str__(self): return self.name class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def get_absolute_url(self): return reverse("choice", kwargs={'pk': self.id}) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Templatetags from django import template from django.utils.safestring import mark_safe from polls.models import Question register = template.Library() @register.simple_tag(takes_context=True) def question(context, id): question = Question.objects.get(pk=id) choices = question.choice_set.all() html = "<p>" + question.question_text +"</p>" html += "<p>Answers</p>" for choice in choices: html += "<p>" + choice.choice_text + ": " + str(choice.votes) + "</p>" return mark_safe(html) cache_project/cache/polls/templates/polls/poll_detail.html {% extends 'polls/base.html' %} {% load polls %} {% block content %} <p>Poll: {{ object.name }}</p> <p>Question 1: {% question id=1%}</p> {% endblock %} Admin: from django.contrib import admin from .models import General from django.apps import apps @admin.action(description='Warm cache up') def warm_up(modeladmin, request, queryset): MODELS_AND_APPS = { "Poll": "polls", "Question": "polls", "Choice": "polls", } for model_name in MODELS_AND_APPS: current_model = apps.get_model(app_label=MODELS_AND_APPS[model_name], model_name=model_name) all_instances = current_model.objects.all() list(all_instances) # The very warming the cache up. class GeneralAdmin(admin.ModelAdmin): actions = [warm_up] admin.site.register(General, GeneralAdmin) I … -
How to allow JSON access to the text within a textarea in HTML>
I am trying to create a button that allows users to save edits to a post, which they write in a textarea, through JSON. I am trying to save the data through a PUT request, but I get the following error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) javascript function: function save_edit(id){ console.log("save button is clicked"); const edit_area = document.querySelector(`#edit_area_${id}`); //save the post fetch(`/edit/${id}`,{ method: 'PUT', post: JSON.stringify({ post: edit_area.value }) }) } django.views: def edit(request, post_id): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: return JsonResponse({"error": "Post not found."}, status=404) if request.method == "POST": edited_post = request.POST.get('post') try: post.post = edited_post post.save() except: return JsonResponse({"error": "Editing the post did not work."}, status=404) elif request.method == "GET": return JsonResponse(post.serialize()) elif request.method == "PUT": data = json.loads(request.body) edited_post = data["edit_area"] post.post = data["edited_post"] post.save() else: return JsonResponse({"error": "Need a GET request."}, status=404) html {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself_{{ post.id }}" class="post_itself">{{ post.post }}</h6> {% if post.user == request.user %} <button id="{{ post.id }}" class="edit_button" value="{{ post.id }}">Edit</button> {% endif %} <textarea class="textarea" id="edit_area_{{ … -
AttributeError at /cart 'str' object has no attribute 'get'
in django e-commerce website i have the error AttributeError at /cart 'str' object has no attribute 'get' i'm realy dont what happend, i have the code which must work with my task, but it doesnt work too Please help me U can find a code below my views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Category, Product, Cart, CartItem from django.core.exceptions import ObjectDoesNotExist # Create your views here. def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create(product=product, quantity=1, cart=cart) cart_item.save() return redirect('cart_detail') def cart_detail(request, total=0, counter=0, cart_items=None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass return render(request, 'cart.html', dict(cart_items=cart_items, total=total, counter=counter)) -
Code just work when debuggig line by line
I'm running a django app and when I run in debuung mode, lien per line, the code works well. Bur in normal mode(runserver), somethings not work.. Someone can explain? I'm trying to run the follow code: def edit_picture(form, request, User_): person = Person.objects.get(User=User_) person.Picture.delete(save=False) person.Picture = None person.save() form.instance.Picture = request.FILES['Picture'] return form The rest of the project is ok..