Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python send database modification from local system to online mysql cloud server
The application runs on 3 different local machines where the db is installed i need to send the data to the cloud server when ever there is internet connectivity how can i do that. I have defined the primarykey such way it will be not repeated in any of the instance. -
Is there any way to change view of Django-rest-auth of register?
I've created rest APIs using Django-rest-auth, in registration, it's returning { "detail": "Verification e-mail sent." } , But I need to add some status like success and message like email sent etc. Is there any way to override view of django-rest-auth for registration? class MyRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() def get_cleaned_data(self): super(MyRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.address = self.cleaned_data.get('address') user.user_type = self.cleaned_data.get('user_type') user.save() return user -
Django Rest Framework how to create Serializer from multiple models
I needed to extend User model to add things like address, score, more user_types, etc. There are 2 possible ways to achieve that, extend the User model or create a new model that will be connected with the target User with OneToOneField. I decided to go with a new model because It seemed easier. But now I cannot create Serializer without nested profile field which is moreover undocumented because default rest_framwork documentation generator cannot generate documentation for nested serializers. My UserSerializer looks like this: class UserSerializer(serializers.ModelSerializer): # This creates a nested profile field profile = ProfileSerializer(required=True) def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create_user(**validate_data) profile, created = Profile.objects.upodate_or_creeate(user=user, defaults=profile_data) return user class Meta: model = User fields = ('id', 'username', 'email', 'password', 'buckelists', 'profile') read_only_fields = ('id',) extra_kwargs = {'password':{'write_only': True}} This Serializer takes following JSON format: { 'name': ..., 'email': ..., 'password': ..., 'profile': { 'address': ..., 'score': ..., 'user_type': ..., 'achievements': ..., 'country': ..., 'trusted': ..., } This looks weird and documentation generated with rest_framework.documentation.include_docs_urls shows just following: { 'username': ..., 'email': ..., 'password': ..., 'field': ..., } So it's not clear what should be included in the profile field. I'd like to create Serializer that would … -
How to populate a from another model's values in django?
I'm working on employee management system, where an employee requests for a leave. So, once the leave has been approved in his leaves-history table has to be updated automatically. views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import LeaveRequestForm from django.shortcuts import render_to_response from .models import Leave, History def leaveRequest(request): if request.method == "POST": form = LeaveRequestForm(request.POST) if form.is_valid(): leave = form.save(commit = False) leave.user = request.user form.save() return HttpResponseRedirect("/thanks/") else: return auto_fill_form(request) forms.py from lrequests.models import Leave class LeaveRequestForm(ModelForm): class Meta: fields = ("name", "employee_ID" , "type_of_leave", "from_date", "to_date") model = Leave In my models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave')) STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),) class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) type_of_leave = models.CharField(max_length = 15, choices = CHOICES) from_date = models.DateField() to_date = models.DateField() status = models.CharField(max_length = 15, choices = STATUS_CHOICES) def __str__(self): return self.name @property def date_diff(self): return (self.to_date - self.from_date).days class History(models.Model): emp_ID = models.CharField(('employee ID'),max_length = 25) full_name = models.CharField(('Name'),max_length = 40) el = models.IntegerField(('Earned Leave')) cl = models.IntegerField(('Casual Leave')) sl = … -
Django signal handling (and recording) for CRUD events on specific models
I am using django 2.0.8 and Python 3.5. I am trying to create a points awarding system based on two classes Foo and Foobar. I want to do two things: Set up a points table which maps an (object specific) CRUD event to a point value Write signal handlers for when the CRUD signals are fired for classes deriving from Foo and FooBar. This is what I have so far: myapp/models.py from django.db import models from django.contrib.contenttypes.models import ContentType class Foo(models.Model): name = models.CharField(max_length=16) class Meta: abstract = True class FooBar(models.Model): name = models.CharField(max_length=16) class Meta: abstract = True class Activity(models.Model): ACTIVITY_TYPE_CREATE = 6 ACTIVITY_TYPE_MODIFY = 7 ACTIVITY_TYPE_DELETE = 8 ACTIVITY_TYPES = ( (ACTIVITY_TYPE_CREATE, 'Create'), (ACTIVITY_TYPE_MODIFY, 'Modify'), (ACTIVITY_TYPE_DELETE, 'Delete'), ) # Generic relation fields content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) activity_type = models.PositiveSmallIntegerField(choices=ACTIVITY_TYPES) points_value = models.SmallIntegerField(null=False,blank=False,default=0) class FoodooChile(Foo): pass class FooBarChile(FooBar): pass myapp/signals.py # Not at all sure that this is correct ... @receiver(post_save, sender='myapp.FoodooChile', dispatch_uid='fooch_save') def fooch_save(sender, instance=None, created=None, update_fields=None, **kwargs): pass myapp/app.py class MyappConfig(AppConfig): name = 'myapp' label = 'myapp' def ready(self): import myapp.signals My questions are: How do I modify myapp/models.py and myapp/signals.py in order to listen to and handle CRUD events relating to FoodooChile and FooBarChile? (Assuming the … -
Views not registered in django rest urls
Why my views is not registered in url? here's my view code, class AView(APIView): def get(self, request, format=None): return Response(apps.get_models()) here's my url code from a_module import views from .views import * from rest_framework_nested import routers app_name = 'a_module' router = routers.DefaultRouter() router.register(r'endpoint', views.AView, base_name="endpoint") urlpatterns = [ url(r'^', include(router.urls)), ] There's other view in a_module that registered in url, but the only view that is not registered is AView, i tried registering with views.AView.as_view() it doesn't work too. It when I access the view through /endpoint it returns not found. -
Dummy API for a Django Test
I have a booking app that can deal with both local and remote API bookings. Our logic —for (eg) pricing and availability— follows two very different pathways. We obviously need to test both. But running regular tests against a remote API is slow. The test environment provided manages a response in 2-17 seconds. It's not feasible to use this in my pre_commit tests. Even if they sped that up, it's never going to be fast and will always require a connection to pass. But I still need to test our internal logic for API bookings. Is there some way that within a test runner, I can spin up a little webserver (quite separate to the Django website) that serves a reference copy of their API. I can then plug that into the models we're dealing with and query against that locally, at speed. What's the best way to handle this? Again, I need to stress that this reference API should not be part of the actual website. Unless there's a way of adding views that only apply at test-time. I'm looking for clean solutions. The API calls are pretty simple. I'm not looking for verification or anything like that here, … -
Django - Bootstrap4 - DateRangePicker - django-bootstrap-datepicker-plus
Firstly, i am not an ultra expert about Django objects or structures, i learn with numerous and various curses and i try during the development of my website to reach the must clear and efficient code in my Django project. Now i try to make a date range picker in bootstrap 4 (4.1.3) I will obtain the same result as this tool django-bootstrap-datepicker-plus, i trying to follow the example code but i dont know how to add this tool on my django project. For now i cant successfully render the daterangepicker on the template. I share the files that concerns by this tool. models.py class Event(models.Model): name = models.CharField(max_length=200) start_date = models.DateField() end_date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() start_datetime = models.DateTimeField() end_datetime = models.DateTimeField() start_month = models.DateField() end_month = models.DateField() start_year = models.DateField() end_year = models.DateField() def __str__(self): return self.name forms.py from bootstrap_datepicker_plus import DatePickerInput from bootstrap_datepicker_plus import TimePickerInput from bootstrap_datepicker_plus import DateTimePickerInput from bootstrap_datepicker_plus import MonthPickerInput from bootstrap_datepicker_plus import YearPickerInput class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'start_date', 'end_date', 'start_time', 'end_time', 'start_datetime', 'end_datetime', 'start_month', 'end_month', 'start_year', 'end_year', ] widgets = { 'start_date': DatePickerInput(options={'format': 'YYYY-MM-DD', 'debug': True}).start_of('event active days'), 'end_date': DatePickerInput(options={'format': 'MM/DD/YYYY'}).end_of('event active days'), … -
Django messages - check if message doesnt already exist before adding
Is it possible to check if an django message and contents exist before adding another message? in my example I am peforming a try except in a loop, and if an exception occurs I add a message, but I only want the message to appear once, not for each item in the loop for i in data: # do something... try: # try to act upon something except: # failed action add a message if not messages.?.contains("Error: Unable to perform action X") messages.add_message(request, messages.ERROR, 'Error: Unable to perform action X') pass -
Python Django Model Signals Post_Save Querry Object Does not Contain Saved Object
My intention is to send a notification once the properties field is updated. I also need to include details of the property updated in the notification sent. The signal is triggered and the notification is sent but I can't get the property being updated from the host instance. I instead end up getting what was saved just before the signal was triggered. Anybody who knows how I can get the host - property instance being updated when the signal is triggered? Please help from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField from django_model_changes import ChangesMixin from django.conf import settings from django.dispatch import receiver from django.db.models.signals import post_save from ..services.notification import NotificationService class Host(ChangesMixin, models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='host', unique=True) properties = models.ManyToManyField('Property', related_name='hosts', blank=True) one_field = models.DateTimeField(null=True, blank=True) another_field = models.OneToOneField('Location') def to_dict(self): if self.phone == None: number = None else: number = self.phone.national_number return { 'one_field': self.one_field, 'another_field': self.properties.count() - self.limit, } def __unicode__(self): return 'Host {} {} {} <{}>'.format(self.user.first_name, self.user.last_name, self.phone, self.user.email) class Meta: db_table = 'host' verbose_name = 'Host' verbose_name_plural = 'Hosts' @receiver(post_save, sender=Host) def send_email_if_change_detected_in_properties(sender, instance, **kwargs): if instance.properties: host = instance property = host.properties.last() # This refuses to take the host.property instance that has just … -
Queryset search with icontains does not work correctly
I have the following code class UserDetails(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='detail') details = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class User(models.Model): name = models.CharField(max_length=100) desc = models.CharField(max_length=200) ... search = 'John Doe' User.objects.filter( Q(name__icontains=search) | Q(desc__icontains=search) | Q(detail__details__icontains=search) | Q(detail__first_name__icontains=search) | Q(detail__last_name__icontains=search) ) If I search for "John" it returns 1 result. If I search for "Doe" it returns 1 result. But if I search for "John Doe" it returns 0 result. I've also checked the query (LIKE UPPER('%John Doe%')) but I don't see any reason why this is not working. -
Removing an obsolete function that's used in an old migration
I have an old Django project which has been poorly maintained with a lot of functionality which is not needed anymore. There is a function called create_account which is no longer needed, but it's used in an old migration file. Since it's bad practice to modify or remove old migration files, I wonder what would happen if I were to remove the use of that function and then remove the function itself. Could it cause problems in production or when a new developer joins the project and runs migrate to initialize their database? -
How to get last object in each hour over last 7 days in Django using DatetimeField column
I have been doing a task of filtering values from a table called 'Feeds', The row gets inserted every 10 mins into system. ie. 6 rows every hour I am storing its datetime in a column called timestamp. I want to filter last row of each such hour of past 7 days. Here is my code. class Feeds(models.Model): value = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) Please Help to solve this. Thank you. -
Django Rest Framework Nested View in Viewset
class GameInviteViewSet(): queryset = Game.objects.all() serializer_class = GameSerializer @action( methods=['get'], detail=True, ) def invite(self, request, **id): # Invite user here with endpoint /api/games/{id}/invite/{user} How would I make the above endpoint? I can make /api/games/{id}/invite/, but how can I add another argument after that. Or, according to the documentation, by default it goes {prefix}/{lookup}/{url_path}/ I want {prefix}/{lookup}/{url_path}/{prefix2}/{lookup2}/{url_path2}/ or {prefix}/{lookup}/{url_path}/{lookup2}/{url_path2}/ So that I could do things like games/{id}/{invite}/{user}/ games/{id}/{kick}/{user}/ games/{id}/{players}/{user}/gamestats/ To register my routers, I do the following: games/urls.py: router = routers.DefaultRouter() router.register(r'^api/games', GameViewSet, 'games') api/urls.py: from games.urls import router as games router = routers.SimpleRouter() urlpatterns += games.urls -
Combining multiple templates in one template
I was building a website where index.html used to have all the html codes of index page like head,body etc.but my client wants individual templates like one for header,another for body,another one for footer etc. so how can i achieve this? -
Django Image Upload, No data in request.FILES['']
I have been simply trying to upload profile image, which i have done before. But this time the file is not uploading, even though the code is same. The image name is accessible from request.data('image'), but the image itself is not from request.FILES['image'] I have tried serializer, forms and direct way as well but still no progress. Here is the code models.py class Profile(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_images', null=True) def __str__(self): return self.user.name HTML code <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit" name="upload-profile-photo">Upload</button> </form> Views.py if 'upload-profile-photo' in request.POST: profile_instance = Profile.objects.get(user=token.user.id) profile_instance.image = request.FILES["myfile"] profile_instance.save() return HttpResponse("Success") Request Information GET: No Get Data POST: csrfmiddlewaretoken: ..... myfile: 'maxresdefault.jpg' upload-profile-photo: '' FILES: No FILES data I usually get MultiValueDictKeyError or KeyError -
Search through queryset with one to one field
I have two models UserDetails and User. I have a simple search that checks if the string is in one of the fields. My problem is that I don't know how to access the one-to-one field in the queryset below to search through this as well. class UserDetails(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='detail') details = models.CharField(max_length=100) class User(models.Model): name = models.CharField(max_length=100) desc = models.CharField(max_length=200) ... search = 'John Doe' User.objects.filter( Q(name__icontains=search) | Q(desc__icontains=search) | Q(__detail_details=search) . # how to do this? ) -
django serializer dynamically set attributes
Is it possible to dynamically set the attributes for a Serializer dynamically? CONTEXT_CLASSES = dict() contexts = ['EmailContext', 'SmsMessageContext',...] for ctx in contexts: Ctx_class = getattr(sys.modules[__name__], f'{ctx}Serializer') ctx_class_instance = Ctx_class(many=False, required=False, read_only=True) attr_name = ctx.split('Context')[0].lower() + '_ctx' CONTEXT_CLASSES[attr_name] = ctx_class_instance class ContextContainerSerializer(serializers.ModelSerializer): for attr_name, instance in CONTEXT_CLASSES.items(): # set attributes somehow -
Django model fields indentation
How can I play with the indentation of the django model fields, e.g. adding a right indent for a specific field? Thanks ahead, Shahar -
Get part of django model depending on a variable
My code PriceListItem.objects.get(id=tarif_id).price_eur In my settings.py CURRENCY='eur' My Question: I would like to pick the different info depending on the CURRENCY variable in settings.py Example: PriceListItem.objects.get(id=tarif_id).price_+settings.CURRENCY Is it possible? -
How to get Total Children in a Parent Serializer
I want to display the total number of Workers associated with a Ticket Counter in a parent (Ticket counter) serializer. Below are the two Serializers: class TicketCounterSerializer(serializers.ModelSerializer): workers = WorkerToCounterSerializer(many=True, read_only=True) class Meta: model = TicketCounter fields = ( 'ticket_counter_name', 'ticket_counter_description', 'ticket_counter_address', 'workers', ) class WorkerToCounterSerializer(serializers.ModelSerializer): class Meta: model = WorkerToTicketCounter fields = ( 'user', 'ticket_counter', 'worker', ) MODELS: class TicketCounter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ticket_counter_name = models.CharField(max_length=100, default="") ticket_counter_description = models.CharField(max_length=1500, default="") ticket_counter_address = models.CharField(max_length=1500, default="") class WorkerToTicketCounter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ticket_counter = models.ForeignKey(TicketCounter,related_name="workers") worker = models.ForeignKey(User,related_name='worker_for_ticket_counter') Here is how I am getting result: { "ticket_counter_name": "First", "ticket_counter_description": "firsty", "ticket_counter_address": "222fdssssss", "workers": [ { "user": 1, "ticket_counter": 3, "worker": 4, }, { "user": 1, "ticket_counter": 3, "worker": 5, }, ] } Here is how I want { "ticket_counter_name": "First", "ticket_counter_description": "firsty", "ticket_counter_address": "222fdssssss", "workers": 2 # just the total count } How to just display the total count? -
Getting operations done on Mysql by Django
I am using Django and MySQL. I have a web site. In this web site i am using some web pages with forms that creates data and deletes data in mysql db. I want to get which DB operations are done behind when i click save button or delete button on web page. I want to see which tables are effected and which rows are created or deleted on Mysql DB. -
How to set GDAL_LIBRARY_URL in django docker based on another image?
I have two services. I use two images. One image is postgis image. Another is django. how can I set up GDAL_LIBRARY_PATH in settings that will point to second image. Both images use alpine linux. version: '3' services: django: image: me/our-image:development build: context: . dockerfile: ./compose/development/django/Dockerfile depends_on: - db volumes: - .:/app env_file: - ./.envs/.development/.django - ./.envs/.development/.postgres - ./.envs/.development/.zoopla ports: - "8000:8000" command: /start db: image: mdillon/postgis:9.6-alpine env_file: - ./.envs/.production/.postgres -
foreign key in django_models
In pgAdmin I create my table : in this table there are 2 columns by "foreign key" and connect to column of other table: how to can create this table in django models? "I use postgresql in django". -
Django and Channels and ASGI Thread Problem
I have a problem using django and channels(in asgi mode) when I set django channels and use asgi mode, my app create a new thread for every http request and every message that I send from channel for example suppose that my app is a simple echo chat server when I run my server and request to connect to socket as client, threads increased and also when I send something to socket again thread increased by every message. Do you know why? How can I fix it?