Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CMS how to blog post
I am learning Django-CMS but I am now extremely good at django. I am not getting how to post through djang-CMS, I have created some pages on Django-cms, just going through menu creation, template, etc. But I couldn't find any menu or option to post something as like as WordPress has add post button. My question is, should i add new app named blog and configure a with `app hook` or there is a good way to make a blog site? Their documentation are not too good and too old documentation. as a beginner, I confused anything. I need someone suggestion what i need to do to post with django-CMS? even i can select category etc through django-CMS, how can i do it? -
Django - Factoryboy: __str__ call with stringformating resturns object instead
I'm creating a number of tests for a Django app whilst using factory-boy to generate the model instances. However, I have tests thats failing but I'm not entirely sure why this is the case. def test__str__(self) -> None: self.assertEqual( str(self.academy_settings), "Academy settings for {}".format(self.academy_settings.academy), ) As you can see I'm verifying a __str__ method on one of our django models, but when I run this test I get the following error. Failure Expected :"<AcademySettingsFactory for <class 'core.models.AcademySettings'>>" Actual :'Academy settings for <factory.declarations.SubFactory object at 0x1105ce438>' These errors are somewhat puzzling to me. Its clear that the actual result is nothing like the result that I am expecting, but the same could be set for the expected result. As you can see in the model definitions below both of them should return simple string objects. class Academy(models.Model): name = models.CharField( max_length=400, unique=True ) def __str__(self) -> str: return "{}".format(self.name) class AcademySettings(models.Model): academy = models.ForeignKey(Academy, on_delete=models.CASCADE) (...) def __str__(self) -> str: return "Academy settings for {}".format(self.academy) Now, as you can see in the factories below I've written some custom lazy_attribute to keep the name field unique, but even without that code the errors keeps getting raised. So I'm not sure what is … -
TypeError: PaginationMiddleware() takes no arguments when trying to use django-pagination
I'm trying to make django-pagination work with djano-filter since I'm working with very large tables. But after implementing it, when I try to do python manage.py runserver, I get a TypeError: TypeError: PaginationMiddleware() takes no arguments This is what I have done so far: 1. Installed django-pagination(1.0.7): pip install django-pagination Added it in INSTALLED_APPS in settings.py: INSTALLED_APPS= [....,'pagination',] In my TEMPLATES in settings.py: 'OPTIONS':{'context_processors': ['django.template.context_processors.request'],}, In MIDDLEWARE in settings.py: MIDDLEWARE = [...,'pagination.middleware.PaginationMiddleware',] In html file: {% load pagination_tags %} ... {% autopaginate filter.qs 40 as filter_list %} {% for f in filter_list %} ... {% endfor %} {% paginate %} I have all this, but when I try to do runserver I get the following error: File "D..Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 36, in load_middleware mw_instance = middleware(handler) TypeError: PaginationMiddleware() takes no arguments Am I missing something here? Any help is appreciated. Django version: 2.1.13 Python version: 3.8 -
Django- Celery - Issues when Using Namespace and AWS SQS
I'm using Celery for a few tasks. In celery.py I have: from __future__ import absolute_import, unicode_literals from django.conf import settings import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') app = Celery('Project') # # Using a string here means the worker doesn't have to serialize # # the configuration object to child processes. # # - namespace='CELERY' means all celery-related configuration keys # # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # # Load task modules from all registered Django app configs. app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Settings.py BROKER_URL = 'sqs://' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_IGNORE_RESULT = False CELERY_DEFAULT_QUEUE = env('CELERY_DEFAULT_QUEUE') CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_BACKEND_DB='db+postgresql://USER:PASSWORD@HOST:PORT/DB_NAME' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'us-east-1', 'polling_interval':20, 'visibility_timeout': 3600, 'task_default_queue': env('CELERY_DEFAULT_QUEUE'), } When I run it the tasks run. The problem is that I need to add namespace='CELERY' to celery.py app.config_from_object('django.conf:settings', namespace='CELERY') This is what I get when I add the namespace. [2019-11-14 15:01:00,377: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 2.00 seconds... If I change BROKER_URL= 'sqs://' to CELERY_BROKER_URL='sqs://' or CELERY_BROKER_URL='sqs://{}:{}@'.format( quote_plus(AWS_ACCESS_KEY_ID), quote_plus(AWS_SECRET_ACCESS_KEY) ) I get: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the … -
DRF serializer for ContentType object return null
I try to work with ContentTypes Framework and DRF. I have followed documentation, generic relationships I have formed BlogPost Model: class BlogPost(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) comments = GenericRelation(Comment) and Comment Model: class Comment(models.Model): comment_author = models.ForeignKey(User, default=1, null=True, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I have formed serializers: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" class CommentedObjectRelatedField(serializers.RelatedField): def to_representation(self, value): """ Serialize tagged objects to a simple textual representation. """ if isinstance(value, Comment): serializer = CommentSerializer(value) else: raise Exception('Unexpected type of commented object') return serializer.data class BlogPostSerializer(serializers.HyperlinkedModelSerializer): comments = CommentedObjectRelatedField(many=True, read_only=True) time_since_publication = serializers.SerializerMethodField() def get_time_since_publication(self, object): publication_date = object.published_at now = datetime.now() time_delta = timesince(publication_date, now) return time_delta class Meta: model = BlogPost fields = ['id', 'pk', 'title', 'slug', 'content','comments', 'published_at', 'timestamp', 'updated', 'time_since_publication'] read_only_fields = ('pk',) lookup_field = ('pk',) When I check the api in the browser I get json answer [ { "id": 1, "pk": 1, "title": "this is title", "slug": "this-is-title", "content": "This is content", "comments": null, "published_at": "2019-11-15", "timestamp": "2019-11-15T12:14:37.336170Z", "updated": "2019-11-15T12:14:37.336208Z", "time_since_publication": "16 hours, 5 minutes" } ] How can I get … -
Python: Attempting to remove whitespace from a csv using DictReader
I am attempting to remove any whitespace surrounding values in a csv file. The following code works as I'd like for a few hundred lines, then stops with the error: print({k: v.strip() for k, v in row.items()}) AttributeError: 'list' object has no attribute 'strip' from csv import DictReader from pathlib import Path for row in DictReader(open(Path('my_file.csv'))): print({key: value.strip() for key, value in row.items()}) The following is extracted from the csv I am using, the first row is the final row that works using said code. The second is the row that seems to throw the error. (note: they scroll to the right quite a bit - damn whitespace) "203506","0","NEWEY'S GIFT ","RM","WILL OF 13TH JULY 1720 (U.V.22 PP 83);","DIOCESE OF EXETER.","","F","","","","","","","","","","" "203508","0","CATHERINE MARY HAY'S GIFT ","RM","\"DECLARATION OF TRUST\" OF 2.1.1923, AS MENTIONED IN CERTIFIED COPY OF RECORDED MINUTE OF THE DEAN AND CHAPTER.;","EXETER","","F","","","","","","","","","","" I have only been programming for a year and using python around a month of that, so nothing in the csv jumps out as unusual to me. Any help is appreciated. endnote: This code is extracted from a django project I have created, maybe there is a function within the framework which could help that I have missed. -
Django: Getting an Error Saying "needs to have a value for field "id" before this many-to-many relationship can be used"
I am a beginner in Django. Right now, I am learning the framework by uilding an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. When I go to http://127.0.0.1:8000/index, I see this page: When I click on Samsung, I see this page: Up to this is fine. But when I click on any phone model, like Galaxy S10, I get 404 error. It looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/details/galaxy-s10 Raised by: PhoneReview.views.ReviewView No review found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error. I thought that performing migration and adding a new review about any phone model, like Galaxy S10, through Django admin would fix the issue. But when I try to add a review for the Galaxy S10 … -
How can the django admin url pattern be modified so the links have unique urls?
I'm trying to add oracle legacy tables that has no pk but a composite pk, only which are unique together, to django admin. When inspecting the URLs to make the change to the objects, they are all the same. Django can't auto create a pk id because oracle will throw an error. This forces one of the fields to be pk which isn't unique, causing get() return more than 1 row. Several issues or requests How can more fields be added to get so it doesn't just use the arbitrary pk. The fields can be concat in str which shows the pair in the view but where else can I store this pair so it can be passed to get the unique object for change. If meta unique_together is set, how can I tell the queryset to use this pair and not the arbitrary pk when building the model list. -
What is the most reliable and efficient way to ensure Twilio sends a chain of messages in order?
I'm attempting to lay the foundation for a relatively simple messaging system using Twilio API and its Python wrapper. Users should be able to text a keyword and receive back a string of responses. The problem is, using the suggested HttpResponse() package from Twilio's documentation, when I loop through the messages to add them to a response chain, they hit Twilio in a block, and sends the service sends them in a seemingly random order, which really compromises the readability of the block. Here's a simplified version of the loop I'm running in Django to create the response: @csrf_exempt def inbox(request) if request.method == "POST": # Interpret the keyword in the incoming message data = request.POST messageBody = data['Body'].lower() # Check if it matches a valid keyword targetTrigger = Keyword.objects.get(trigger_word=messageBody) # Pull the appropriate responses messageChain = Message.objects.filter(keyword_answers=targetTrigger) # Create the messaging response resp = MessagingResponse() # Populate it with messages for sms in messageChain: resp.message(sms) # Send them to Twilio return HttpResponse(str(resp)) I've glossed over the try and error catches for the sake of readability. And like I said, this sends the messages in a seemingly random order, with shorter messages appearing to send through to my iPhone first … -
PyCharm does not automaticaaly recognise a sqlite3 database inside a Django project
I am following a Django tutorial. After creating the project tictactoe, I opened it using PyCharm professional According to some PyCharm tutorials the database should be automatically recognised and should appear on the database windows. This is not the case. According to other PyCharm tutorials I should be able to drag the db.sqlite3 file into the database windows to automatically connect to the database and this is also not working. Could someone guide me step by step and explain how do I connect to the DB and how I visualise its content? Thank you for your help -
Could not parse the remainder: ' .counter' from 'forloop .counter'
< h1 > {{ question.question_text }} </ h1 > {% if error_message %} < p >< strong > {{ error_message }} </ strong ></ p > {% endif %} < form action = " {% url 'polls:vote' question.id %} " method = "post" > {% csrf_token %} {% for choice in question.choice_set.all %} <% input type = "radio" name = "choice" id = "choice {{ forloop .counter }} " value = " {{ choice.id }} "% > < label for = "choice {{ forloop .counter }} " > {{ choice.choice_text }} </ label >< br > {% endfor %} < input type = "submit" value = "Vote" > </ form I have this error running the command: python manage.py runserver "django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: ' .counter' from 'forloop .counter'" How can i fix this error? Thanks. -
Sending a cURL POST request as a link
I have a LAMP Django API that sends out a text message to my customer which says Click [This Link] to do A and [Another Link] to do B. I've been using POST requests to take in data to my API but that's been me polling directly from cURL in cmd. I want to create the request, then be able to send it out as a link to my client, then they click it and the post request is sent to my API. Is this possible? -
DJANGO virtual env unable to import models
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Trying to import django model but i have a virtual env which might be the cause not sure -
Unable to map values to a different key in Django Rest Serializer
I am trying to serialize input data to different keys using Django Rest Framework serializer like this class BooHoo(serializers.Serializer): boo = serializers.CharField(source="hoo") boohoo_serializer = BooHoo(data={"hoo": 1234}) I am expecting the validated_data to be, in this case {"boo": 1234} But when I call is_valid() it throws error that boo is required field and when I provide default=None in serializer I always get None in the result. Somewhere it's not mapping the value to the source key. -
Django Signal when User closes broswer
I have two signals for user login and logout to handle various things such as storing user session information, particularly login and logout time. Issue arises when the user closes the browser and not explicitly logs out the user_logged_out signal isn't triggered. So the logout time is never stored. The user can use various tabs during a session so simply using ajax to manually logout a user won't handle this edge case correctly. Is there any other signal or implementation I can use to handle a user closing the browser and not just a tab? My code: @receiver(user_logged_in) def update_user_login(sender, user, request, **kwargs): ... @receiver(user_logged_out) def update_user_logout(sender, user, request, **kwargs): ... -
Send two forms one button in django, fix error
in django template I have code {% include 'temp/first_page.html' %} {% include 'temp/last_page.html' %} in these two templates two different form, example at first: <form name='first'> </form> in second: <form name='second'> </form> when I send these form by one button with code: document.forms['first'].submit(); document.forms['second'].submit(); sometimes I get just second form, first not sending in POST. How can I fix this error? -
How to authorize an app with Google in Django on a live site
I am working with the Google Calendar API, but this would be applicable to any of their APIs. I followed the quickstart example that they provide, and in a local environment, this works great. The main issue that I'm facing is that in a local environment, the code they provide is setup to automatically open a URL to authorize the application once authorization becomes necessary. This isn't the case in a live environment, and it has to do with this section of the code: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) But, I don't quite understand what I should be calling in place. Here's the full code of what they provide: from __future__ import print_function import datetime import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] def main(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if … -
Creating dependency in two Django Models
Im developing a site in django with two models: Match, Month I want to Update a query in Match model so it will update a specific query in Month model aswell. models.py: from django.db import models class Month(models.Model): name = models.CharField(max_length = 20) matches_count = models.IntegerField() class Match(models.Model): first_team = models.CharField(max_length = 20) second_team = models.CharField(max_length = 20) in_month = models.CharField(max_length = 20) I Have made those queries in my views.py file: _query_one = Month(name = 'January',matches_count = 0) _query_one.save() _query_two = Month(name = 'February',matches_count = 0) _query_two.save() _query_three = Match(first_team = 'LA',second_team = 'NYC', in_month = 'March') _query_three.save() _query_four = Match(first_team = 'SF',second_team = 'LV', in_month = 'February') _query_four.save() My goal is to update the new 'matches_count' value of February month from 0 to 1. I've searched for a smarter way to do that except of just running this snippet right after the query: _query_to_update = Month.objects.get(name = 'February') _query_to_update.matches_count = 1 _query_to_update.update() I was thought that there is a special type of Field in django for dynamic update. Or, a specific code to run that validates that models Match and Month having a dependency. I also thought that this is a very common need for any django developer … -
how to make JsonResponse can be accessd by everyone without needing for login django?
how to make JsonResponse can be accessd by everyone without needing for login django? Is there anyway to make a function public like below: def json_response(request): t={'tawfiq':'Accountant'} JsonResponse(t) I just read about API and AllowAny but I couldn't figure out how to do it. I will be very grateful for help -
Django: Problem with Creating a Clickable Link in Template
I am doing a Django project, named PhoneRadar. I have a template page (details.html), which looks like this: As you can see, the link is not clickable. How can I make it clickable? Here are my codes of models.py: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=150, null=True, blank=True) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform = models.CharField(max_length=100) slug = models.SlugField(max_length=150, null=True, blank=True) def __str__(self): return self.model_name def save(self, *args, **kwargs): self.slug = slugify(self.model_name) super().save(*args, **kwargs) class Review(models.Model): phone_model = models.ManyToManyField(PhoneModel, related_name='reviews') review_article = models.TextField() date_published = models.DateField(auto_now=True) # slug = models.SlugField(max_length=150, null=True, blank=True) link = models.TextField(max_length=150, null=True, blank=True) def __str__(self): return self.review_article Here are my codes of details.html located inside templates folder: {% extends 'PhoneReview/base.html' %} {% load static %} <html> <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}"> <html lang="en"> {% block title%}Details{% endblock %} {% block content %} <h1>This is the Details Page</h1> <h2>Review:</h2> <p>{{ review.review_article }}</p> <h2>News Link:</h2> <p>{{ review.link }}</p> {% endblock %} </html> How can … -
consumer: Cannot connect to redis://localhost:6379//: Error 61 connecting to 127.0.0.1:6379. Connection refused
I'm trying to get celery up and running on Heroku as per the woeful instructions here whenever i try to run "heroku local" it gives me the error: consumer: Cannot connect to redis://localhost:6379//: Error 61 connecting to 127.0.0.1:6379. Connection refused.. any help is much appreciated. -
Django-filter - filter an annotated field
I'm using Django-filter on my django-tables2 table, I have a custom filter that uses one search box to search all fields. However I cannot currently filter on any annotated fields, is this possible with the custom filter given below? I want to filter on active_circuit what I tried thus far is adding, which did not work class SiteFilterEx(django_filters.FilterSet): ex = django_filters.CharFilter(label='Ex filter', method='filter_ex') connectivity = django_filters.CharFilter(field_name="active_circuit") search_fields = ['connectivity','location'... filter: class SiteFilterEx(django_filters.FilterSet): ex = django_filters.CharFilter(label='Ex filter', method='filter_ex') search_fields = ['location', 'sitesupernet__subnet', 'bgp_as', 'opening_date','town','postcode','active_circuit'] def filter_ex(self, qs, name, value): if value: q_parts = value.split() # Use a global q_totals q_totals = Q() # This part will get us all possible segmantiation of the query parts and put it in the possibilities list combinatorics = itertools.product([True, False], repeat=len(q_parts) - 1) possibilities = [] for combination in combinatorics: i = 0 one_such_combination = [q_parts[i]] for slab in combination: i += 1 if not slab: # there is a join one_such_combination[-1] += ' ' + q_parts[i] else: one_such_combination += [q_parts[i]] possibilities.append(one_such_combination) # Now, for all possiblities we'll append all the Q objects using OR for p in possibilities: list1=self.search_fields list2=p perms = [zip(x,list2) for x in itertools.permutations(list1,len(list2))] for perm in perms: q_part = Q() … -
django authenticate user and generate JWT token
I wanna authenticate user to get JWT token which later I will pass to JS. But I'm getting the error saying: django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint My login functions: views.py def loginTest(request): user = authenticate( username=request.GET.get('username'), password=request.GET.get('password')) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) urls.py from .views import loginTest urlpatterns = [ path('api/auth', loginTest), ] App.vue mounted() { const url = window.location.origin axios.post(url+'/accounts/api/auth?username=myUsername&password=1243') .then(response => { console.log(response) }) .catch(error => { console.log(error) }) } the error which I'm getting is: django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint and have no idea why I like that -
Popup rendering with close button but it does not work when clicked?
I have a custom popup that shows upon form submission to let the user know it was successful. Currently it displays when it's supposed to (although I can't get it to display in the middle right on top, but that's a minor issue) like shown below: But the little X button does not actually close the message. You can click it but it does nothing, and if you reload the page then it's gone until you submit again. base.html {% load static purchasing_tags humanize %} {% include 'operations/message.html' %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static 'images/favicon.ico' %}" type="image/x-icon" rel="shortcut icon"/> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="{% static "css/plugins/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "css/apps.css" %}" rel="stylesheet"> <script src="{% static "js/plugins/jquery.js" %}"></script> <script src="{% static "js/plugins/bootstrap.min.js" %}"></script> <!--[if lt IE 9]> <script src="{% static 'js/plugins/respond.js' %}"></script> <![endif]--> </head> <body> <div id="login" class="panel panel-default"> <div class="panel-body"> {% block main %} {% endblock main %} </div> <div class="panel-footer"> {% block panel_footer %} {% endblock %} </div> </div> {% if messages %} <script> {% for message in messages %} $(document).ready(function () { $('.toast').toast('show'); }); {% endfor %} </script> {% endif %} </body> … -
How can i retrieve specific data using axios.Right now it is returning all the data from database
How can i retrive a specific data using axios.It is returning all the data from database .My frontend is react js and backend is python django