Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django load error
I'm learning django in django tutorial part3 but I have a problem I updated my index view in polls/views.py to use the template I loaded the page by pointing my browser at “/polls/” but this is not working I have a FieldError at /polls/ this is traceback Environment: Request Method: GET Request URL: http://localhost:8000/polls/ Django Version: 2.0.5 Python Version: 3.6.5 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/choco/python3/django/mysite/polls/templates/polls/index.html, error at line 1 Cannot resolve keyword 'pub_' into field. Choices are: choice, id, pub_date, question_text 1 : {% if latest_question_list %} 2 : <ul> 3 : {% for question in latest_question_list %} 4 : <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> 5 : {% endfor %} 6 : </ul> 7 : {% else %} 8 : <p>No polls are available.</p> 9 : {% endif %} 10 : Traceback: -
Django no blank choices for inline formfield
In the django admin pages, I have a model with a field that can be blank. The choice field has a first line with dashes '-----' that allows to leave the field to blank. However using inlines, for the same model, the attribute choice field has no defaut choice for blank. Here is the model: from django.db import models class Character(models.Model): name = models.SlugField() condition = models.ForeignKey( CharCondition, blank=True, null=True) world = models.ForeignKey(World) class World(models.Model): name = models.SlugField() The admin file: class MyBaseModelAdmin(admin.options.BaseModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super(MyBaseModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) if db_field.related_model.__name__ == 'CharCondition': print("{}: CharacterCondition for field '{}'" \ .format(self.__class__.__name__, db_field.name) ) formfield.empty_label = "------" return formfield class CharacterAdmin(MyBaseModelAdmin): list_display = ('name', 'condition',) class WorldAdmin(MyBaseModelAdmin): list_display = ('name',) inlines = (CharacterInline,) class CharacterInline(admin.TabularInline, MyBaseModelAdmin): model = Character extra=2 In the Dango admin pages, the single Character page has a choice field on the condition foreign key. Because it's attribute 'blank' is true in the model, I have listed all different conditions, and the first choice is '-----' for the blank choice which is what I expect. Now on the single World page, I have Character inlines, with two default inlines to fill and save ('extra=2'). … -
write subprocess stdout to file: missing last lines before freeze
A subprocess stdout is saved in a local file, but when this process goes into an infinite loop it appears it didn't print the last stdout lines before the infinite loop to the file. On a django website, a long running subprocess is started from views.py upon clicking a button: argString=' '+user+" "+email+" "+folder command='python '+r'D:\pythonScript.py'+argString with open("D:\folder\stdout_"+user+".txt", "w") as stdoutFile: with open("D:\folder\stderr_"+user+".txt", "w") as stderrFile: pythonProcess = subprocess.Popen(command,bufsize=0,shell=True,stdin=subprocess.PIPE, stdout=stdoutFile,stderr=stderrFile, encoding='utf8') The pythonScript.py subprocess create files in a folder. After creating a file it prints something like "file_number_78.txt is created" to the stdout file. When it goes into the infite loop i might notice the last file created is "file_number_211.txt" but the last message read in the stdout file is "file_number_207.txt is created". So it appears some of the stdout info is stuck in a buffer and not (yet) written to the stdout file. I've tried with buffsize=1 and universal_newlines=True, without buffsize argument, without stdin or with creationflags = DETACHED_PROCESS but nothing i tried so far gave the desired output. -
Using Default Values in Django YAML Fixtures
I have created YAML fixtures for my Django app for development and testing purposes. However, when creating many fixtures there are a lot of rows that repeat in the file: - model: my_app.model pk: 1 fields: name: name1 creation_date: 2018-01-01 00:00:00 +00 modification_date: 2018-01-01 00:00:00 +00 - model: my_app.model pk: 2 fields: name: name2 creation_date: 2018-01-01 00:00:00 +00 modification_date: 2018-01-01 00:00:00 +00 - model: my_app.model pk: 3 fields: name: name3 creation_date: 2018-01-01 00:00:00 +00 modification_date: 2018-01-01 00:00:00 +00 What I would like to do is to have some kind of a template for the fixtures that eliminate the repetition. Along the lines of this: template: &TEMPLATE model: my_app.model fields: creation_date: 2018-01-01 00:00:00 +00 modification_date: 2018-01-01 00:00:00 +00 - << *TEMPLATE pk: 1 fields: name: name1 - << *TEMPLATE pk: 2 fields: name: name2 - << *TEMPLATE pk: 3 fields: name: name3 Is there a way to accomplish this with Django YAML fixtures? -
how to save value ='val' where user ='username' in django
I have a function in admin.py which is generating a token i need to save that token to database. How to do that? token = get_token(key,cert,salt,picval); models.py file content below: The token value is generated and stored in token class GenerateCertificate(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) token = models.CharField(max_length=20, default='') def __unicode__(self): return unicode(self.username) How do I save the new generated token value to token field in database. where username = user1 -
What is a good way to run django management command on production
In a dockerized environment, we run django management command. Essentially running a management command like python manage.py command is single threaded. So Basically we are running single process within a docker container. Now if sometime db connection is reset or some process throws an unhandled exception which kills the process, or any other scenario, the container needs to be restarted in order to make it working again. What I want is something like gunicorn which creates multiple processes and maintains the processes (meaning, kill stale processes, keep on starting new processes on reload etc.). Basically what are some best practices for running management commands in django and flask application. -
Django mezzanine does not recognize correct site
I am trying to use multiple sites in one mezzanine project. I have multiple themes (moderna, nova): HOST_THEMES = [ ('.......', 'nova'), ('different.....', 'moderna'), ] The actual names (first column in HOST_THEMES) correspond to real Sites in DB created with admin. However, the mezzanine completely ignore the request host (or url) and directly go for SITE_ID in settings.py. So I can switch the themes by changing SITE_ID in settings. If I remove the SITE_ID from settings, It crash with an error that SITE_ID is missing (something like that). I am using the django testing server and the "request host header" seems to be correct in browser. How to force the mezzanine to choose the correct SITE_ID according to the request host? What I am missing? -
Remote image upload performs different than development server
My local development and live development server have the exact same code and database (all static/media files upload to s3 storage). I have a Post model with an image field. My Post has an image upload field which uploads via AJAX to my s3 storage. In both my local and live server, the image successfully uploads and the url of that image in my s3 bucket is saved. So when I submit the Post in my local server, it doesn't upload again, I just point to the URL when I render the image. However, my remote server doesn't do this. After I have uploaded the image via AJAX, when I submit the Post form, it then submits the image again (it shows the upload progression on my browser - 3%, 5%, 10% etc...). Any idea why this happens? My code is here: models class Post(models.Model): image = models.FileField(null=True, blank=True) views def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user ... if instance.image: instance.imageURL = "https://s3.us-east-2.amazonaws.com/my-bucket/media/%s" % filename instance.image = None instance.save() return HttpResponseRedirect('/') else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return … -
No matter which gmail id I am using for login I am getting a specific email on {{user.email}} in google OAuth in django 2
I am able to login with gmail but whenever I am displaying the authenticated user's credential it is showing a specific email id's(that i have used in google console) information. Lets say I logged in with parvez@gmail.com or parry@gmail.com. The credentials are still displaying for 'specific@gmail.com'. I tried with different browser still after login it is displaying the credential information of that specific email. Thank you in advance. Settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#o^k=ox&wx!=+jf9d%hgu$9&q)71o0*0$b%etc5j0udn-wc9v*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Authentications.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # <- Here 'social_django.context_processors.login_redirect', # <- Here ], }, }, ] WSGI_APPLICATION = 'Authentications.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': … -
Retrieve the source code of request object
For the curiosity, I test within a CBV by adding print statement: def post(self, request, block_id): sf = inspect.getsourcefile(request) code = inspect.getsouce(request) However, I got the error: TypeError: <WSGIRequest: POST '/article/create/1'> is not a module, class, method, function, traceback, frame, or code object. Request is an object but it prompts that none of a module, class, method, function, traceback, frame, or code object. How does this happen? -
django success messages printed in admin site rather than pages
After a version upgrade from 1.11.1 to 1.11.4 success messages are not displayed in pages but in admin site. what has to be changed... Best Regardsenter image description here messages.success(request, 'denetim başarıyla kaydedildi......') #return render(request, 'islem/tek_sayfa.html', context,) return redirect('index') else: messages.success(request, ' form hatası - tekrar deneyin....') return redirect('teksayfa_yarat') link for image -
Invoking a class based function from a template to do a particular action (a.k.a button events)
I have a listing page (call it a page to list the draft blogs or unpublished blogs). When I click a blog item from the draft, it shows the details on read-only format It provides four functionalities - Close, Edit, Delete, Publish. I have completed Close by calling {% url 'blog:drafts' %}, Edit by calling a class derived from UpdateView and delete by calling a class derived from DeleteView. However, I am stuck at publish since there is no view present to create a class based view and get it done. Other option was to define a function and then invoke that function in urls.py I run into issues when I try this I keep receiving error saying that the function that I invoked is not a valid view I am stuck at this error message for days. Is there any alternate ways to write a "publish" function inside the DetailView class and then invoke that function for the active object from the html template? -
IntegrityError-null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 0, 176, 243)
i used postgresql and my django model is class SelectResources(models.Model): collection_resource = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ PageChooserPanel('collection_resource'), ] class Meta: abstract = True class ResourcePageSelectResources(Orderable, SelectResources): page = ParentalKey('ResourceCollections', related_name='selectresources') class ResourceCollections(ResourcePage): collection_cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text=""" Max file size: 10MB. Choose from: JPEG, PNG """ ) image_text = RichTextField(blank=True, help_text="Text that displays hover the image" ) body_text = TextField(blank=True, help_text="Text that displays on the body" ) collection_heading = TextField(blank=True, help_text="Heading of collections" ) description = TextField(blank=True, help_text="Short description of collections" ) button_text = TextField(blank=True) content_panels = Page.content_panels + [ ImageChooserPanel('collection_cover_image'), FieldPanel('image_text', classname="full"), FieldPanel('body_text', classname="full"), FieldPanel('collection_heading', classname="full"), FieldPanel('description', classname="full"), FieldPanel('button_text', classname="full"), InlinePanel('selectresources', label="selectresources"), ] promote_panels = Page.promote_panels + [ FieldPanel('topic_tags'), FieldPanel('priority'), ] def get_context(self, request, **kwargs): slug = '' context = super(ResourceCollections, self).get_context(request) context = get_data( request, data=context, slug=slug, path_components=kwargs.get('path_components', []) ) return base_context(context,self) def get_template(self, request): return 'resources/collections_index_page.html' when i try to pubilsh the pages with SelectedResources in wagtail admin ,it throws the error IntegrityError-null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 0, 176, 243) without SelectedResources, the page publishes correctly as expected -
IOS in app purchase
I want to integration my Django app to Apple store. When I create book I want to create same thing in apple store in-app purchase. I did it in google with python library(apiclient for google). But I cannot find any documentation or example for it. Does Apple have any api for this issue? -
Does Django have a toolbar for the writing tools? Like Stackexchange or Wordpress's Bold, Italics, and other formatting
I am almost done with the mozilla local library tutorial, and my challenge will soon be to create a simple blog. But I noticed that I do not have a toolbar for word formatting. Questions: Do I have to enable it some how? I tried googling, but I am not finding anything. :( When I am create a blog post in Django, is there a way I can get it to look like the Wordpress create a blog post page? It's pretty convenient and easy to use. -
django app not being able to connect to mysql using pymysql
I have installed the following on my OSX(High Sierra 10.13.4): python 3.6.5 MySQL ver 8.0.11 (Community Edition GPL) And I've installed the following in a virtual environment using venv: Django 2.0.5 PyMySQL 0.8.1 I've created a user 'admin'@'localhost' with root PRIVILEGES, accessed mysql through 'mysql -u admin -p' and created a database. I also changed the ENGINE to 'django.db.backends.mysql' with the corresponding changes in the NAME, USER, and PASSWORD fields and added the following lines to 'manage.py': import pymysql pymysql.install_as_MySQLdb() I was following the basic django tutorial Writing your first Django App, part 2 After creating the polls app and it's associated model, I was instructed to activate the model using: python manage.py makemigrations polls This command is resulting in the following error: django.db.utils.OperationalError: (1045, "Access denied for user 'admin'@'localhost' (using password: NO)") I've attached the screenshot of my terminal below. Any information regarding this error will be helpful. -
Django signals duplicate with unique dispatch id
I have a problem with duplicate signals. I have looked-up the relevant part of Django docs and a similar question on Stackoverflow but I still can't get it working right - i.e. the action that I have planned (creation on an ActivityLog entry) is actually happening 4 times :/ I have added the dispatch_uid and the problem still persists, so I guess I'm doing something wrong. Can you please hint me to the error? Here's my code: signals.py from patient.models import Patient from .models import ActivityLog @receiver(pre_save, sender=Patient) def create_new_patient(sender, instance, **kwargs): ActivityLog.objects.create( user=instance.created_by_user, event='created a new patient', patient_id=instance.patient_id ) and this is it's usage in the patient.apps module: from django.apps import AppConfig from django.db.models.signals import pre_save app_name = "patient" class PatientConfig(AppConfig): name = 'patient' verbose_name = "Patients" def ready(self): from activity_logger.signals import create_new_patient print('Patient APP is ready!') pre_save.connect(create_new_patient, sender='patient.Patient', dispatch_uid='patient') The print Patient APP is ready! does appear twice, and the object gets created 4 times, despite setting the dispatch_uid. What have I misunderstood? -
can't display image in django template
I want to show an image(named 1.png) in the template hashtag_details.html(both image and this files are in same directory) hashtag_details.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Trends Result</title> <!--script> window.setTimeout(function(){ window.location.href = "{{ request.path }}"; }, 3000); </script--> </head> <body> <img src="1.png"> </body> </html> -
How can I know what is cached with django cachalot in my server?
I have Django with Django Cachalot and I need know what is cached with cachalot in my server? I want to use CACHALOT_UNCACHABLE_TABLES parameter and I need to know if this works and certain tables are not cached. I hope that somebody can help me, thank you. I initialized the parameter like this: CACHALOT_UNCACHABLE_TABLES = frozenset(('django_migrations', 'company_company', 'customers_customer, 'auth_user')) -
How to add authentication token in header of `APIClient` in `django rest_framework test`
I am using oauth2_provider for my rest_framework. I am trying to write test case for my api. I have obtained an access token. But I am not able to authenticate user using access token in APIClient I am looking to get this curl command work with APIClient. curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/v1/users/current/ I have tried client.get('/api/v1/users/current/', headers={'Authorization': 'Bearer {}'.format(self.access_token)}) and client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token) Here is the part of snippet from rest_framework.test import APIClient from rest_framework.test import APITestCase .... class APITest(APITestCase): def setUp(self): ... self.client = APIClient() ... response = self.client.post('/api/v1/oauth2/token/', post_data) self.access_token = response.json()['access_token'] def test_get_current_user(self): client.get('/api/v1/users/current/', headers={'Authorization': 'Bearer {}'.format(self.access_token)}) I am getting response <HttpResponseForbidden status_code=403, "text/html; charset=utf-8"> -
Django Rest - Custom JSON based on applied logic
I am trying to create a custom JSON in Django rest framework. (The method used is serializers.ModelSerializer). I am not sure what approach is taken to achieve this. Logic: Check for some data in a model and based on that data further calculation is done over another model. This will go on un till desired output is obtained. How do I setup my serializer and viewset. class DataPointSerializer(serializers.ModelSerializer): class Meta: model = DataPoint fileds = (what goes here ?) def to_representation(self,instance): model_one = model_one.objects.all() calculation using model_one model_two.objects.filter(by calculated data) construct JSON return JSON I would like to know the approach that would take to accomplish this task. -
How can I get the lookup_field value in My Update APIView?
How can I get the lookup_field value in My Update APIView? the bellow is my code: class UserAdminDeleteAPIView(RetrieveUpdateAPIView): model = User serializer_class = UserAdminSerializer permission_classes = [] lookup_field = "username" def get_object(self, queryset=None): username = self.request.data.get('username') # there I get None obj = User.objects.get(username=username) return obj When I access the API by localhost:8000/api/users/user10/delete, I can not get the username(user10). How can I get the username param? -
Django: find the id with a value_list
How do you find the id of a value_list Here is what I have: views.py: group = Groups_By_Dates.objects.filter(date=date) all_groups = group.values_list('time', flat=True) time = Groups_By_Dates.objects.get(time=???) I need to be able find time so that I can use it later in my template for a url. How would I be able to do that? I have tried doing that already but it doesn't work: {% for grouptime in all_groups %} <div class="row1"> <a href='{% url "listbygroup" time.id %}'> {{grouptime}}</a> </div> <div class="row2"> </div> {% endfor %} -
What to write in the documentation in manage.py in Django project?
I write simple Django application for myself for development my Python skills. I add Travis for my project and pre-commit. And Travis shows not a good message for me because I have not written correctly code (PEP 257). I read about PEP 257, but I don't how to correctly to write documentation for my code. For example: manage.py #!/usr/bin/env python """Am I here to need to write documentation? And what am I here to write?""" import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " 'available on your PYTHONPATH environment variable? Did you ' 'forget to activate a virtual environment?' ) from exc execute_from_command_line(sys.argv) Thank you. -
Best database practices for a global single element?
I've been recently developing a Django app (using MySQL) that globally depends on a single constantly-changing list of values. I save them on a JSON Field that's something like {'value1':0.123, 'value2':2.33214, ...} I use a cron job that runs 24/7 that retrieves this object once at the start and then updates it every second. To do this, i do something like L = ValuesList.objects.all().first() if L is None: L = ValuesList.objects.create(my_json=some_default) And this code is pretty much present whenever i want to get the values. If that looks bad, i even used to do try: L = ValuesList.objects.get(id=1) catch: L = ValuesList.objects.create(my_json=some_default) My question comes from that situation, it looks messy because i know beforehand that it's a SINGLE object, so i figured there could be something more appropriate to use for THE object (which, by the way, is guaranteed to exist, the whole business logic depends on this), instead of doing a model, creating tables and then searching for the first element if it exists. Is there a better way that i do not know of to store and retrieve a single object? Thanks!