Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker contain receiving unsolicited HTTP POST Requests
When i start my django app in a docker container. I get the following Error/Warning every 5 or 10 seconds. (the app is using gunicorn HTTP server) Invalid HTTP_HOST header: '10.255.255.12:8082'. You may need to add u'10.255.255.12' to ALLOWED_HOSTS. My question is not how to fix the error, but what is making the requests? I realise that this may be as a result of some line of code in my app, and i haven't shared any of my code. I am asking if anyone is aware of anything with django/gunicorn/docker which would be sending requests, perhaps some sort of tool which makes requests periodically as a status test? -
Django dynamic models.FileField Storage
I have a model like this: class Person(models.Model): name = models.Charfield(max_length¶=30) photo = models.FileField(upload_to='uploads/') Is there any way to dynamically change the Storage class of photo field based on the value of the name field? for example, I want to store the photo of the persons with the name xxx to FileSystemStorage¶ and for the others I want to use S3Storage -
Django REST Framework update record using mixin
I'm using Django 2.x and Django REST Framework. I have a UserSetting model to save user's setting class UserSetting(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.PROTECT) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) and UserSettingSerializer class UserSettingSerializer(serializers.ModelSerializer): class Meta: model = UserSetting depth = 1 fields = ( 'id', 'country', 'created', 'modified' ) The setting record is created while a new user is registered using allauth signal. I want a REST viewset to allow only get and update to the settings record. For that I have defined the viewset like class UserSettingViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): serializer_class = UserSettingSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission) def get_queryset(self): queryset = UserSetting.objects.filter( user=self.request.user ) return queryset def update(self, request, *args, **kwargs): print(kwargs) print(request) return super(UserSettingViewSet, self).update(request, *args, **kwargs) I'm able to get the settings as an array while using GET request to list view and detail using id in the URL parameter. But when I use PUT method to update the record, it returns the detail view data and no validation is raised even if there is no data found in the request. How to properly hand the update()? Also, What is the best approach to get user's settings as … -
Django Post request not sent on button click
I am trying to create a simple web app in Django and trying to use Ajax so the page will not refresh. The only goal of this app is to have a form that takes some user input and does not refresh when the form is submitted. However, for some reason this does not happen when I click the button. Here is the Index page: <!DOCTYPE html> <html> <body> <h2>Create product here</h2> <div> <form id="new_user_form"> <div> <label for="name" > Name:<br></label> <input type="text" id="name"/> </div> <br/> <div> <label for="email"> email:<br></label> <input type="text" id="email"/> </div> <div> <label for="password" > password:<br></label> <input type="text" id="password"/> </div> <div> <input type="submit" value="submitme"/> </div> </form> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type = "text/text/javascript"> $(document).on('submitme', '#new_user_form', function(e)){ e.preventDefault() $.ajax({ type: 'POST', url:'/user/create', data:{ name:$('#name').val(), email:$('#email').val(), password:$('#password').val(), } success.function(){ alert('created') } }) } </script> </html> Here is my main urls.py file: from django.contrib import admin from django.urls import path from django.conf.urls import include, url from testapp import views import testapp from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', testapp.views.index), url(r'^user/create/$', csrf_exempt(testapp.views.create_user)) ] My views.py file: from django.shortcuts import render from testapp.models import User from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'index.html') def … -
Django Rest: Hashing used in set_password() function of BaseUserManager
Can I know the hashing algorithm used in set_password() of BaseUserManager Early on, I assumed that it must be creating a same output(encrypted password) like make_password(). But both gives different outputs For example, pbkdf2_sha256$120000$fpYd7FD1Cf3Z$sHRDYkxU6wST9i17AeVZeDPMGjwSpV4U1+8bxTC7B9U= this is hashed using set_password() method in my app(which is the encrypted form of the password, 'password' then in the python shell, >>>from django.contrib.auth.hashers import make_password >>>make_password('password') gives an output 'pbkdf2_sha256$120000$PCjS8f7J2zU8$7pj4Xp5R1h935z9U3UyRlcprJpQRgUID+I9UQp+q1w4=' and I run the make_password('password') command once again,interestingly, this time also it gave a different output 'pbkdf2_sha256$120000$Jyhjh4luFw4F$wMKnv4BuNVw0NFpKgQjJNoyC6CuMqeXCo1neTEQ6S58=' So, what I want is I want to add a change password feature in my app., So I want my user to type his current password before changing it. As it is hashed using set_password(), I cannot check it directly., and I think the only possible way is to hash the inputed password and then check it with the original one. Can anybody help me in solving it? -
Adding manually an entry to the Django queryset
This is my model (the relevant part): class Country(models.Model): name = models.CharField(max_length=500, choices=COUNTRY_NAME_CHOICE) country_id = models.CharField(max_length=500,choices=COUNTRY_ID_CHOICE,primary_key=True,unique=True) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=500,choices=CITY_NAME_CHOICE) country = models.ForeignKey('Country',on_delete=models.CASCADE) zip= models.CharField(max_length=500, choices=ZIP_CHOICE, primary_key=True,unique=True) def __str__(self): return self.name class Cost(models.Model): date = models.ForeignKey('Date' ,on_delete=models.CASCADE) city= models.ForeignKey('City' ,on_delete=models.CASCADE) value = models.FloatField(validators=[MinValueValidator(0)]) entry_time = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.city.name + ' ' +str(self.value) For model Cost, I have a Django form CostForm that I am listing out on a template, so that users can insert new costs. class CostForm(ModelForm): class Meta: model = Cost exclude = ['user','entry_time'] #Makes only FR, NO, and RU cities available def __init__(self, *args, **kwargs): super(CostForm, self).__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.filter(country__name__in=['France','Norway','Russia']) On the template city field is shown as a dropdown. I have already managed to limit this field to the values I want in the form above (user can input costs only for Russia, Norway and France, because their cities are the only options they see in the dropdown). Here is my problem: I need to make another option available for the users in the city dropdown. A city that doesn't exist for real in the database. Lets call it "X". When user chooses city … -
Chat with the staff django channels
I am developing a chat in which users of the platform will be able to chat with the staff members. Only if they are connected, otherwise, the chat will be disabled. There may be one or more staff members. I do not finish to understand how to count the connected staff, right now I have a variable instance (total_staff) of the consumer where I increase or decrease, but it does not work well. This is my code: from channels.generic.websocket import AsyncJsonWebsocketConsumer from .exceptions import ClientError class ChatConsumer(AsyncJsonWebsocketConsumer): """ Chat consumer """ rooms = set() total_staff = 0 async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ # Accept the connection await self.accept() async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass it as the first argument. """ # Messages will have a "command" key we can switch on command = content.get("command", None) try: # User normal join to platform if command == "join": # Make them join the room await self.join_room(content["room"]) elif command == "staff_connect": # Staff online await self.staff_connect() elif command == "staff_diconnect": # Staff disconnect await self.staff_diconnect() elif command … -
Django views with nested serializers
I have the following model structure: class Parent(models.Model): name = models.CharField(max_length=100) class Child1(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey(Parent) class Child2(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey(Parent) With the serializers: class Child1Serializer(serializers.ModelSerializer): class Meta: model = Child1 fields = ( "name", ) class Child2Serializer(serializers.ModelSerializer): class Meta: model = Child2 fields = ( "name", ) class ParentSerializer(serializers.ModelSerializer): child1_ctx = Child1Serializer(many=False, required=False) child2_ctx = Child2Serializer(many=False, required=False) class Meta: model = Parent fields = ( "name", "child1_ctx", "child2_ctx" ) read_only_fields = ("name") The ViewSet: class ParentViewSet(GenericViewSet, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin): serializer_class = ParentSerializer queryset = SocialMediaContextContainer.objects.all() However, when calling the ParentViewSet I only receive the fields for that model and not a combination of all its related submodels!? Return value: { "name": "test" } -
TypeError: __init__() missing 1 required positional argument: 'app_module'
Im trying to run tests on my site and i get this error message. Was wondering if anyone else has experience with this.Also I'm new to the Django framework. TypeError: init() missing 1 required positional argument: 'app_module' -
Disabling a database for testing when multiple databases configured
I have two databases configured in my app: DATABASES = { 'default': { ... } 'legacy': { ... } } The legacy database is only used in a particular part of the app (I've added it as a second database for convenience). This works fine, except that when I try to run tests, Django tried to create a test database for the legacy database, causing an error: Got an error creating the test database: (1044, "Access denied for user ... to to database 'test_...'") How can I tell Django not to create a test database for the second legacy database? I thought setting the following would work: DATABASES['legacy']['TEST'] = { 'NAME': None, 'CREATE_DB': False } but that doesn't seem to help -
Counting instances of item in django template - table numbering
Is it possible to write a template tag that auto increments its' item number? I have a series of manually generated HTML tables and I would like to be able to put a tag such as {%table_number%} below it and have it output like "Table 1", "Table 2" etc. Can I pass a variable around somehow? -
DJANGO POSTGRESQL FATAL: DATABASE DOES NOT EXIST (But actually, it does exists)[HOW TO SOLVE IT]
everyone. I'm trying to config postgresql on my Django Project, I've followed a tutorial on this website but I'm getting an Error when I try to make migrations. FATAL: database "laudosOnline" does not exist, as it follows: (venv) saudebelem@saudebelem-development:~/projeto/laudosOnline$ python3 manage.py makemigrations /home/saudebelem/projeto/venv/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "/home/saudebelem/projeto/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/saudebelem/projeto/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/saudebelem/projeto/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/saudebelem/projeto/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: database "laudosOnline" does not exist This is my database config on settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', 'laudosOnline'), 'USER': os.environ.get('DB_USER', 'edson'), 'PASSWORD': os.environ.get('DB_PASS', 'mypassword'), 'HOST': 'localhost', 'PORT': '5432', } } Now, the awkward part: I was sure I've created the laudosOnline database, so I went to psql and tried to create this database again and for my surprise, I've got the message: ERROR: database "laudosonline" already exists, as it follows: postgres=# CREATE DATABASE laudosOnline WITH OWNER edson; ERROR: database "laudosonline" already … -
How to create users, database in mysqlclient python
I am new to django. I want to connect mysql database with django. I have installed mysqlclient. Now, I have to set parameters like database name, username, password in my projects settings.py. However, I dont know how to create these parameters. There is no way to access the mysqlclient command line. Any help would be appreciated. Thanks. -
Authenticating Registrationn form in django
I have this html form that I want to use for signup of customers. <form id='registration-form'> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname" ><br> <input type="text" class="form-control input-upper" id="username" placeholder="Username" name="username"><br> <input type="email" class="form-control input-upper" id="email" placeholder="Email" name="email"><br> <input type="text" class="form-control input-upper" id="organization" placeholder="Organization" name="organization"><br> <input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password"><br> <input type="password" class="form-control input-upper" id="password" placeholder="Confirm Password" name="password"><br> <small>By registering you agree to our <a href="{% url 'tos' %}">terms and conditions</a></small> <button type="button" class="btn btn-primary btn-block btn-signup-form">SIGN UP</button> <button type="button" class="btn btn-primary btn-block btn-sign-linkedin" href="{% url 'social:begin' 'linkedin-oauth2' %}?next={{ next }}">Sign up with LinkedIn</button> <p class="text-already">Already have an account? <a href="">LOGIN</a></p> </div> </form> How do I make an validation of the data filled i.e the email and password and I want customers to be able to log in after signing up -
Python social auth app django 'social' is not a registered namespace
I'm working on a project with Python(3.6) and Django(2.0) in which I'm trying to integrate social login by using social-auth-app-django package. Managing users in the users app. Here's my configurations: From settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'phone_field', '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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ] LOGIN_URL = 'users/login/' AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'social_core.backends.linkedin.LinkedinOAuth2', # for Github authentication 'social_core.backends.facebook.FacebookOAuth2', # for Facebook authentication 'django.contrib.auth.backends.ModelBackend', ) From users/urls.py: app_name = 'users' urlpatterns = [ path('signup/', views.SignUpView.as_view(), name='signup'), path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), url(r'^auth/', include('social_django.urls', namespace='social')), ] SOCIAL_AUTH_URL_NAMESPACE = "users:social" From login.html: <div class="col-lg-12 center-aligned"> <div style="margin: auto"> <div class="or-seperator"><b>or</b></div> <div class="social-btn text-center"> <a href="{% url 'social:begin' 'facebook-oauth2' %}" class="btn btn-primary btn-lg" title="Facebook"><i class="fa fa-facebook"></i></a> <a href="{% url 'social_django.urls.url' %}" class="btn btn-info btn-lg" title="LinkedIn"><i class="fa fa-linkedin"></i></a> <a href="{% url 'social:begin' 'google-oauth2' %}" class="btn btn-danger btn-lg" title="Google"><i class="fa fa-google"></i></a> </div> </div> </div> When I load the … -
why does django celery task is showing a "attribute error"?
when i ran the below code the django is throwing an wrapper error the error code is shown below Error Message: AttributeError: 'method-wrapper' object has no attribute 'module' Models.py class PatientMasters(models.Model): patient_id = models.AutoField(primary_key=True) patient_n_key = models.CharField(max_length=15, blank=True, unique=True) centre_master_short_name = models.CharField(blank=False, max_length=33) centre_master_id = models.CharField(blank=False, max_length=15) pid_no = models.CharField(max_length=45, blank=True, null=True) aadhar_number = models.CharField(max_length=45, blank=True, null=True) date_of_registration = models.BigIntegerField() patient_name = models.CharField(max_length=45,blank=False) gender = models.CharField(max_length=45,blank=False) patient_category = models.CharField(max_length=45, blank=True, null=True) age = models.IntegerField(blank=False) class Meta: managed = False db_table = 'patient_masters' @receiver(post_save, sender=PatientMasters) def generate_pat_unique_key(sender, instance, created, **kwargs): """ Generate unique n_key as an combination of primary key and centre_master_id """ post_save.disconnect(generate_pat_unique_key, sender=PatientMasters) instance.patient_n_key = "{}-pat-{}".format(instance.centre_master_short_name, instance.patient_id) instance.save() post_save.connect(generate_pat_unique_key, sender=PatientMasters) Views.py class PatientMastersviewset(viewsets.ModelViewSet): queryset=models.PatientMasters.objects.all() serializer_class=serializers1.PatientMastersserializer lookup_field = 'patient_n_key' tasks.PatientMastersviewset.delay() tasks.py @app.task class PatientMastersviewset(viewsets.ModelViewSet): queryset=models.PatientMasters.objects.all() serializer_class=serializers1.PatientMastersserializer lookup_field = 'patient_n_key' -
Array of Dates in Django models
I want to create a table in database which will store the holidays of three months that are August, September and October. I am planning to create this array because different months will have different list of holidays which we cant store in postgres database. This table "Holidays" will have only one row with array in each column for August, September and October. Later when I have to check a date from psql query, I can check the arrays in this table for a particular month to find whether it is a holiday or not. So I have two questions. First how can we define this model in Django models.py file. Actually I am creating a populating script which fills the data in the tables created by Django models. And second, is there a better way of doing this ? -
Can I add colorpicker in django-models
Hello is it possible to add a color picker in a django model? I need to have a color in my model so it can be passed to the front-end in Hex Color Code I can do that with saving the hex color In char field, but is it possible to have an actual color-picker in Django admin -
How to incorporate python programs on django
I have a created a python program that is used for web scraping. And i want to incorporate it into a web application. How can i incorporate it using Django? Thank you in advance guys, hoping for your feedback and ideas. -
Saving images on files or on database when using docker
I'm using docker for a project, the main focus for its usage is to make the application available even if one of the node (it's a 6 nodes cluster with docker swarm) is down. The application is basically a Django App that can save some images from users and others models. I'm currently saving the images as files, but since I need to specify a volume locally for a single machine, I would like to know if it would be better to save the images on database cluster, so it would be available even if the whole node goes down. Or is there another way? -
Hierarchical multi-tenant architecture with Django and Postgresql using separate schemas
I have a django app has clients and multiple users that are linked to those clients, and I want to migrate the system to hierarchical multi-tenant architecture. Hierarchical Part Clients can include other clients recursively. For instance, Client A includes Client B and Client C. If a user Client A logs in the system, user will see Client B and Client C's data. If a user of Client B logs in the system, user will see only Client B's data. Multi-Tenant Part I want to store all clients' data in separate schemas. But there is some data that is not relevant to clients, so I want to store that data in public schema. When I research Building Multi Tenant Applications with Django, I saw this part: def set_tenant_schema_for_request(request): schema = tenant_schema_from_request(request) with connection.cursor() as cursor: cursor.execute(f"SET search_path to {schema}") However, to apply my hierarchical example that I've mentioned above, I must reach multiple schemas at the same time. Can I do that or are there any other ways to implement my architecture? -
Create a progress bar showing copying files progress with the help of Celery in Django framework
Generally speaking, I need to creat a html page with progress bar showing the file copying progress after the user pressed the "DO" button. Below are what I have done and tried: Following is the "progress bar" element in theml: Copying progress: <progress id = "progressCopy" value="0" max="100"> </progress> Below, in the Celery task named "copying", I update the task status with the variable "progressPercentage" in JSON format. self.update_state(state = 'PROGRESS', meta = {'percentage':progressPercentage}) So the question is, how should I code in HTML to let the Progress bar element updated with the return JSON data (showing above) from function without refreshing the page. The key here is: how to return the JSON data from called function to Javascript. I tried something like this below: return HttpResponse(Celery.AsyncResult(copying.request.id)) But seems it is not correct. -
Test save_related of an AdminModel using RequestFactory
I have overridden the save_related() of an AdminModel and I am trying to test it using RequestFactory(). I am trying to test the messages being displayed, which I managed to do using the test Client(), however, it seems too much, when I simply need a post request. factory = RequestFactory() obj = mommy.prepare('MyModel') data = model_to_dict(obj) request = factory.post(reverse('admin:myapp_mymodel_add'), data) request.user = user setattr(request, 'session', 'session') storage = FallbackStorage(request) setattr(request, '_messages', storage) AdminSite().index(request) And even tho [message.message for message in messages.get_messages(request)] should display the messages, it does not. From the documentation, I understood that I should pass the request to a view and I assume, passing the request to ìndex() of the AdminSite is the part, which is failing. -
How to check if ManyToMany field is not empty?
How do I check if there are any ManyToMany field objects related to my model object? For example, I have a model: class Category(models.Model): related_categories = models.ManyToManyField('self', blank=True) I want to do something only if there are related objects existing: if example_category.related_categories: do_something() I tried to do example_category.related_categories, example_category.related_categories.all(), example_category.related_categories.all().exists(), example_category.related_categories.count(), but none of these works for me. I have no any additional conditions to filter by. Is there any easy way to check emptiness of this field? -
Django Views: When is request.data a dict vs a QueryDict?
I have run into some trouble with the issue, that request.data sometimes is a dict (especially when testing) and sometimes a QueryDict instance (when using curl). This is especially a problem because apparently there is a big difference when calling a view using curl like so: curl -X POST --data "some_float=1.23456789012123123" "http://localhost:8000/myview" Or using the django_webtest client like so: class APIViewTest(WebTest): def test_testsomething(self): self.app.post(url=url, params=json.dumps({some_float=1.26356756467})) And then casting that QueryDict to a dict like so new_dict = dict(**request.data) my_float = float(new_dict['some_float']) Everything works fine in the tests, as there request.data is a dict, but in production the view crashes because new_dict['some_float'] is actually a list with one element, and not as expected a float. So while I am wondering why QueryDict behaves in this way, I would rather know why and when response.data is a QueryDict in the first place. And how I can use django tests to simulate this behavior. Having different conditions for production and testing systems is always troublesome and sometimes unavoidable, but in this case I feel like it could be fixed. Or is this a specific issue related to django_webtest?