Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in Creating history record using Django Simple History
Why Django-Simple history records get created on calling save method if I call update then it doesn't create history record ? Django : 1.11.15 Django-simple-history : 1.9.0 Python : 3.6 -
Using force_authenticate() for serializers testing in Django REST Framework
I want to use reverse from rest_framework library. I used it like this: reverse('admin:rooms') but in serializers testing, I get an error that I have to authenticate as an admin first, then do the reversing process. How can I use force_authenticate() in my test? -
How to store values (given by user via postmain) in the variables with POST method using Django restful services
I need help to store values for x , y, z into the variables with Django restful services. With the php this can be done with similar to below code. var1 = $_POST['x']; var2 = $_POST['y']; var2 = $_POST['z']; I have started learning Django (mainly Restful API) and easily learned to do many other things (which is not that easy to do with PHP) with Django such as insert, del, update data configured swagger and admin but I did not find a way to store value in variable. I want to store these variables to 'return' the kind of data that is being requested (these variable will have value something like that). -
TemplateDoesNotExist, Django has the good path but can't open the file
I have a problem with my Django project : the Templates engines search at the good path but they don't find it... I tried everything :/ I think my settings.py file is ok : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'public', ] 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', ], }, }, ] I put my register.html in C:\SitePetitDejs\public\templates\public (yes the path is strange but it symplifies the problem) And, when I go on http://127.0.0.1:8000/public/register I have "TemplateDoesNotExist at /public/register" error The strangest thing is that the engines search at the good path : django.template.loaders.filesystem.Loader: C:\SitePetitDejs\templates\public\register.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\victo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\public\register.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\victo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\public\register.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\SitePetitDejs\public\templates\public\register.html (Source does not exist) Very blur behavior from the engines... Maybe they don't have the permissions ? I don't know how to solve this problem, I hope will be able to help me :) Thankss -
complexity of a reverse django foreign key lookup
Assume I have a model like this: class Post(models.Model): name = models.CharField(max_length=25, unique=True) class Picture(models.Model): post = models.ForeignKey(to=Post, ondelete=models.CASCADE) image = models.ImageField() Now assume I do a query something like this: p = Post.objects.get(name=foo) images = p.picture_set.all() Now the first query obviously searches through all the posts to get the one that has name foo. But I would like to know about the second one. Does it search through all the Picture table in the database to find all the pictures that have post=p or is the information available when I get p in the first query? Because if it's the former, then I am worried about scalbility issues. -
How to get Django to accept date format dd/mm/yyyy?
I have a model form that won't accept my new date format input for date field (I want to accept dd/mm/yyyy). How can I get the model to accept my new formatting? When I submit the form, it says to "Enter a valid date". Note, I'm changing the datefield input to textinput using a widget so I can use bootstrap's datepicker and use a text placeholder. Here is my code: In settings: DATE_INPUT_FORMATS = ['%d/%m/%Y', ] In forms.py: class WorkExperienceForm(ModelForm): class Meta: model = WorkExperience fields = ['position', 'company', 'city', 'start_date', 'end_date', 'achievements', 'resume', ] widgets = {'start_date': TextInput(attrs={'class': 'date-picker', 'placeholder': 'DD/MM/YYYY'}), 'end_date': TextInput(attrs={'class': 'date-picker', 'placeholder': 'DD/MM/YYYY'}), In models: class WorkExperience(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE, blank=True) position = models.CharField(max_length=255, blank=True) company = models.CharField(max_length=255, blank=True) city = models.CharField(max_length=255, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) -
Django unique together constrain with relations
I'm writing a REST API using Django and Django Rest Framework. I'm currently writing the models. I have a model for students, a model for questions and a model for answers. class Question(models.Model): question_text = models.CharField() class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField() class Student(models.Model): name = models.CharField() The students should be able to pick one and only one answer per question. So I was thinking of designing a student picked answer model - so that I can let the students pick through a relation - like this: class StudentPickedAnswer(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) I found that there is a unique_together constraint for the class Meta. But it seems to me that it can't specify relations. I would need something like this; class Meta: unique_together = ('student', 'answer__question') How can I achieve that the students can only pick one question per answer? Or is picking through a model with relations a bad design? -
server error 500 when waiting after clicking
I'm testing with Selenium a function for my Django project. I've got a button to be clicked which redirect to another page, after some processing. I use to test it: @classmethod def wait_until(cls, findhow, findwhere): WebDriverWait(cls.selenium, 10).until(EC.presence_of_element_located((findhow,findwhere))) So, I click on the button with selenium: self.wait_until(By.ID, 'text_table') but I've got immediately (without any pause) a 500 server error, with the traceback: Traceback (most recent call last): File "/mnt/backup/BACKUP_Aubrey/workspace/LingL/functional_tests/selenium_text_detail.py", line 56, in test_create_a_new_text self.wait_until(By.ID, 'text_table') File "/mnt/backup/BACKUP_Aubrey/workspace/LingL/functional_tests/selenium_base.py", line 53, in wait_until EC.presence_of_element_located((findhow,findwhere)) File "/home/campagne/backup_ln/.Envs/LingL/lib/python3.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: (the Message part is empty) Any idea? It looks like it isn't waiting in fact? -
ManyToMany field selects all model instances by default
I changed my .all method so it would select only instances with published=True: class EventManager(models.Manager): def all(self, *args, **kwargs): return super().get_queryset().filter(published=True, *args, **kwargs) This is my related model fields: class Event(models.Model): related_events = models.ManyToManyField('self', blank=True, related_name='related') published = models.BooleanField(default=False) objects = EventManager() As a result ManyToManyField ends up selecting all the Event instances. What would to suggest me to do in order to save the published functionality and be able to manually add related events? Thank you. -
Running multiple Daphne processes (channels 1.x)
How many messages/second one daphne process can send? I am currently handling 20K messages per second. It works but daphne is not accepting any more connections. I tried to add more processes where each will listen on a different port and will be balanced by an nginx. It helps for the connection thing but I see some of the messages being dropped since the daphne process is not recognizing the response channel. Is it possible for multiple daphne processes to work on the same websocket connection or do I need to create separation in code? Thanks -
Nginx SSL_ERROR
I've managed to set up a Nginx server on an old laptop connected to my router. MY problem is that when accesing it via the public ip i get This site can’t provide a secure connection and ERR_SSL_PROTOCOL_ERROR while via the internal ip everything works fine. I do not have a domain name, in my nginx config server_name is set to default. I don't really need nor care to use HTTPS but i can't figure out where might the problem be. My configuration is Django+Gunicorn+Nginx. I read about Let's Encrypt and Certbot but they only issue SSL certificates for domain names so that doesn't help me. Bottom line: Is there a setting that i might have overlooked and how can i disable HTTPS? -
Django: integration of external classes?
I apologise in advance for the silly question. :) I am trying to create a REST API using the Django rest-framework. This API sits on top of an algorithm, which I have been trying to integrate within the Django framework, but it is frustrating to do this properly, and I suspect this is due to my poor understanding of Django. Here are my code snippets. models.py from django.db import models class my_model(models.Model): dob = models.TextField() response = models.TextField() field1 = models.TextField() class Meta: ordering = ('dob','response','field1') serializers.py import re import numpy as np from django_rest.quickstart.models import my_model from rest_framework import serializers from rest_framework.renderers import JSONRenderer from my_algorithm import my_algorithm class BazhiSerializer(serializers.ModelSerializer): my_algorithm_instance = my_algorithm() response = serializers.SerializerMethodField('myAlgorithm_wrapper',my_algorithm_instance) field1 = serializers.SerializerMethodField('field1_wrapper', my_algorithm_instance) def myAlgorithm_wrapper(self, my_model, my_algorithm_instance): # Get the inputs. dob = str(my_model.dob) components = np.array(re.split('/| |:', dob)).astype(int) birth_day = components[0] birth_month = components[1] birth_year = components[2] birth_hour = components[3] birth_minutes = components[4] my_algorithm_instance.set_birthdate_time(\ birth_year, birth_month, birth_day,\ birth_hour, birth_minutes) my_algorithm_instance.run() my_structure = my_algorithm_instance.my_struct content = JSONRenderer().render(my_structure) return(content) def field1_wrapper(self, my_model, my_algorithm_instance): another_structure = my_algorithm_instance.another_pillar_struct content = JSONRenderer().render(another_structure) return(content) class Meta: model = Bazhi fields = ('dob', 'response', 'field1') I get an error message, which essentially says that the methods 'myAlgorithm_wrapper' and … -
Django unique together
there' s a db driven application, where there' s a table (view) defined in the db (psql) having 2 keys together as primary key. My belonging django model looks like: class TS(models.Model): id = models.AutoField(primary_key=True) ... class Meta: db_table = '"t_s\".\"vt_s"' managed = False class TSI(models.Model): ts = models.ForeignKey(TS, primary_key=True, on_delete=models.PROTECT, db_column='t_s_id') item_number = models.IntegerField() ... class Meta: db_table = '"t_s\".\"vt_s_i"' managed = False unique_together = (('ts', 'item_number'),) . Or at least i thought unique_together should work like this. Running the following query in the db works fine: insert into t_s.vt_s_i (t_s_id, item_number, ...) values (10, 20, ...); and fails only if the (ts, item_number) combo exists already. Trying to insert a TSI from the django shell however fails: In [29]: ts = TS.objects.filter()[8] In [28]: ts.id Out[28]: 11 In [30]: ts.tsi_set.all() Out[30]: <QuerySet []> In [31]: tsi = TSI(description='First description', t_s = ts, item_number = '600033') In [32]: tsi.full_clean() In [33]: tsi.save() In [34]: ts.tsi_set.all().values('t_s_id', 'item_number', 'description') Out[34]: <QuerySet [{'item_number': 600033, 'description': 'First description', 't_s_id': 11}]> In [35]: tsi = TSI(description='New description', t_s = ts, item_number = '999999') In [36]: tsi.full_clean() --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-36-3a0eb883d57f> in <module>() ----> 1 tsi.full_clean() ~/.virtualenvs/srd/lib/python3.4/site-packages/django/db/models/base.py in full_clean(self, exclude, validate_unique) … -
Django anymail links in emails are changed and don't work
I'm trying to do something which I would have thought should be very simple but appears to be very complicated. I'm using Django Anymail, with SparkPost as ESP. I want to include a link back to my site in the email, something like <a href="www.example.com>click here</a>. However, no matter what I do, that link gets changed to something like: http://go.sparkpostmail1.com/f/a/Vju1M3X6TVz79ONI6TywgA~~/AAOsuQA~/RgRdt_u-... Then, when I click on the link I just get a This site can’t be reached. I've disabled click and open tracking, and I've tried sending the email both as content generated in Django and as a SparkPost template, and I've even tried switching ESP to Mailgun and I get the same results. Here's my Anymail config: EMAIL_BACKEND = "anymail.backends.sparkpost.EmailBackend" ANYMAIL = { "SPARKPOST_API_KEY": "MY_KEY", "SPARKPOST_API_URL": "https://api.sparkpost.com/api/v1", 'SPARKPOST_SENDER_DOMAIN': "mail.mysite.com", "SEND_DEFAULTS": { "track_clicks": False, "track_opens": False, }, } Here's my message sending function: from django.core.mail import EmailMultiAlternatives from smtplib import SMTPException def send_welcome_email( address ): subject, from_email = 'Hello! Thank you for your interest in Discover three.js', 'Discover three.js <welcome@mail.discoverthreejs.com>' html_content = '<a href="www.example.com">click here</a>' message = EmailMultiAlternatives(subject, 'Hello!', from_email, [address]) message.attach_alternative(html_content, "text/html") # alternatively, use sparkpost template #message.template_id = 'welcome' try: message.send() except SMTPException as e: print('There was an error … -
DJANGO unable to use the django admin because of login redirects and middleware
I created a custom User model to replace my Django User model. I have set in my settings file -> AUTH_USER_MODEL = 'accounts.User' , but when I use in one of my views I get an error here users = settings.AUTH_USER_MODEL.objects.exclude(id=request.user.id) class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-date_created') users = settings.AUTH_USER_MODEL.objects.exclude(id=request.user.id) try: friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() except Friend.DoesNotExist: friends = None args = {'form': form, 'posts': posts, 'users': users, 'friends': friends} return render(request, self.template_name, args) The error is as follows users = settings.AUTH_USER_MODEL.objects.exclude(id=request.user.id) AttributeError: 'str' object has no attribute 'objects' Any tips appreciated -
Django Rest Framework - JSON Post Request ManyTomany field issue
TLDR; using Django Rest Framework, how can I make a POST (application/json content) to an API Resource that has a Many to Many Relation Field using only the ID/PK for said M2M field? I'm currently modeling an application for a college project that used Django Rest Framework. The following model represents a Volunteer on the application (I've hidden some minor details to avoid polluting the code) class Volunteer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) state = models.CharField(max_length=2, choices=STATE_CHOICES) city = models.CharField(max_length=255) gender = models.CharField(max_length=2, choices=GENDER_CHOICES, blank=True, null=True) phone = models.CharField(max_length=13) email = models.EmailField(max_length=100) description = models.TextField(max_length=500) photo = models.ImageField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) interest_areas = models.ManyToManyField(VolunteeringArea, blank=True) class Meta: verbose_name_plural = "Volunteers" ordering = ("first_name", "last_name") def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return reverse('volunteers:volunteer-detail', kwargs={'pk': self.id}) And the respective serializer looks like this: class VolunteerSerializer(serializers.ModelSerializer): interest_areas = VolunteeringAreaSerializer(many=True) class Meta: model = Volunteer fields = ('id', 'first_name', 'last_name', 'phone', 'email', 'state', 'gender', 'interest_areas', 'city', 'description', 'photo') read_only_fields = ('created_at', ) def to_representation(self, instance): representation = super(VolunteerSerializer, self).to_representation(instance) representation['interest_areas'] = VolunteeringAreaSerializer(instance.interest_areas.all(), many=True).data return representation As you may notice, each Volunteer may have many Interested areas attributed to it (Many to Many Field). The following model represents … -
CSRF verification failed on a fresh django project's admin login
I just created a project in django using django-admin startproject xyz and then, I navigated to the project folder and created a superuser using the command python manage.py createsuperuser on my Ubuntu's terminal and I filled the details. After this, I started the server by python manage.py runserver and I went to http://127.0.0.1:8000/admin/ on my browser and everything seemed to be normal: Image of the admin login page Then, I clicked on the submit button after entering the admin credentials and this showed up: Image of the 403 Forbidden page Please help. -
Using static folding inside app folding Django
I have a static directory inside my apps folder. I added this line of code to my projects settings.py file STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] I'm getting stuck, what should I do? -
django.db.utils.OperationalError: foreign key mismatch - "django_admin_log" referencing "transcript_userprofile"
when I create superuser, I meet this problem. django.db.utils.OperationalError: foreign key mismatch - "django_admin_log" referencing "transcript_userprofile" transcript/models.py: class UserProfile(AbstractUser): student_num = models.CharField(unique=True, null= False, max_length=9) birthday = models.DateField(verbose_name='生日', null=True, blank=True) gender = models.CharField(max_length=5, choices=(('male', '男'),('female', '女')), default='female') address = models.CharField(verbose_name='地址', max_length=100, blank=True, null=True) city = models.CharField(verbose_name='城市', max_length=20, default='Windsor') province = models.CharField(max_length=20, verbose_name='省', default='ON') zip_code = models.CharField(max_length=6, verbose_name='post code',blank=True, null=True ) mobile = models.CharField(max_length=10, null=True, blank=True) enter_date = models.DateField(verbose_name='入学时间', blank=True, null=True) class Meta: verbose_name = 'StudentInfo' verbose_name_plural = verbose_name def __str__(self): return self.username I deleted all my table except auth_user before, and I encountered this problem. Anyone help? -
how to display angular ng-model value inside django template
I have an input field with angular data binding and I would like to see the value I enter in the input field right next to it. This works when trying out on just plain angular environment but doesnt work when rendering django template. <div ng-app="myApp" ng-controller="myCtrl"> <input ng-model="nname"> {{nname}} </div> I tried verbatim but it did not work. {% verbatim %} <div ng-app="myApp" ng-controller="myCtrl"> <input ng-model="nname"> {{nname}} </div> {% endverbatim %} Is it not common to use this angular functionality inside Django? Thanks -
update model based on global variable value django middleware
is_paid_member=False #Global variable Function: global is_paid_member if is_paid_member == True: with transaction.atomic(): client = ClientProfile.objects.get(user=request.user) client.subscription = "Member" client.save(update_fields=['subscription']) I want to update the model based on the value of global variable.This function has to update the model if payment is made.Where do i put this function in order to update the model field? Im changing is_paid_member to True in the transaction success function @csrf_exempt def payment_success_member(request): data = {} global is_paid_member is_paid_member=True user=request.user return render(request, 'payu_success.html',data) -
How to get some specific real-time data from several websites continuously using Python (Django)?
I am working on a web application that needs to pull data from other websites continuously. For example, the price of a product. If the price changes on the original website, my site's price will also be changed automatically. Is it possible to scrape/pull/get data from other websites continuously like this? -
Django Rest Framework: allow a serializer field to be created, but not edited
Right now, DRF's read_only argument on a Serializer constructor means you can neither create nor update the field, while the write_only argument on a Serializer constructor allows the field to be created OR updated, but prevents the field from being output when serializing the representation. Is there any (elegant) way to have a Serializer field that can be created, exactly once, when the model in question is created (when the create() is called on the Serializer), but that cannot later be modified via update? NB: Yes, I've seen this solution, but honestly I find it ugly and un-Pythonic. Is there a better way -
Importing static files across apps in Django
Im trying to put most my python logic for my Django webapp in a static directory that I can access across different apps. I'm either not understanding or not finding exactly what I'm looking for online. I need to be able to import classes from these files in the views.py of different apps. Is there an example someone could share? -
When I test my POST route for Django Rest Framework API it returns a 401 not authenticated even though logged in
When I attempt to test my Create/POST route for my Django Rest Framework API I receive a response status code of 401 with the error detail telling me ErrorDetail(string=u'Authentication credentials were not provided.', code=u'not_authenticated'). The weird thing is I Django tells me I'm authenticated when I check is is_authenticated. Does anyone have an idea what might be causing this? All relevant code provided below. # test_api.py def test_create_project(self): ''' When given valid parameters a project is created. ''' user = User.objects.get(username="user_001") self.authorise_user_and_test_is_authenticated(user.id) # pass of authenication and auth testing to method, when tested with is_authenicated() it returns true. response = self.client.post('/api/user/{0}/project/create/'.format(user.id), json.dumps({"model_name": "POSTed Project", "description": "Project tested by posting", "shared_users[]": [2] }), content_type='application/json') self.assertEqual(response.status_code, 201) # views.py class MyCreateView(generics.GenericAPIView): pass serializer_class = FerronPageCreateAndUpdateSerializer def get_queryset(self): return User.objects.filter(pk=self.kwargs.get('user')) def post(self, request, format=None, **kwargs): # This dictionary is used to ensure that the last_modified_by field is always updated on post to be the current user print request.data request_data = { 'user': request.user.id, 'model_name': request.data['model_name'], 'description': request.data['description'], 'last_modified_by': request.user.id, 'shared_users': request.data.getlist('shared_users[]', []) } serializer = FerronPageCreateAndUpdateSerializer(data=request_data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # settings.py REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated …