Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cart quantity model for order and for item
thanks for your time. i got a shopping-cart app with Order->Pedido and Item models. And those are related through ManytoManyField. when the first time any user add a product to his cart the Item object gets created. So i set a quantity field on the Item model to get increassed +1 every time that Item has been ordered. So i could get how many times that item got ordered. i'm trying to get a field that shows me how many Items of that Item are in the cart at that order (and them sum and checkout the order). And a field to shows me how many of that item have already been ordered in all time. should i create a Quantity model? i've read some questions and still kinda lost. products/Models.py: class Produto (models.Model): model = models.ForeignKey(Modelo, on_delete=models.CASCADE, related_name='mod') nome = models.CharField(max_length=200) preco = models.DecimalField(max_digits=5, decimal_places=2) created_time = models.DateTimeField(auto_now=True) updated_time = models.DateTimeField(auto_now_add=True) shoppingcart/Models.py: class Item(models.Model): product = models.OneToOneField(Produto, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) date_ordered = models.DateTimeField(null=True) quantity = models.PositiveIntegerField(default=1) def __str__(self): return self.product.nome class Pedido(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(Item) date_ordered = models.DateTimeField(auto_now=True) shopping_cart/views.py: @login_required(login_url='/accounts/automatic') def add_to_cart(request, **kwargs): … -
If statement in template Django now
I have created 2 apps: 1. Score for uploading posts by users 2. Core for uploading items by users In the home.html I am trying to add a button only if there are posts submitted by user to appear Here is the template: {% if not posts %} <a href="{% url 'score:user-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-success btn-sm btn-block"> Click Here</button></a> {% else %} {% endif %} Here are the core app views.py: class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] here are the score post models: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to="media") title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank=True, null=True, max_length=120) -
Error saving cidrfield field from django admin interface
The issue I am facing is trying to save a cidrfield (imported from netfields) in the djanog admin interface. I have the following models: from django.db import models from netfields import CidrAddressField # Create your models here. class Zone(models.Model): zone_text = models.CharField(max_length = 20, unique = True ) def __str__(self): return self.zone_text class Vlan(models.Model): zone = models.ForeignKey(Zone, on_delete=models.CASCADE) vlan_id = models.IntegerField(default = 0, unique = True ) subnet = CidrAddressField( unique = True ) def __str__(self): return str(self.vlan_id) I am able to create a new Vlan entry from the django shell: >>> v = Vlan.objects.create(zone=z, vlan_id="2", subnet="192.168.2.0/24") >>> type(v.zone) <class 'network.models.Zone'> >>> type(v.vlan_id) <class 'str'> >>> type(v.subnet) <class 'ipaddress.IPv4Network'> >>> But when I attempt to add a new Vlan entry via the django Admin interface, I receive the following error: InterfaceError at /admin/network/zone/1/change/ Error binding parameter 0 - probably unsupported type. Request Method: POST Request URL: http://127.0.0.1:8000/admin/network/zone/1/change/ Django Version: 3.0.6 Exception Type: InterfaceError Exception Value: Error binding parameter 0 - probably unsupported type. Exception Location: C:\Users\elijah\python_projects\project1\lib\site-packages\django\db\backends\sqlite3\operations.py in _quote_params_for_last_executed_query, line 141 Python Executable: C:\Users\elijah\python_projects\project1\Scripts\python.exe Python Version: 3.8.2 This django site is running on my local machine using sqlite3 as the DB. Any idea what I'm missing? Any help is greatly appreciated. -
How to add Data in Django Relation table?
I have 2 tables in my Database, first is city and the second is builder, I have some data store in my builder table, and the city name is stored in the city table. Now, When I will submit builder data then each builder can have multiple cities, so I want to create another table builder_city, where data will be store in this format id,city_id, builder_id, It means when I will submit my form then builder names will be store in builder table and the selected multiple cities from builder form will be store in builder_city table with builder_id and city_id. Please let me know how I can do this. I am doing this, Please check my views.py code.. def add_builder(request): city=City.objects.all() if request.method == 'POST': name = request.POST.get('name') slug = request.POST.get('slug') meta_title = request.POST.get('meta_title') meta_desc = request.POST.get('meta_desc') meta_keyword = request.POST.get('meta_keyword') bldlogo = request.POST.get('bldlogo') data = SubCategory(name=name, slug=slug, meta_desc=meta_desc, meta_title=meta_title, meta_keyword=meta_keyword, bldlogo=bldlogo) data.save() return redirect('/dashboard/builder') else: return render(request, 'adminpanel/builder/create.html', {'city':city}) -
Django Bootstrap Modal Ajax - 1st time it works perfectly, 2nd time - no luck
I am using Django 2.2 with Bootstrap. This is the approach used for Opening a modal window , User updates the data, User saves it Underlying table from where the window was opened is updated and modal window is closed Till here everything works perfectly, however, the issue occurs when you click the same button to open the window. Here when you click the button, nothing happens ! This is the javascript file. $("#modal-risk-profile").on("submit", ".form-risk-profile", function () { var form = $(this); $.ajax({ url:form.attr("action"), data:form.serialize(), type:form.attr("method"), dataType:'json', success: function(data) { console.log(data.form_is_valid); if(data.form_is_valid) { console.log(data.html_planner_client_list); $("#id_client_table tbody").html(data.html_planner_client_list); // if you remove this line, modal window appears without any issues $("#modal-risk-profile").modal("hide"); console.log("I have returned with success"); } else { console.log("I am in else"); $("#modal-risk-profile .modal-content").html(html_form); } } }); return false; }); The output of the html_planner_client_list is as follows: <tr> <td> Rajesh </td> <td> 01-04-2000 </td> <td> Bangalore </td> <td> ramachandran.test@gmail.com </td> <td> Salaried </td> <td class="text-center"> <button class="button-risk-profile btn btn-danger btn-sm py-0" style="font-size:0.9em" data-url="/client/riskprofileplanner/19/"> Take Questionnaire </button> </td> <td> Subramanian</td> <td class="text-left"> <a href="/client/client_select/19/" class="btn btn-primary btn-sm py-0" style="font-size: 0.9em;">Select </a> <a href="/client/client_edit/19/" class="btn btn-primary btn-sm py-0" style="font-size: 0.9em;">Edit </a> <a href="/client/client_report/19/" class="btn btn-primary btn-sm py-0" style="font-size: 0.9em;">Report </a> <button class="button-choose-planner … -
Django cannot find GDAL on windows 10 64 bit
I am using PyCharm and Python 3.8 - 64 bit. I am trying to learn to implement GeoDjango and Leaflet with a Postgis database. I have a postgresql database with postgis extension. I also have psycopg2 installed following the comments from this earlier thread of mine. psycopg2 not detected by postgres django In settings.py, DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my-database', 'USER': 'my-user', 'PASSWORD': 'my-password', 'HOST': 'localhost', 'PORT': '5432', } } When I try to run python manage.py makemigrations I get the following error. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", … -
Django - Manually set the values of ManyToMany Field on form submit (multiple inputs to one field)
The hardest question i asked so far. I have a Book Model with a many to many relationship to my Tag model. I need to split the tags by type, in diferent inputs () and then mix all the inputs in the single ManyToMany Field of my book model. My Book Model: class Book(models.Model): project = models.ForeignKey(Project, on_delete=models.PROTECT, verbose_name="Proyecto") user = models.ForeignKey(UserSap, on_delete=models.PROTECT, verbose_name="Autor principal") authors = models.ManyToManyField(Account, blank=True, verbose_name="Otros Autores") title = models.CharField(max_length=220, verbose_name="Titulo del libro") editorial = models.CharField(max_length=220, verbose_name="Editorial") isbn = models.CharField(max_length=17, verbose_name="ISBN") publicationYear = models.CharField(max_length=4, verbose_name="Año de publicacion") tags = models.ManyToManyField(Tag, blank=True, verbose_name="Etiquetas") file = models.FileField(upload_to="archiving/", verbose_name="Libro (PDF)") created = models.DateTimeField(auto_now_add=True) product = models.CharField(default="book", editable=False, max_length=15) def __str__(self): return self.title def get_absolute_url(self): return reverse("book:book-detail", kwargs={"id": self.id}) MY Tag Model: Tag.tag mean the type of tag ( the rightmost column inputs represents the type of tags) class Tag(models.Model): name = models.CharField( max_length=100, verbose_name="Nombre de la etiqueta") tag = models.CharField(max_length=10, verbose_name="Tipo") def __str__(self): return f'{self.name}' def get_absolute_url(self): return reverse("tag:tag-detail", kwargs={"id": self.id}) My create View: I tryed doing this by querying the multiple inputs into the tables their scooped then got the objects and add em to the many to many fields before saving the whole new book in def … -
How to add a reply to a comment in a post section in Django
I am trying to add a reply to comments on a post section for a post I have commented out the reply that I have added in the views.py as it is not working at all The templates are working perfectly but with every new reply comment is added not a reply so the issue is with the views I guess I have added a reply section to the comment models as following: models.py class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) user = models.ForeignKey( User, on_delete=models.CASCADE) reply = models.ForeignKey( 'Comment', on_delete=models.CASCADE, null=True, related_name="replies") content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} by {}'.format(self.post.title, str(self.user.username)) here is the views: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') #reply_id = self.request.POST.get('comment_id') comment_qs = None #if reply_id: #comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class … -
Django - Generic m2m relation or two m2m relations?
I'm building a Movie database. The thing is each movie can have many producers and many directors. The directors can be either persons or collectives, and the producers might be persons, collectives or institutions (or a mixture of all these things). I also want to store different information for these kinds of entities (persons, collectives and institutions). Furthermore, I need: To have order (director1, director2) is different from (director2, director1) The admin to be able to handle producer/director adding, modifying, etc. from the Movie module. To organize my models I've thought of having a generic m2m relation (inspired in this answer) --only for directors, to simplify: class Movie(models.Model): name = models.CharField(max_length=100) # etc... class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) director_of = GenericRelation('Directorship') class Collective(models.Model): name = models.CharField(max_length=100) number_of_participants = models.IntegerField() director_of = GenericRelation('Directorship') class Directorship(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='directors') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') order = models.PositiveIntegerField() The problem with this solution is that the Movie admin with a Directorship inline looks awful: I could customize the admin form to display a specific ModelForm depending on the choice of the first combobox, but that looks like an awful lot of work … -
POST method not being submitted by form django
I have two radio buttons and i want one of them to be selected and send to my Django views.py template.I can't use django.forms for specific reasons.The page hardwareq1 is linked to hardware1 in urls.py .My problem is a None Object is sent to the backend after i press submit. Please tell what is wrong with my code. HTML:- <form action="{% url 'hardwareq1' %}" method="POST"> <label class="btn btn-success"> <input type="radio" id="control_1" name="question_type" value="Indoor" />Indoor </label> <label class="btn btn-success" > <input type="radio" id="control_1" name="question_type" value="Outdoor" />Outdoor </label> <input type="submit" value="Submit" class="btn btn-secondary btn-block" /> </form> urls.py path('hardwareq1',views.hardware1,name='hardwareq1'), views.py:- def hardware1(req): h=HardwareModel.objects.all().filter(productid=1) print(req.POST.get('question_type')) if req.method=='POST': h.q1=req.POST.get('question_type') h.save(force_update=True) context={ 'hardware':h } return render(req,'pages/shardware1.html',context) -
AttributeError: 'module' object has no attribute 'lru_cache' in Apache using Python3
I'm having trouble running my Django application through Apache. Running Django on the built in development server works fine, as does serving html files directly through Apache. I originally had the error 'no module named django.core.wsgi' which I remedied by updating the WSGIPythonHome directive to point to the python3.6/site-packages directory. After doing this from looking at the traceback the server appears able to locate django.core.wsgi but now throws the error: AttributeError: 'module' object has no attribute 'lru_cache' I read it could potentially be a Python2 / Python3 issue with Apaches version of mod_wsgi so I reconfigured Apache and reran make, make install but no luck there. I found the same question posted here: AttributeError: 'module' object has no attribute 'lru_cache' and tried the recommended solution of removing libapache2-mod-wsgi and installing libapache2-mod-wsgi-py3 both system wide and within the virtual environment I'm pointing to in my httpd.conf file. This didn't fix the issue either. What could be the cause ? Help is greatly appreciated ! Full traceback: [Sat Jun 06 10:00:57.085731 2020] [wsgi:error] [pid 14226:tid 139691700082432] [client 127.0.0.1:60174] Traceback (most recent call last):, referer: http://127.0.1.1/ [Sat Jun 06 10:00:57.085749 2020] [wsgi:error] [pid 14226:tid 139691700082432] [client 127.0.0.1:60174] File "/WEBPAGE/myproject/wsgi.py", line 12, in <module>, … -
django.db.utils.IntegrityError: UNIQUE constraint failed: core_user.email
I'm trying to do a unit test for my model, but it kept throwing IntegrityError. I've researched many articles and in StackOverflow to find solutions but couldn't find. I am trying to create a unit test for the admin app of Django application Commands to reproduce: docker-compose runs app sh -c "python manage.py test" This is the output: ====================================================================== ERROR: test_users_listed (core.tests.test_admin.AdminSiteTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: core_user.email The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 14, in setUp self.user = get_user_model().objects.create_user( File "/app/core/models.py", line 11, in create_user user.save(using=self._db) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 782, in save_base updated = self._save_table( File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 924, in _do_insert return manager._insert( File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1392, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 68, … -
How can I select two ranges of the same field in Django?
With the following model: class Event(models.Model): latitude = models.FloatField() longitude = models.FloatField() I would like to execute the following logic: Select all events where latitude is in range(float1, float2) or in range (float3, float4) This looks like this in SQL: SELECT * FROM event WHERE latitude (BETWEEN float1 and float2) or (BETWEEN float3 and float4); I tried this in Django but I get a "SyntaxError: keyword argument repeated": Events.objects.filter(latitude__range(float1, float2), latitude__range(float3, float4) -
my detail view is updating but not redirecting me to my blog post Django
i have a single Blog,which is still the main Detailview,so i am trying to add class base view,for CRUD,so i redirected my detailview to my blogpost,but when i add new post it will only show the pagination,but the post will already be added to my blogpost not until i go to the blog home page,even when i search blog with http://127.0.0.1:8000/pages/blog/22/?= , but wont show the post views.py class BlogDetailView(DetailView): model = Blog template_name = 'pages/blog.html' context_object_name = 'blog' ordering = ['-timestamp'] urls.py path('blog/', blog, name='blog'), path('blog/<int:pk>/', BlogDetailView.as_view(), name='blog'), -
how to call function based view using DefaultRouter in?
I tried to run run server in Django but unfortunately i have got an error AttributeError: 'function' object has no attribute 'get_extra_actions'. urls.py here is the url file where router is defined for the view. from rest_framework.routers import DefaultRouter from django.conf.urls import url, include from enable_app import views router = DefaultRouter() router.register(r'practice', views.practice, basename='practice') url patterns = [ url(r'^', include(router.urls)), ] views.py here is the views file where function based view is written from rest_framework.response import Response from rest_framework import viewsets def practice(request): return Response('hello world') here is the errors. errors Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/getmyparking/PycharmProjects/enable_practice/venv_prac/lib/python3.7/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, … -
CSRF verification always fails when accessing Django admin page through nginx proxy
I have gunicorn serving a Django (v3.0.6) project on my server (at port 8000). I have the host name (and variations on localhost) in the ALLOWED_HOSTS variable of my Django project. And I have nginx set up to serve various apps within my Django project via a reverse proxy, like this: location /guestbook/ { proxy_pass http://localhost:8000/guestbook/ ; } These all seem to work just fine, for the record. What isn't working fine is the Django admin app. Initially I set it up with a very simple reverse proxy as shown above, but over time, as I was experiencing problems with it, I started incorporating various suggestions I found online until now it looks like this: location /admin/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_set_header Upgrade $http_upgrade; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://localhost:8000/admin/ ; } but my problem persists: If I visit the admin site (via the nginx proxy) remotely after clearing all my cookies, the admin page loads just fine. I type in my login credentials, hit "login" and nothing happens. If I hit login again, the CSRF verification fails, and if I have DEBUG set to True Django says the CSRF … -
Django REST Framework. Keep getting KeyError in all the methods
After some time of testing my Django REST Api i started to get KeyError when using request.data. The problem didn't occured before that, it just randomly started to happen. Im using Python 3.8 and Django REST 3.11 Here are my serializers and views. I'll appreciate any help. serializers.py class InterestSerializer(serializers.ModelSerializer): class Meta: model = Interest fields = '__all__' class UserIntrestSerializer(serializers.ModelSerializer): interest = InterestSerializer() class Meta: model = UserInterest fields = ('id','interest') views.py class UserInterestView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserIntrestSerializer def get_user_interests(self, request): try: user = get_object_or_404(User, pk=request.data['id']) interests = UserInterest.objects.all().filter(user__id = user.id) serializer = UserIntrestSerializer(interests, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except MultiValueDictKeyError: return Response("No data given", status=status.HTTP_204_NO_CONTENT) def create_user_interests(self, request): try: user = User.objects.get(pk=request.data['id']) interest_list = [Interest.objects.all().filter(name=interest)[0] for interest in request.data['interests']] print(interest_list) for interest in interest_list: UserInterest(user=user, interest=interest).save() return Response("User interests created properly") except IndexError: return Response("Interest not found", status=status.HTTP_404_NOT_FOUND) except User.DoesNotExist: return Response("User not found") def delete_interest(self, request): try: userinterest = UserInterest.objects.get(interest__name=request.data["interest_name"], user__id=request.data["user_id"]) userinterest.delete() return Response("User's interest deleted properly", status=status.HTTP_200_OK) except UserInterest.DoesNotExist: return Response("User or User's interest not found", status=status.HTTP_404_NOT_FOUND) def update_interest(self, request): try: user = User.objects.get(pk=request.data['id']) current_interests = [user_interest.interest for user_interest in UserInterest.objects.all().filter(user__id=user.id)] new_interests = [Interest.objects.get(name=interest) for interest in request.data['new_interests']] for current_interest in current_interests: if current_interest not in … -
How to display posts on homepage? Django
In my system, admin create posts and I want to display them on homepage with paginators. But when I add homepage, nothing is showing up on the page. When I view source from browser, I cannot see for loop like templates/homepage.html ... <div> {% for post in self.posts %} <div class="panel panel-primary"> <div class="panel-heading text-center"> <a style="color: black"> <h3>{{posts.title}}</h3> </a> </div> <div class="panel-body"> <h4><p class="text-success">Title: <small>{{post.title}}</small></h4> <h4><p class="text-success"> <small>{{post.text}}</small></h4> <h5><p class="text-warning">Created Date: {{post.created_date}}</h5> </div> </div> {% endfor %} </div> <ul> <div class="row" > <div class="col-md-6 col-md-offset-3"> <ul class="pagination"> <div class="pagination"> <span class="step-links pagination"> {% if posts.has_previous %} <li><a href="?page={{ posts.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">Previous</a> {% endif %}</li> <li ><span class="current"> Page {{ posts.number }} of {{ posts.paginator.num_pages }}. </span></li> <li>{% if posts.has_next %} <a href="?page={{ posts.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">Next</a> {% endif %} </li> </span> </div> </div> </div> </ul> </div> . . . blog/views.py def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') query = request.GET.get('q') if query: posts = posts.filter( Q(title__icontains=query) | Q(text__icontains=query) | Q(created_date__icontains=query) | Q(published_date__icontains=query) ) paginator = Paginator(posts, 5) # Show 5 contacts per page page = request.GET.get('page') try: patients = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver … -
Trying to create a dynamic search/filter table for 25 thousand rows of NBA data using Django, Postgresql, and Jquery
But I have no idea what I'm doing. Now this is how far I've gotten: views.py: statsReg = list(seasonstats.objects.filter(pts__gt=2000).order_by('pts')[0:5].values()) stats = simplejson.dumps(statsReg) return render(request, 'djangotest.html', {'stats': stats}) html: <table border="1", id="players", class="text-center"> <tr> <th>Year</th> <th>Player</th> <th>Pos</th> <th>Age</th> <th>Tm</th> <th>G</th> <th>GS</th> <th>MP</th> <th>PER</th> <th>TS%</th> <th>Points</th> </tr> <tbody id="myTable"></tbody> </table> <script> var myArray = {{ stats|safe }}; buildTable(myArray) function buildTable(data){ var table = document.getElementById('myTable') for (var i = 0; i < data.length; i++){ var row = `<tr> <td>${data[i].year}</td> <td>${data[i].player}</td> <td>${data[i].pos}</td> <td>${data[i].age}</td> <td>${data[i].tm}</td> <td>${data[i].g}</td> <td>${data[i].gs}</td> <td>${data[i].mp}</td> <td>${data[i].per}</td> <td>${data[i].tspercent}</td> <td>${data[i].pts}</td> </tr>` table.innerHTML += row } } </script> So this code displays five rows of statistics correctly in a table on my page, but I have a few questions on where to go from here. My first question is if i'm even accessing postgres with this mode.objects call, I've migrated the model to my database and can browse it in psql, but I just don't get how this works. My second question is how I would alter the query by use of a button to for instance, increase the value in the [0:5] part of the query, or change the filter or order. Any comments would be greatly appreciated! -
WSGI: (11) Couldn't create worker thread
I set up an apache2 server running 2 different django projects as virtual hosts using their own subdomain. Both hosts got their own demon WSGI process. However, when I start the apache2 server only one of those 2 projects run properly. Trying to open the index page of project 2 leads to an endless loading try by the browser. So I checked the error.log of apache2 and saw, that it was full of [wsgi:alert] [pid xxxx:tid xxxxxxx] (11)Resource temporarily unavailable: mod_wsgi (pid=xxxx): Couldn't create worker thread x in project2 process project2 It logs this message every 5 sec. or whenever a request for project 2 comes in. That explains, why there is this infinite waiting loop in the browser, but I don't get, why no thread could be spawned. I already looked around the web for a possible solution, but did not find anything helpfull. Most of the findings were either different problems, had no solution or had a solution that was out of date or used files I can't find on my system. Using top I did not find any unexpectedly high usage of CPU or Memory that could explain, why no thread was spawned. I already tried to … -
Django ModuleNotFoundError: No module named 'architect' when start from docker
When I trying start Django from docker I get an error server_1 | return _bootstrap._gcd_import(name[level:], package, level) server_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import server_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load server_1 | File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked server_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed server_1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import server_1 | File "<frozen importlib._bootstrap>", line 991, in _find_and_load server_1 | File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked server_1 | ModuleNotFoundError: No module named 'architect' openfoundation-container_server_1 exited with code 1 But when I run Django manually "python 3 manage.py runserver 7000" then the server starts correctly my dockerfile my docker-compose version: "3" services: server: build: server/ command: "python3 ./manage.py runserver" ports: - 7000:7000 client: build: client/ command: "npm run dev" network_mode: host ports: - 3333:3333 depends_on: - server tree Can u help me please? Thnk! -
DisallowedHost Django deployment in Kubernetes cluster: Invalid HTTP_HOST header
I have a Django deployment for a frontend service in my Azure Kubernetes cluster with some basic configuration. But note that the same question applies for my local Minikube cluster. I fetch my Django frontend container image from my remote container registry and expose port 8010. My service configuration is quite simple as well. frontend.deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: frontend-v1 labels: app: frontend-v1 spec: replicas: 1 selector: matchLabels: app: frontend-v1 template: metadata: labels: app: frontend-v1 spec: containers: - name: frontend-v1 imagePullPolicy: Always image: yourremotename.azurecr.io/frontend-remote:v1 ports: - containerPort: 8010 imagePullSecrets: - name: acr-secret frontend.service.yaml kind: Service apiVersion: v1 metadata: name: frontend-v1 spec: selector: app: frontend-v1 ports: - NodePort: protocol: TCP port: 8010 targetPort: 8010 type: NodePort Now, when I access my deployed frontend service in the browser i.e. http://172.17.194.253:31436 with Django's setting DEBUG = True, I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/dist-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 122, in get_host raise DisallowedHost(msg) Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: '172.17.194.253:31436'. You may need to add '172.17.194.253' to ALLOWED_HOSTS. But … -
error: failed to push some refs to 'https://git.heroku.com/boytalksaboutcoding.git'
I know that there are a lot of questions like this out there, but none match my problem exactly. I recently made a django blog, and I just added staticfiles(pictures, css etc.). When I pushed to Heroku, it gave me this: Enumerating objects: 41, done. Counting objects: 100% (41/41), done. Delta compression using up to 4 threads Compressing objects: 100% (28/28), done. Writing objects: 100% (30/30), 245.74 KiB | 18.90 MiB/s, done. Total 30 (delta 11), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.7 remote: Learn More: https://devcenter.heroku.com/articles/python-runtime remote: -----> No change in requirements detected, installing from cache remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: -----> $ python manage.py collectstatic --noinput remote: /app/.heroku/python/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. remote: """) remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in … -
How do I maintain session across requests in django if I'm using cache / db based session?
I'm implementing a in-memory cache-based session in django: https://docs.djangoproject.com/en/3.0/topics/http/sessions/#using-cached-sessions session_store = SessionStore() session_store['key'] = value session_store.create() but i found that even though the data does persist in memory across multiple requests, but it wont set the session_key in the cookie. Is the intended usage to just pass the key to client and have them send back as a param? right now im manually setting and retrieving the cookie (as request.session['session_key'] doesnt work for me) CREATE response = Response(serializer.data, status=status.HTTP_201_CREATED) response.set_cookie('session_key', session.session_key) RETRIEVE session_key = request.COOKIES['session_key'] -
Stripe does not work correctly - invoice paid but it does not send randomly 'invoice.payment_succeeded' webhook response - bug?
I am using Stripe Webhook and this is phenomenal. I use Stripe webhook in my Django app like this: class StripeView(GenericAPIView): serializer_class = UserNameSerializer def post(self, request): payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: # Invalid payload return HttpResponse(status=400) print(event.type) if event.type == 'invoice.payment_succeeded': payment_invoice = event.data.object ... Every single time I use exactly the same method exactly the same way and it is executed without any errors in the same way. It looks like this: customer = stripe.Customer.create( email=user.email, source=request.data['token'] ) subscription = stripe.Subscription.create( customer=customer.id, items=[ { 'plan': 'plan_H8K23228WmaQM', 'quantity': request.data['amount'], }, ], expand=['latest_invoice.payment_intent'], ) Once Stripe generate requests in this way: 2020-06-05 22:48:21 --> payment_method.attached [evt_no] 2020-06-05 22:48:21 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:22 --> customer.created [evt_no] 2020-06-05 22:48:22 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:23 --> charge.succeeded [evt_no] 2020-06-05 22:48:23 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:23 --> invoice.created [evt_no] 2020-06-05 22:48:23 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:24 --> invoice.finalized [evt_no] 2020-06-05 22:48:24 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:24 --> payment_intent.succeeded [evt_no] 2020-06-05 22:48:24 <-- [400] POST http://localhost:8007/stripe/ [evt_no] 2020-06-05 22:48:27 --> customer.source.created [evt_no] 2020-06-05 22:48:27 <-- [400] POST http://localhost:8007/stripe/ [evt_no] Other times he …