Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how i get the list Phases of a selected project and put them in forms.ModelChoiceField in django
I want to create a new production and step one is to select a project in the first Field step two is give the list of phases of project selected in the first field. How I do that? this is my Models : class Project(models.Model): STATUS_CHOICE = ( ('En cours', 'En cours'), ('Arret', 'Arret'), ('Terminer', 'Terminer'), ) CATEGORY_CHOICE = ( ('Hydraulique Urbaine', 'Hydraulique Urbaine'), ('Assainissement', 'Assainissement'), ('Hydro Agricole', 'Hydro Agricole'), ('Step', 'Step'), ('Barrage', 'Barrage'), ('AEP', 'AEP'), ) name = models.CharField(max_length=400, unique=True) delais = models.IntegerField() ods_demarage = models.DateField() montant_ht = models.DecimalField(decimal_places=2, max_digits=20) montant_ttc = models.DecimalField(decimal_places=2, max_digits=20) category = models.CharField(max_length=25, choices=CATEGORY_CHOICE) status = models.CharField(max_length=20, choices=STATUS_CHOICE) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Phase(models.Model): name = models.CharField(max_length=200, unique=True) montant = models.DecimalField(max_digits=20, decimal_places=2) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Production(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) phase = models.ForeignKey(Phase, on_delete=models.CASCADE) montant = models.DecimalField(max_digits=20, decimal_places=2) taux = models.DecimalField(max_digits=6, decimal_places=2) montant_prod = models.DecimalField(max_digits=20, decimal_places=2) date = models.DateField(auto_now_add=True) and this is my views method : def create_production(request): form = NewProductionForm() if request.method == 'POST': form = NewProductionForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'production': form } return render(request, 'production/create_production.html', context) my form class NewProductionForm (forms.ModelForm): class Meta: model = Production … -
Django Pagination Next button does not show additional results
I am struggling with the pagination of a DB search query and its results. This is my views.py class SearchView(ListView): model = Project template_name = 'project_automation/search.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') if query is None: result = None elif query.isnumeric(): numeric_query = int(query) postresult = Project.objects.filter(coleman_project_id=numeric_query) paginator = Paginator(postresult, 5) page = self.request.GET.get('search') try: result = paginator.page(page) except PageNotAnInteger: result = paginator.page(1) except EmptyPage: result = paginator.page(paginator.num_pages) elif type(query) == str: # print(type(query)) postresult = Project.objects.filter(description__contains=query) | \ Project.objects.filter(name__contains=query) paginator = Paginator(postresult, 5) page = self.request.GET.get('search') try: result = paginator.page(page) except PageNotAnInteger: result = paginator.page(1) except EmptyPage: result = paginator.page(paginator.num_pages) else: result = None return result pagination_search.html template <div class="pagination"> <span class="span-links"> {% if all_search_results.has_previous %} <a href="?page={{ all_search_results.previous_page_number }}{% if request.GET.search %}?search={{ request.GET.search }}{% endif %}">Previous</a> {% endif %} <span class="current"> Page {{ all_search_results.number }} of {{ all_search_results.paginator.num_pages }}. </span> <span class="current"> {% for num in all_search_results.paginator.page_range %} {% if all_search_results.number == num %} <li class="active"><a href="#!">{{ num }}</a></li> {% else %} <li class="waves-effect"><a href="?page={{ num }}{% if request.GET.search %}&search={{ request.GET.search }}{% endif %}">{{ num }}</a></li> {% endif %} {% endfor %} </span> {% if all_search_results.has_next %} <a href="?page={{ all_search_results.next_page_number }}{% if … -
Delete objects in the database on post request
I have an endpoint that accepts and stores a list of objects. I would like that when sending a post request, a check for event_id occurs and if there are already values in the database with it, then they should be deleted. But I don't understand how this can be done. models class FAQs(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) question = models.CharField(max_length=255) answer = models.CharField(max_length=255) position = models.IntegerField() class Meta: db_table = "FAQs" view class FAQs(viewsets.ModelViewSet): queryset = FAQs.objects.all #permission_classes = [IsAuthenticated] serializer_class = FAQsSerializer def create(self, request, *args, **kwargs): many = True if isinstance(request.data, list) else False serializer = self.get_serializer(data=request.data, many=many) serializer.is_valid(raise_exception=True) serializer.save(event_id=kwargs['pk']) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) serializer class FAQsSerializer(serializers.ModelSerializer): class Meta: model = FAQs fields = ('__all__') -
when i put project on AWS and deploying with apache. django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module
when I put the project on AWS and deploying with apache. django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' solutions tried: *uninstalled and installed pyscopg2 *installed psycopg2-binary *installed psycopg2 inside the environment when I'm deploying locally it's working fine, but when I tried on AWS, getting Django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' error when I run like python manage.py runserver, it's working with no error -
Django REST RetrieveUpdateAPIView problem
I'm using generic RetrieveUpdateAPIView for my API and I want to users can retrieve and update their profile and user informations (profile) . but when I'm testing the API just can retrieve and update profile i can't retrieve the user . serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' extra_kwargs = { 'user': {'read_only': True}, 'id': {'read_only': True}, } class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' extra_kwargs = { 'id': {'read_only': True}, } views: class ProfileRetrieveUpdateView(generics.RetrieveUpdateAPIView): def get_serializer_class(self): return UserSerializer and ProfileSerializer def get(self, request, *args, **kwargs): if request.user.is_authenticated: user = request.user profile = get_object_or_404(Profile, user=request.user) return user and profile return Response( status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) and this is the endpoint: -
Django ImageField image doesn't get uploaded through the form, but it does get uploaded through the admin interface
A similar question has been asked here. However, it has not resolved my issue. I also tried solutions from here and here, among other ones. My problem is that the image that I specified as an ImageField in my model doesn't get uploaded through the form, but it does get uploaded through the admin interface. I also noticed that the function specified in the upload_to attribute of my ImageField doesn't get called through the form, but it does get called when I change the ImageField from the admin interface. I have made sure of the following things: I'm not missing a request.FILES parameter I've made all the database migrations (I deleted all the migrations and the database and started from a blank database several times) Django can create the folders in question (since it creates them successfully via the admin interface) I added enctype="multipart/form-data" to my form I added static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my project's urls.py file (not the apps urls.py file, but the projects urls.py file) Below is the relevant code from the relevant files: models.py: def get_upload_path_logo(instance, filename): print("Here in the get_upload_path_profile_picture function") extension = filename.split('.')[-1] employer_name = instance.name employer_name = employer_name.replace(" ", "-") to_return = "employers/" + str(employer_name) … -
TypeError: can not serialize 'User' object in Chat Application
I want to integrate a chat app with my instagram-like project. My primary goal is to provide the users of this website with the possibility to chat with each other real-time. I have the following code but I keep getting the error: TypeError: can not serialize 'User' object from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json from .models import Message from django.contrib.auth.models import User class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Message.last_10_messages() content = { 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): author = data['from'] author_user = User.objects.get(username = author) message = Message.objects.create(author=author_user, content=data['message']) content ={ 'command' : 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'author' : message.author, 'content' : message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message' : new_message } def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) self.commands[data['command']](self, data) def send_chat_message(self, data): message = data['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) def send_message(self, message): self.send(text_data=json.dumps(message)) def … -
POST 400 Bad Request Django
My branch model has 4 primary keys which are unique together: ('branch_short_name', 'partner_short_name', 'tenant', 'contributor'). I would like to be able to create/ POST some objects with similar 'branch_short_name', 'partner_short_name', 'tenant' but then with a unique 'contributor'. When doing that I get a 400 bad request error in postman. I don't know where the problem lies, in the model or in the serializer. models.py class Branch(models.Model): additional_address1 = models.CharField(max_length=255, blank=True, null=True) additional_address2 = models.CharField(max_length=255, blank=True, null=True) branch_number = models.CharField(max_length=255, blank=True, null=True) branch_short_name = models.CharField(primary_key=True, max_length=255) building = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) country_code = models.CharField(max_length=255, blank=True, null=True) created = models.DateTimeField(blank=True, null=True) display_name = models.CharField(max_length=255, blank=True, null=True) display_web = models.BooleanField(blank=True, null=True) district = models.CharField(max_length=255, blank=True, null=True) file_origin_date = models.DateTimeField(blank=True, null=True) filename = models.CharField(max_length=255, blank=True, null=True) floor = models.CharField(max_length=255, blank=True, null=True) business_name = models.CharField(max_length=255, blank=True, null=True) house_number = models.CharField(max_length=255, blank=True, null=True) import_file_number = models.BigIntegerField(blank=True, null=True) contributor = models.CharField(max_length=255) job_id = models.CharField(max_length=255, blank=True, null=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) start_date = models.DateTimeField(blank=True, null=True) branch_hours = models.CharField(max_length=255, blank=True, null=True) po_box = models.CharField(max_length=255, blank=True, null=True) province = models.CharField(max_length=255, blank=True, null=True) region = models.CharField(max_length=255, blank=True, null=True) remarks = models.CharField(max_length=255, blank=True, null=True) street = models.CharField(max_length=255, blank=True, null=True) … -
Need help understanding If I need to implement a refresh system for my JWT token for Django clients?
I'm trying to create a well-rounded authentication/registration/login system in Django using the rest framework. I've slowly started wrapping my head on how to get it done well. I want to be satisfied with my token situation, however after reading all the docs and looking at other git repo's, I've seem to dug myself in a hole of confusion. To my understanding, there are some libraries that do token authentication/refreshing for you, others give you the tools to create one. I'm not sure if I have a solid base to build a token refresh function given my code below. I would greatly appreciate some help on how I can implement a token refresh system for users that log-in. Here is my code, it works fine and I see registration data in my User model. serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=65, min_length=8, write_only=True) email = serializers.EmailField(max_length=255, min_length=4) username = serializers.RegexField("^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{3,29}$") first_name = serializers.RegexField("^[A-Za-z]+((\s)?((\'|\-|\.)?([A-Za-z])+))*$", max_length=32, min_length=2) last_name = serializers.RegexField("^[A-Za-z]+((\s)?((\'|\-|\.)?([A-Za-z])+))*$", max_length=32, min_length=2) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def validate(self, attrs): email = attrs.get('email', '') if User.objects.filter(email=email).exists(): raise serializers.ValidationError( {'email': ('Email is already in use')}) return super().validate(attrs) def create(self, validated_data): … -
Is there a way to connect a PostgreSQL and Django in a2hosting shared hosting
I know this may sound silly, but I want to know how to connect PostgreSQL to Django in a shared hosting of a2hosting, I mean you only get username and password while creating a database according to this tutorial here https://www.a2hosting.com/kb/cpanel/cpanel-database-features/managing-postgresql-databases they only provide a username and password but how do I connect them in Django, an alternative could someone show me Database production level setting in Django... Thanks in advance... -
Filtering condition on many to many field in subquery
I came across a case when I need to ignore the condition if the many-to-many field is empty and vice versa apply the condition if it exists, which I'm trying to do: class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) class BookSearch(model.Models): authors = models.ManyToManyField(Author) BookSearch.objects.annotate( books_count=Subquery( Book.objects.filter( Q(author__in=OuterRef('authors')) | Q(OuterRef('authors') == None), ).values('id').annotate(c=Count('id')).values('c')[:1] ) ).values('books_count') In the OuterRef ('authors') == None block I'm trying to check the condition, but it's clear that it won't work here, it's just an example of what I want to achieve, I've been trying to figure it out for a couple of days, I will be grateful for any help. And dont look on .values('id').annotate(c=Count('id')).values('c')[:1] its just an example. -
Filter nested queryset in serializer
I have these models: class Item(..): .... class Folder(..): ... class File(..): item = ... folder = ... class FileSerializer(...): class Meta: model = File class FolderSerializer(...): files = FileSerializer(many=True,readonly=True) class Meta: model = Folder When I call the FolderViewSet LIST request, it serialized all the Files for every Folder. I need to make it serialize only files that became to the particular Item. Right now, I'm filtering the Files on the frontend but that will become very heavyweight in a future. Do you know how to make it work? Is there a built-in way? -
Is at a good idea use serializers to convert client data to json?
My task is to take data from the client, convert it to the canonical form (if the client has not specified any fields, set the default) and then send it to the service by "POST" request. For example, the canonical message looks like this { "action": "user_created", "body": { "name": "Test user", "age": 25, "isActive": false }, "creationDate": "2020-10-10" } But the client has to send data to me like this: { "name": "Test user", "age": 25 } My task is to take the json of the client, convert it to the canonical form (if it has not filled in some fields, then fill them with a default value). I have UserSerializer: class UserSerializer(Serializer): name = serializers.CharField(reguired=False, default='Test user') age = serializers.IntegerField(required=False, default=25) And then i convert the data to canonical form: def canonical(request_body): serializer = UserSerializer(data=request_body) serializer.is_valid(raise_exception=True) canonical = { 'action': 'user_created', 'body': serializer.data, 'creationDate': date_now() } return json.loads(json.dumps(canonical)) Is this a good way to convert user data to canonical form? Please note that I don't need to save anything to the database. -
Get a list of last messages sent to/by a user from/to other users, using a Message table. Django. Chat app
The Model class Message(models.Model): sender = models.ForeignKey( User, ... ) receiver = models.ForeignKey( User, ... ) text = models.TextField("text") time = models.DateTimeField("Time", ...) class Meta: ordering = ("-time",) I'm making a chat app. On the chats page, I have to show the last messages from each communication. Required Behavior Let's assume the logged in user is x and any other user is y. We expect the query to return a list of messages such that: The message model can have either sender or receiver as user x. However, the returned result should only have one message that was last communicated between user x and user y. The resulting list of messages are ordered by descending time. Using the words communication/communicated means that direction (to/from) is irrelevant. How can I construct a Django ORM query for this? I'm using the latest Django and PostgreSQL. I'm having a hard time describing this requirement, so I apologize. Any help will be appreciated. Thank you. -
Full text search in MySql and Django
I have just learned how to use MySQL Database for my django project, and now I would like to implement full text search for my app. I did search for this online, and the resources found were either for PostgresSQL, or really old. How can I implement full text search using a MySQL database for my Django project -
How can I showcase a front-end search function that utilizes a python script and csv database?
I have a database of cars: Car Dealership Price honda A $100 honda B $105 honda C $98 toyota A $101 toyota B $92 toyota T $80 Let's say I've developed a function in python that returns the lowest priced dealership when I enter in the car name ie - I enter in 'toyota' and 'T' is returned. The function is: def cars(car): python code to find lowest priced dealership returns 'Dealership' I have this saved as a python script. I'd like to make a front end site that simply has a search box and will return the results of my function, using that script, when a user enters in their selection which would plug into the 'cars' function. Ive looked at Dash/flask, Django, and Tableau - and they don't seem to have something this simple. -
gunicorn not Binding showing some package error?
I have installed PostgreSQL and Nginx and all those things's working fine please let me help for this error it' showing error after tying to bind my project but I tested another sample project but it's working fine I can't able to bind gunicorn please help me 502 Bad Gateway [2020-12-11 15:30:39 +0000] [30480] [INFO] Starting gunicorn 20.0.4 [2020-12-11 15:30:39 +0000] [30480] [INFO] Listening at: http://0.0.0.0:8000 (30480) [2020-12-11 15:30:39 +0000] [30480] [INFO] Using worker: sync [2020-12-11 15:30:39 +0000] [30482] [INFO] Booting worker with pid: 30482 [2020-12-11 15:30:39 +0000] [30482] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/env/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in … -
I wanted to create a search box in which it has to show the results as each character is typed
This is the html code of search bar. <form id="search"> <input type="text" name="key" placeholder="Search" width="100" id="contact"> </form> I want to pass the values to Django inorder to return the results. I have created a Django project with the name contactlist and an app inside with the name contacts. I have done all the requirements for code to be running. Please help me creating the search bar. Thank you in advance! -
Unable to start server of Django through command prompt
When I type " python manage.py runserver " it show this in the picture how to fix this problem? Once I've started the server but now it shows this error. -
how to format & show required content in log file(logger) whenever any changes is happening in model objects
I am trying to implement logger functionality to my Django Application. In my App, I am having 6 different Models(from frontend users can change their Shift Timing/delete or upload new user's records from the .xls file). I want to create a log file so that I can monitor which user is logined and what action he performed(e.g update /delete/upload/download). Please find the below code I am using in my settings.py which is giving me a huge log without proper format. (However, I can see the action details in the generated log file but the structure is not user-friendly). settings.py import logging # DataFlair #Logging Information LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #########formatter######################### #disable logging 'formatters': { # 'console': { # 'format': '%(name)-12s %(levelname)-8s %(message)s' # }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, #########################Handlers ################################## 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'Apple3.log', }, }, ################################ Loggers ################################# 'loggers': { 'django': { 'handlers': ['file',], 'level': 'ERROR', 'propagate': True, 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG') }, }, } Please find the few lines from the log file. Traceback (most recent call last): File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/template/base.py", line 849, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed … -
Using Jquery select radio otpions from dictionary
I have a HTML template which has Multichoice Question with options and Essay type questions. The user's answers are saved in model called Sitting in user_answers field as sitting.user_answers = {"424": "1527", "319": "adadadf", "203": "786", "437": "1572", "383": "1429"} The first number is the question_id and and second is the answer_id(selected option) or answer itself (incase essay type question). I am able to display the questions in one template using the following code: views.py if self.sitting.get_first_question() is False: questions= MCQuestion.objects.filter(question_ptr_id__in=self.sitting._question_ids()).prefetch_related('answer_set__question') essayquestions= Essay_Question.objects.filter(question_ptr_id__in=self.sitting._question_ids()) answerdetails = Sitting.objects.filter(id=self.sitting.id) print(answerdetails) return render(self.request, 'dashboard/exam-review.html', {'questions': questions,'essayquestions': essayquestions,'form': True}) Template {% for question in questions %} <div class="row mt-2 mb-4 shadow-1" style="background: #ececec"> <div class="col-md-10"> <input type=hidden name="question_id" value="{{ question.id }}" class="question_id"> <div class="panel-heading"> <p class="panel-title mb-2 mt-2" > <li style="list-style-type: none;" class="mb-1 mt-1"><strong> {% autoescape off %}{{ question.content }}{% endautoescape %} </strong></li> {% if question.figure %} <div class="row mb-1"> <img src="{{ question.figure.url }}" alt="{{ question.content }}" /> </div> {% endif %} {% if question.questionmarks %} <div class="row ml-1" > <p style="font-size:0.8rem"><b>Marks :</b> {{ question.questionmarks }}</p> </div> {% endif %} </div> <div class="panel-body "> <ul class="mb-2" style="list-style-type: none;"> {% regroup question.answer_set.all by get_content_display as answer_list %} {% for answers in answer_list %} <span>{{ section.grouper }}</span> … -
Using some variable in Django CASE WHEN condition
I am having something like: value = Func(Now(), F('reg_date'), function='DATEDIFF') # days since registration exp = Case( When(value__gt=150, then=Value(1.5)), When(value__gt=90, then=Value(1.3)), default=0 ) User.object.aggregate(score=Avg(exp)) You can se here the value is not a field from the model, and I want to perform the check on it. Is there a way I can perform the check inside the When condition on non-model fields? Actually, I want to perform the following SQL Query: select AVG( CASE WHEN DATEDIFF(now(), reg_date) > 150 THEN 1.5 WHEN DATEDIFF(now(), reg_date) > 90 THEN 1.3 ELSE 0 END) as score from users_user; -
Django search by lat, lon and name of a business
I am trying to search for location using latitude, longitude and the name of the business. How do I use multiple parameters in objects.filter ? My current code can search by lat and lon. I want to search by name of business for a given lat and lon. Here is my code: businesss = Business.objects.filter(location__dwithin=(ref_location, 50000))\ .annotate(distance=GeometryDistance("location", ref_location))\ .order_by("distance") -
Request.user on Django Model forms
I have a ledger account table that consist of ledger accounts of all the companies. The user in logged into a specific company and hen he selects an account to use on a form only the accounts that company must be available for the user. for this purpose I use the request.user to determine the user. I however get an error "request does not exist". I understand why it is not available on the forms.py as there is no request executed. Is there a way that I can make request.user available of the form. Models.py class tledger_account(models.Model): id = models.AutoField(primary_key=True) description = models.CharField(max_length=30, unique=True) gl_category = models.CharField(max_length=30, choices=category_choices, verbose_name='category', db_index=True) note = models.CharField(max_length=25, blank=True, default=None) active = models.BooleanField(default=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT, db_index=True) forms.py class SelectAccountForm(forms.ModelForm): date_from = forms.DateField(widget=forms.SelectDateWidget(years=year_range)) date_to = forms.DateField(widget=forms.SelectDateWidget(years=year_range)) select_account = forms.ModelChoiceField(queryset=tledger_account.objects.filter( company = request.user.current_company)) class Meta: model = ttemp_selection fields = ['select_account', 'date_from', 'date_to'] -
Django Simple History INSERTS rather than UPDATES when reverting a model
I'm reverting a model instance as specified in the docs: # In a DRF ViewSet, although I don't think that should matter... instance = self.get_object() # Find the historical record I want desired_record = instance.history.first().prev_record # Get the instance from it (I removed code handling the edge case of no prior history, for question clarity) desired_instance = desired_record.instance # EDIT, I have also tried # desired_instance = instance.history.most_recent() # which exhibits the same problem on save # Include a changelog comment desired_instance._change_reason = "Reverted to previous" # Update the instance desired_instance.save() However, this produces the error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "projects_configuration_pkey" DETAIL: Key (id)=(9ffc4e31-e714-4258-95dd-a196a70bf301) already exists. The model (in app projects) looks like: class Configuration(models.Model) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(auto_now=True) name = models.CharField(blank=False, null=False, max_length=60) The same problem occurs when I use the instance.history.as_of(<datetime>) method. DSH seems to be attempting to insert a new record rather than update the existing one to a former state. What's going on here?