Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail how to add benefit template context to catalogue view?
I added the discount to productdetailview by adding context and editing the template. Everything works fine in Detailview but the context is not passed to catalogue view so this doesn't appear in browse. I tried to add the same context with little change to the catalogue view but it doesn't work. anyone have any idea? working detail view catalogue views.py Benefit = get_model('offer', 'Benefit') def get_discounts(self): try: discounts = Benefit.objects.get(id=self.object.id ) except: discounts = '' return discounts def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['alert_form'] = self.get_alert_form() ctx['has_active_alert'] = self.get_alert_status() ctx['benefits'] = self.get_discounts() return ctx stock_record.html <!--Added discount price--> {% if benefits %} <mark class="sale">Product in Sale!</mark> {% with type=benefits.type %} {% if type == 'Percentage' %} <p> Price after {{benefits.value}}% discount </p> <p class="price_color">{{ session.price.excl_tax |percent:benefits.value|currency:session.price.currency }}</p> {% elif type == 'Absolute' %} <p> Price after {{benefits.value}}{{session.price.currency }} discount </p> <p class="price_color">{{ session.price.excl_tax |subtract:benefits.value|currency:session.price.currency }}</p> {% endif %} {% endwith %} {% endif %} -
Django elastic search dsl-drf
RequestError at /elastic-producthub/category-search RequestError(400, 'search_phase_execution_exception', 'No mapping found for [division_id] in order to sort on') this is the error am getting from django elastic search dsl .Actually I have a model called category and have a foreign key called division. Here, I want to perform a search query on category with division name. -
How To Skip RSS Feeds Missing Certain Attributes
I have a list of RSS feeds that i want to parse in my Django Application. Some contain all my desired attributes, others don't have some of the attributes. The ones that miss my desired attributes keep crashing my program. I keep getting such errors. raise AttributeError("object has no attribute '%s'" % key) AttributeError: object has no attribute 'summary' My model class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title', null=False) link = models.URLField(max_length=500, verbose_name='Post Link', null=False) summary = models.TextField(verbose_name='Post Summary', null=False) image_url = models.URLField(max_length=500, null=False, verbose_name='Post Image URL', default='') slug = models.SlugField(unique=True, max_length=500, null=False) tags = TaggableManager() pub_date = models.DateTimeField(verbose_name='Date Published', null=False) guid = models.CharField(max_length=500, verbose_name='Guid Code', null=True) feed_title = models.CharField(max_length=500, verbose_name='Feed Channel Title', null=False) feed_description = models.TextField(verbose_name='Feed Channel Description', null=False) date_created = models.DateField(auto_now_add=True, verbose_name='Date Created', null=False) last_modified = models.DateField(auto_now=True, verbose_name='Last Modified', null=False) source = models.ForeignKey(Source, on_delete=models.CASCADE, verbose_name='Source', null=False) category = models.ForeignKey(Categories, on_delete=models.CASCADE, verbose_name='Category', null=False) def __str__(self): return f"{self.title} - {self.feed_title}" class Meta: verbose_name_plural = 'Posts' My RSS save function if not Posts.objects.filter(slug=post_slug).exists(): try: post = Posts.objects.get(slug=post_slug) except Posts.DoesNotExist: post = Posts( title = post_title, link = post_link, summary = post_summary, image_url = image_link, slug = post_slug, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_description = channel_feed_desc, source_id = … -
how can I get requests(module name) data parameter to my dJango server?
my tkinter app def _calculation(self): myList = [1,2,3,4,5] url = "http://127.0.0.1:8000/test" response = requests.post(url, data=json.dumps(myList)) my dJango Server @csrf_exempt def test(request): print(request.data) # why error happen? return HttpResponse('') I am making a tkinter app(front) and django Server(back) post matching, but I can't get requests(module name) data(request parameter) from django server. how can I get requests data parameter -
how to show all product when not apply any filter
class ProductListView(TemplateView): template_name = "storefront/shop/product/list.html" def get_context(self,request,id,slug, *args, **kwargs): category = get_object_or_404(Category,id=id,slug=slug) return category.get_option_list_context(request) def get(self, request,id, slug, *args, **kwargs): template=self.template_name if request.GET.get('ajax'): # print("In ajax call") template = "storefront/shop/product/includes/sidebar.html" if request.GET.get('pagination_ajax'): template = "storefront/shop/product/includes/list-ajax.html" return render(request, template, self.get_context(request,id, slug, args, kwargs)) -
Django: AuthStateMissing at /oauth/complete/google-oauth2/
I am using social-auth-app-django for GoogleOauth2 authentication. It works fine for all users but in case of django admin it gives me following error: AuthStateMissing at /oauth/complete/google-oauth2/ Session value state missing. I have tried all answers posted on stackoverflow but the error still persists. This is the result it returns. The state value seems to be present there but either it gets null or overridden somehow. This is my GoogleOAuth2 class, created by overriding social-auth-app-django's GoogleOAuth2 class. Though there is not much difference except for pipeline from base class. It works fine for non-admin user login. class GoogleOAuth2(GoogleOAuth2): """Google OAuth2 authentication backend""" name = 'google-oauth2' REDIRECT_STATE = False AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/auth' ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token' ACCESS_TOKEN_METHOD = 'POST' REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke' REVOKE_TOKEN_METHOD = 'GET' # The order of the default scope is important DEFAULT_SCOPE = ['openid', 'email', 'profile'] EXTRA_DATA = [ ('refresh_token', 'refresh_token', True), ('expires_in', 'expires'), ('token_type', 'token_type', True) ] def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs): out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) user_ip = get_request_ip_address(self.strategy.request) if not isinstance(out, dict): return out user = out.get('user') if user: user.social_user = out.get('social') user.is_new = out.get('is_new') if user.is_new: logger.info(f'Register attempt', extra={"email": user.email, "remote_ip": user_ip, "status": "success", "user_id": user.pk, "oauth_backend": "google"}) else: logger.info(f'Login attempt', extra={"email": user.email, … -
FlowPaper Integration with Python
I want to integrate Flowpaper as ebook viewer in my python/django web but unable to do it as there is no documentation. Kindly help me by providing the same or any good alternate ebook viewer. -
Cannot start apache server with mod_wsgi config
I am trying to set up a simple django app on a windows vm with apache2 server and mod_wsgi. I cannot start apache server after adding wsgi config. LoadFile "C:/Python310/python310.dll" LoadModule wsgi_module "C:/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Python310" WSGIScriptAlias / "C:/Users/karna/Desktop/webproject/webproject/wsgi.py" WSGIPythonPath "C:/Users/karna/Desktop/webproject/" <Directory "C:/Users/karna/Desktop/webproject/webproject/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/Users/karna/Desktop/webproject/static/" <Directory "C:/Users/navar/Desktop/webproject/static/"> Require all granted </Directory> This is the error i am getting in apache logs. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 1800:tid 628] AH00455: Apache/2.4.52 (Win64) mod_wsgi/4.9.0 Python/3.10 configured -- resuming normal operations [Mon Jan 31 05:58:26.207229 2022] [mpm_winnt:notice] [pid 1800:tid 628] AH00456: Apache Lounge VS16 Server built: Dec 17 2021 10:17:38 [Mon Jan 31 05:58:26.207229 2022] [core:notice] [pid 1800:tid 628] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Mon Jan 31 05:58:26.222856 2022] [mpm_winnt:notice] [pid 1800:tid 628] AH00418: Parent: Created child process 2784 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Python310' sys.base_exec_prefix = 'C:\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Python310' sys.exec_prefix = 'C:\\Python310' sys.path = [ 'C:\\Python310\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python … -
How do I pass URLs from my Django rest API to the Flutter front-end
I am very new to Django REST framework and Flutter so if the solution to this is very simple I apologies. I am trying to pass the URLs from my Django back-end to the Flutter front-end. I feel like the solution is a urls.dart file where I can store all the URLs from Django. However, I have no idea what the code for this file would look like. Here are the URLs that I need passed over urlpatterns = [ path('', views.getRoutes), path('notes/',views.getNotes), path('notes/create/', views.createNote), path('notes/<str:pk>/update/', views.updateNote), path('notes/<str:pk>/delete/', views.deleteNote), path('notes/<str:pk>/',views.getNote), ] It is not deployed so I am using localhost. When I implement the URLs into the flutter code I want them to look something like this: .put(updateUrl(widget.id), body: {'body': controller.text}); widget.client.post(createUrl, body: {'body': controller.text}); Any help would be much appreciated. -
FATAL: password authentication failed for user in Postgresql
GETTING AN ERROR IN POSTGRESQL (connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "postgres" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "postgres") -
creating a List type Field/attribute in django model
What I'm trying to do class Node(models.Model): Name = models.CharField(max_length=10) Ancestor = models.CharField(max_length=10) Descendent = models. In the Descendent attribute I want to assgin a list of objects of Node. What can I Do? -
How to access a field from a ForeignKey on a Queryset in django?
This is my models.py: class Computer(models.Model): name = models.CharField(max_length=40) ip = models.GenericIPAddressField(blank=True, null=True, unique=True) class Template(models.Model): data = models.JSONField(...) computer = models.ForeignKey(Computer,on_delete=models.CASCADE) When I delete a template object, from django admin, I need to make an API request, so I edited the delete() method. That works fine. But this doesn't work for the multiple delete option in django admin. I already know that I have to edit the delete_queryset() in admin.py. What I need to know is how to get the field IP from Computer from the queryset that the delete_queryset() method returns. When I do the following in admin.py: class TemplateAdmin(admin.ModelAdmin): def delete_queryset(self,request,queryset): print(queryset) print(queryset.values('computer')) ... And I try to delete multiple template objects (A,B and C) I get the following response: <QuerySet [<Template: A>, Template: B>, Template: C>]> <QuerySet [{'computer': 22}, {'computer': 21}, {'computer': 21}]> 22 and 21 are the computer_id referenced by the ForeignKey in A,B and C. The question is, how do I access the IP field from those computers so that I can make the API request in the delete_queryset() method? -
django unable to connect with postgres from docker container
Dockerfile FROM python:3.8 ARG index_url ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/report_backend COPY ./ /usr/src/report_backend RUN apt-get -y update RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose file version: "3.9" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" django db settings DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "story", "USER": "monetree", "PASSWORD": "Thinkonce", "HOST": "dev.report.inergio.io", "PORT": 5432 }, } Here i am trying to connect local server database. but i am getting below error web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: FATAL: database "story" does not exist here is my database. database already exist but it is not working . psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) Type "help" for help. postgres=# postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -------------+----------+----------+---------+---------+----------------------- postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | story | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =Tc/postgres + | | | … -
Picking database in django
I am developing a patient tracking system. to summarize. I need a database in the backend where we create a flexible schema (will evolve over time) for keeping track of health related data. I have some of the fields I want in it now. also i will develop front-end portal that people can access themselves or be access by an admin where we will ask questions that fill those fields. That front-end will also display to the user or the admin a summary of those datapoints. Can anyone tell me does postgresql can solve this problem or should i choose mongoDB? i am so sorry for posting without code, actually i tried of making decision which one should i choose. -
Docker-compose cant reach second command
I have my docker-compose.yaml file like this: version: "3" services: app: build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" sh -c "python simple_script.py" and the problem is that when i run docker-compose up it never reaches the second command ( sh -c "python simple_script.py" ) . I think this is because the first command sh -c "python manage.py runserver 0.0.0.0:8000" never exits. Is there a way to run two commands like this? -
Async Class Based Views in Django
I am new to Django and I have been working on a Stripe based application and I found out that my class based views are quiet slow and I need to make them run as fast as possible. I discovered that in Django there is Asynchronous Support available but I am unable to figure how can I use it in class based views everywhere I find there are functional based example just. Django documentation that I was looking into was: Django Asynchronous Support I am adding an example code where I want to convert it into async support view VIEW: class BillInfo(DisablePATCHMethod, generics.RetrieveAPIView): serializer_class = BillSerializer SERIALIZER: class BillSerializer(ReturnNoneSerializer, serializers.ModelSerializer): interval = serializers.CharField(read_only=True, required=False) amount = serializers.IntegerField(read_only=True, required=False) date = serializers.DateTimeField(read_only=True, required=False) is_active = serializers.BooleanField(read_only=True, required=False) subscription_expiry = serializers.BooleanField(read_only=True, required=False) active_jobs = serializers.IntegerField(read_only=True, required=False) class Meta: model = Billing fields = "__all__" def to_representation(self, validated_data): stripe.api_key = settings.STRIPE_API_KEY stripe_sub = (stripe.Subscription.retrieve(self.context["request"].billing.stripe_subscription_id)) stripe_object = stripe_sub.get("items") quantity = stripe_object.get("data")[0].get("quantity") amount = stripe_object.get("data")[0].get("price").get("unit_amount") // 100 * quantity interval = stripe_object.get("data")[0].get("plan").get("interval") date = datetime.fromtimestamp(stripe_sub.current_period_end).strftime("%Y-%m-%d %H:%M:%S") if validated_data.subscription_end < make_aware(datetime.now()): is_active = False else: is_active = True if validated_data.subscription_end <= make_aware(datetime.now()): subscription_expiry = True else: subscription_expiry = False return { "date": date, "interval": interval, "amount": … -
Should I a create a separated model/table to organize info?
Supposing that I have a group of data, such as Payment data, like status, amount, external id and etc, and the actual model that this data is related: Order, should I create one model for each, such as: class Product external_id = models.IntegerField() ... class Order payment = models.ForeignKey(Product) Or should I just put the Product data directly into Order fields, to avoid a new table creation? Note: the example is in django, but I think that it should apply for all database designing cases. -
Message doesn't close
I'm making a website and when I give invalid input to my login & register pages (or any other), an error message pops up, however when I click on the '⨯', I can't close it. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ main.html: <html lang="en"> {% load static %} <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Favicon --> <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" /> <!-- Icon - IconMonster --> <link rel="stylesheet" href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css" /> <!-- Mumble UI --> <link rel="stylesheet" href="{% static 'uikit/styles/uikit.css' %}" /> <!-- Dev Search UI --> <link rel="stylesheet" href="{% static 'styles/app.css' %}" /> <title>DevSearch - Connect with Developers!</title> </head> <body> {% include 'navbar.html' %} <!-- {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} --> {% for message in messages %} <div style="display: flex; justify-content: center;"> <div class="alert alert--{{message.tags}}"> <p class="alert__message">{{message}}</p> <button class="alert__close">⨯</button> </div> </div> {% endfor %} {% block content %} {% endblock content %} </body> <script src="{% static 'uikit/app.js' %}"></script> </html> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JavaScript: // Invoke Functions Call on Document Loaded document.addEventListener('DOMContentLoaded', function () { hljs.highlightAll(); }); let alertWrapper = document.querySelector('.alert') let alertClose … -
How to have a Python Django map with a satellite view using from django.contrib.gis.db import models?
I know python and I know a bit of Django. Lately I have been trying to upgrade my maps that I use in my app to a satellite view. Right on my map I am able to draw multiple polygons and save it to the database (postGres). I am using the following to draw the map: from django.contrib.gis.db import models ... ... myMap = models.MultiPolygonField(verbose_name="Boundaries Map", null=True, blank=True, srid=4326) The only thing I wanted to do is instead of having the map View have a Satellite view. Does anyone know any way of doing it? -
RelatedObjectDoesNotExist?
can someone help me to understand want seam to be the problem I Create a model in a e-comers website. models: class Customer (models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(null=True, max_length=200) email = models.CharField(null=True, max_length=200) def __str__(self): return self.name then in views i add it to the cart: def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] context = {'items': items} return render(request, 'ecomeres/cart.html', context) -
Django Templates vs React - Already started down the templates route
I'm currently in the process of learning Django to make a web application for my workplace. I initially had the thought of just learning Django first to get the hang of it, then once I had the core logic in place I would then move over to a React for the UI (also need to learn how to use React), instead of templates. I'm now at the point where I could switch, but I've now only just discovered that I should be developing the backend with the Django REST framework to provide APIs for React (and other front ends). Is this something I can easily transfer to? Or is there a way to use React with my existing Django setup? I'm on a slightly tight timeframe and don't exactly need the core features of React right now. Is it better to get the main web application online sooner with Templates (continuing development down that route) or transition now to React and the REST API and finish the rest of the features after? Will it become too big of a task down the track to transition? -
Override create() method in ModelSerilizer and get object by ID (Django 3.2)
Main Model class Main(models.Model): title = models.CharField(max_length=255) event = models.ForeignKey('Event', null=True, on_delete=models.CASCADE) Event Model class Event(models.Model): day = models.DateField(u'Day of the event', help_text=u'Day of the event', null=True) JSON Structure example: { "titre": "main", "event": { "id": 13, #can't filter or get object by id "day": "2022-01-30", } } Override create() in Serializer: class MainSerializer(serializers.ModelSerializer): event = EventSerializer() class Meta: model = Main fields = '__all__' def create(self, validated_data): event_data = validated_data.pop('event') event = Event.objects.get(id=event_data['id']) main = Main.objects.create(event=event, **validated_data) return main So I encounter an error "KeyError id" and I can't add the object. -
How to make graphql query that can find "latest" or "min" or "max"
I'm trying to use graphql with python to retrieve the latest item added to a temperature table. The temperature table has 2 columns: timestamp and value. My models.py is: from django.db import models class Temperature(models.Model): timestamp = models.DateTimeField(auto_now=True) value = models.FloatField() def __str__(self): return f"the value:time is {self.value}:{self.timestamp}" and schema.py is: import graphene from graphene_django import DjangoObjectType from temperature import models class Temperature(DjangoObjectType): class Meta: model = models.Temperature class Query(graphene.ObjectType): temperature = graphene.Field(Temperature, id=graphene.Int()) def resolve_temperature(self, info, **kwargs): id = kwargs.get("id") if id is not None: return models.Temperature.objects.get(pk=id) return None schema = graphene.Schema(query=Query) I want to make one query thatt returns the latest temperature added, like this: query { currentTemperature { timestamp value } } And another query that returns the min and max temperatures over a timespan, like this: query { temperatureStatistics(after: "2020-12-06T12:00:00+00:00", before: "2020-12-07T12:00:00+00:00") { min max } } I am having a lot of trouble finding documentation on how to accomplish this. I've looked at these graphql docs and this stackoverflow post. I've looked at other things as well but these are the only things that came close to helping. -
Using graphene-django to get "max" from DB
How do you implement an SQL "max" equivalent with graphql? The query should return the object from the database with the max value in a certain column. I have tried things like this from this stackoverflow post with no success: query { table_name(limit: 1, order_by: {time: desc}) { data time } } Where is tells me: { "errors": [ { "message": "Unknown argument \"limit\" on field \"table_name\" of type \"Query\".", "locations": [ { "line": 2, "column": 15 } ] }, { "message": "Unknown argument \"order_by\" on field \"table_name\" of type \"Query\".", "locations": [ { "line": 2, "column": 25 } ] } ] } I have also looked at these graphql docs that didn't tell me anything. Am I supposed to implement this in the schema.py file with a resolver? -
How To Create Model Django For Fixed Question And Integrated with user document?
I have three user in my app. AUTHOR REVIEWER ADMINISTRATOR The flow in app like this: AUTHOR input data document data document will receive by REVIEWER and then he will review that document. REVIEWER will do review with answer five fixed question provided by ADMINISTRATOR. My question is how to create models? I have tried created models like this : models.py from django.db import models from django.conf import settings from dashboard.models import UserUsulan class Question(models.Model): question = models.TextField() def __str__(self): return str(self.question) class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) usulan = models.ForeignKey(UserUsulan, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.BooleanField(default=False) def __str__(self): return str(self.usulan) And then i'm confused. How To Show The Reviewer Question to Template. Please help, your answer very precious to me. Thanks