Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying django(windows) with apache(on unix)
I know it might be a bad design but since we are developing the django website on our laptops which runs Win7, I thought it would be better to run django on a Windows platform only in production. (Laptop is not powerful enough to run a Unix VM inside and our Unix team doesn't provide any Unix server with UI access (Only Putty) so using an IDE is impossible on Unix.) I have deployed django with gunicorn and nginx on a Linux server very easily, but this time I have to deploy django on a Windows server with Apache on another Unix server (I know it sucks). Our middleware team is asking(forcing) to run django components on a separate server so that they can manage their Apache (on Unix) instance comfortably. As far as I understand, Apache and django should reside on the same server for mod_wsgi to work. Is this possible to keep Apache on a Unix machine and make a django website run from a Windows machine? If not, what are the best possible solutions in my case? (Switch django on Unix? Use waitress on Django windows? Do not separate Apache and Django? etc.) Regards, Aditya -
Is it possible to create more Data Fields after Migrations have taken place?
I wanted to ask if it is possible to add more integerfields and charfields to a model if it has already been migrated to an SQLite database. -
django-filters: How do I use ModelChoiceFilter, unable to add classes to form fields and unable to set form labels
I'm trying to create a drop down form as a filter but its not working, and I'm trying to have a text field along with it. The two model fields that the fields are pulling from are a TextField and CharField respectively. filters.py import django_filters as df from django import forms from django.utils.translation import ugettext_lazy as _ from .models import FoodTruck class FoodTruckFilter(df.FilterSet): category_queryset = FoodTruck.objects.exclude(category='').values_list('category', flat=True).distinct().order_by('category') category_drop_down = df.ModelChoiceFilter(queryset=category_queryset) class Meta: model = FoodTruck fields = { 'name': ['icontains'], 'category': ['icontains'], } labels = { 'name': _('Food Truck Name'), 'category': _('Category'), } #widget = { # 'name': forms.TextInput(attrs={'class': 'form-control'}), # 'category': forms.Select(attrs={'class': 'form-control'}) #} models.py class FoodTruck(models.Model): name = models.CharField(max_length=25) category = models.CharField(max_length=20) bio = models.TextField() avatar_url = models.URLField(blank=True) avatar_alt_text = models.CharField(max_length=20, blank=True) avatar_title = models.CharField(max_length=20, blank=True) cover_photo_url = models.URLField(blank=True) cover_photo_alt_text = models.CharField(max_length=20, default="No photo provided") cover_photo_title = models.CharField(max_length=20, default="No photo provided") website = models.URLField(blank=True, null=True) facebook = models.URLField(max_length=100, blank=True, null=True) instagram = models.CharField(max_length=30, blank=True, null=True) twitter = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name views.py class TruckListView(generic.ListView): model = FoodTruck template_name = 'truckReviews/landing.html' ordering = 'name' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = FoodTruckFilter(self.request.GET, queryset=self.get_queryset()) return context landing.html {% extends "truckReviews/base.html" %} {% block content %} <!--Filter … -
understanding django formset
please someone can explain for me a bit more about formset with its template , all my formsets only save the last form a appreciate your helps class Name(models.Model): name = models.CharField(unique=True,max_length=50) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name forms.py class NameForm(ModelForm): class Meta: model = Name fields = '__all__' NameFormSet = modelformset_factory(Name,form=NameForm,extra=1,max_num=10) my template <button class="btn-block mt-1 border-left border-right shadow-lg" id="add_more">+</button> <div class="dup col-12" style="border-top:1px solid white;border-radius: 30px;"> <form method="POST">{% csrf_token %} {{formset.management_form}} <div class="row mx-auto p-2" class="div1"> <div class="input-group inp mx-auto col-12 col-sm-10 p-1 col-md-5 div2 dynamic-form"> {% for form in formset.forms %} {{form.name | add_class:'col-12' | attr:'id:add'}} {% if form.name.errors %} <div class="text-center text-light bold">{{form.name.errors}}</div> {% endif %} {% endfor %} </div> </div> <div class="col-12 col-sm-7 col-md-3 mx-auto"> <button class="s btn-block mt-1 border-left border-right shadow-lg">insert</button> </div> </form> <script> $('#add_more').click(function() { cloneMore('.dynamic-form:last', 'add'); }); </script> <script> function cloneMore(selector, type) { var newElement = $(selector).clone(true); var total = $('#add_' + type + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-'); var id = 'add_' + name; $(this).attr({'name': name, 'add': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-'); $(this).attr('for', newFor); }); total++; $('#add_' + type … -
Got AttributeError when attempting to get a value for field `Name` on serializer `AppointmentSerializer`
When attempting to get a value for field Name on serializer AppointmentSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Response instance. Original exception text was: 'Response' object has no attribute 'Name'. Here is my models.py class Doctor(models.Model): DoctorName = models.CharField(max_length=25) def __str__(self): return self.DoctorName class Appointment(models.Model): Name = models.CharField(max_length=25) Phone = models.CharField(max_length=12) Email = models.EmailField() Date = models.DateTimeField(auto_now=False) Comments = models.TextField(max_length=60) Doctor= models.ForeignKey(Doctor,on_delete=models.CASCADE) def __str__(self): return self.Name serializer.py from rest_framework import serializers from .models import Appointment class AppointmentSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = ['Name','Phone','Email','Date','Comments','Doctor'] views.py class AppointmentDetailView(APIView): def get_object(self,id): try: return Appointment.objects.get(id=id) except Appointment.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, request, id=None): appointment = self.get_object(id) serializer = AppointmentSerializer(appointment) return Response(serializer.data) def put(self, request, id=None): appointment = self.get_object(id) serializer = AppointmentSerializer(appointment, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, id=None): appointment = self.get_object(id) appointment.delete() return Response(status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ path('detail/<int:id>/', AppointmentDetailView.as_view()) ] -
Django: Show different button in template if user object exists
I want to show one button if a user has already added an object, and another button if he/she hasn't. In my template I have: <tr> {% for word in dict_list %} <td>{{word.target_word}} </td> <td>{{word.source_word}}</td> <td> <a href="javascript:" class="add-word btn btn-warning btn-sm" data-wordpk="{{word.pk}}">Add</a> {% if user_word %} <a href="" class="add-word btn btn-success btn-sm" >Added</a> {% endif %} </td> </tr> {% endfor %} And in my views: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) def get_context_data(self,**kwargs): context = super(custom_create_word, self).get_context_data(**kwargs) if Word.objects.filter(target_word=target_word, user=user).exists(): user_word == True context['user_word'] = user_word return context I don't get any errors, but I don't get the desired result either. Am I going about it the wrong way? -
How do i integrate microsoft translation api into my web app?
I'm new to Django and I'm trying to understand how to integrate the Microsoft Translator API into my code on Pycharm. I am confused as to where to include the different codes with the subscription keys. I have already created an account on Microsoft and got the subscription key. -
How can I make only superusers to edit model
I have 2 models: Recipe and Ingridient and I want that only superusers will be able to edit model Ingridient, normal users can only view ingridients and are not able to edit them. Right now is set that way that if you are logged in you have all permissions, but I want that only superusers have ability to edit Ingridients and normal logged in users are able to add recipes (not able to edit ingridients). #views.py class ReceptViewRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = Recipe.objects.all() lookup_field = 'id' serializer_class = RecipeSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def delete(self, request, *args, **kwargs): try: id = request.data.get('id', None) response= super().delete(request, *args, **kwargs) if response.status_code == 204: from django.core.cache import cache cache.delete("{}".format(id)) return response except Exception as e: return response({ "Message":"Failed" }) def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) if response.status_code == 200: mydata = response.data from django.core.cache import cache cache.set("ID :{}".format(mydata.get('id', None)),{ 'title':mydata["title"], 'description':mydata["description"], 'image':mydata["image"], 'galery':mydata["galery"], 'kitchen_type':mydata["kitchen_type"], 'num_persons':mydata["num_persons"], 'preparation_steps':mydata["preparation_steps"] }) return response class SestavinaViewRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = Ingridient.objects.all() lookup_field = 'id' serializer_class = IngridientSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def delete(self, request, *args, **kwargs): try: id = request.data.get('id', None) response= super().delete(request, *args, **kwargs) if response.status_code == 204: from django.core.cache import cache cache.delete("{}".format(id)) return response except Exception as e: … -
Django: Pipfile.lock dependency installation problem
I am working on a Django Project (in Docker) and use pipenv for installation of various packages. When installing the latest package, I made a mistake by using docker-compose exec web pipenv install dateutil instead of python-dateutil, which is the correct package name. What happened is that the installation failed with the message that there is no package with this name. Nevertheless dateutil showed up in my pipfile. So I tried to remove it from the file via docker-compose exec web pipenv uninstall dateutil which did not work, as the package is not installed. I went on and simply deleted dateutil from my pipfile and installed python-dateutil with the correct name. When I tried to rebuild my image afterwards I got the following error message: Installing dependencies from Pipfile.lock (789763)… remote: Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/code-_Py8Si6I/bin/python: not found remote: remote: Output: remote: Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/code-_Py8Si6I/bin/python: not found remote: remote: Output: remote: Failed to load paths: /bin/sh: 1: /root/.local/share/virtualenvs/code-_Py8Si6I/bin/python: not found remote: remote: Output: remote: Removing intermediate container 84c77fef6192 remote: ---> 109aa5618fd4 remote: Step 8/8 : COPY . /code/ remote: ---> 5afe012dfe80 remote: Successfully built 5afe012dfe80 remote: Successfully tagged 3c44f0505a52f77469b72b43bc40afe49fed878e:latest My app still works (locally … -
ERROR: Could not find a version that satisfies the requirement django>=2.0
I'm using python2 and django vesrion 1.8.13. When I tried to install django-urls got this error. Using cached django_urls-1.0.3.tar.gz (1.9 kB) ERROR: Could not find a version that satisfies the requirement django>=2.0 (from django-urls) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26, 1.11.27, 1.11.28, 1.11.29) … -
Django3 inspectdb Oracle schema
I want to generate models for Oracle's pre-existing SCOTT schema (i have other schemas as well but i want a working example so ..), inspectdb is working fine and generating models for public schema. following command returns models for all tables in Public schema python manage.py inspectdb> output.py I have multiple schemas and the tables have 100s of columns, creating models for individual tables manually looks impossible. i tried using python manage.py inspectdb MYSCHEMA.TABLE_NAME > output.py however this doesn't work. I tried many workarounds like introspection.py modification but it didn't work. please someone give a working example with SCOTT schema and django. it would be very useful for all those people starting django with oracle. thanks :) -
how to update data in template with out refresh the page in django
I am working on an eCommerce project. when the user added an item into the cart then item saved into the database then I am reloading the page to update the cart items in the template. but the problem is every time the page reloading is very critical in the production server. so I need help on how to update the data in the template without reloading the page every time. any suggestions, please... Thanks in advance. -
Django redirect from other domain gives Page Not Found error
When clicking on a url that points to my Django website, I get a Page Not Found error. When I look to the error with DEBUG=True, I see that the "current path" displayed in the error message is different from the actual url. For example, take a look at the shared articles on linkedin: https://www.linkedin.com/company/huvepharma-nv/. When clicking on the first post I am redirected to my Django website: https://huvepharma.com/news/article/how-butyrate-producing-bacteria-can-support-food-safety/. This gives me a Page Not Found error, saying that the current path is company/huvepharma-nv/, which is the path on the LinkedIn website. How can I fix this? I added the following fix in the past but now I get ERR_TOO_MANY_REDIRECTS with DEBUG=False. So the quick fix is also not working anymore. def handler404(request, exception, template_name='errorhandlers/handler404.html', *args, **kwargs): if request.META.get('HTTP_SEC_FETCH_SITE') == 'cross-site': return redirect(request.path) response = render_to_response(template_name) response.status_code = 404 return response -
DRF will not update record although getting 200 OK
Every 1/10 requests for updating a record, the framework would response 200 ok, but after fetching the same record using GET, I don't see the changes. When running it in context of unit test, this will not reproduce Is there a way narrowing down what causing it? -
Django order by Min Distance to a list of points
I want to get a queryset of all Jobs that are within a given distance to at least one of the many provided locations, order them by the minimum distance, and do not show duplicate jobs. from django.db import models from cities.models import City class Job(models.Model): title = models.CharField(max_length=255) cities = models.ManyToManyField(City) If there is only one point I could do this as: from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import Point point = Point(x, y, srid=4326) Job.objects.filter(cities__location__dwithin=(point, dist)) \ .annotate(distance=Distance("cities__location", point) \ .order_by('distance') but when I have many points I build out a Q expression for the filter but am unsure of a clean way to annotate the Min distance of the Job to all points query = Q() for point in points: query |= Q(cities__location__dwithin=(point, dist)) Job.objects.filter(query).annotate(distance=Min(...)).order_by('distance') FYI using postgres 12.1 with PostGIS extension -
Validated data fields differs from data fields Django Rest Nested serializers
so I was playing around with serializers in django and wanted to change the names of my fields in my response when I realized my changes had not been taken in count I did some digging and saw that my validated_data differs from my data. My goal here is to give a python object to a serializer which has different fields than the name I want to return so I used the 'source=' argument to my field. Note that changing the name of the python object's field is not an option. Here's the python object: class Flow(object): """Just a regular python object""" def __init__(self, name=None, flow_uid=None, data_type=None, parent=None, container=None): """This has more fields than the serializer is waiting""" self._parent = None self._container = None self.name = name self.data_type = data_type self.flow_uid = flow_uid And the following serializers (I am using a nested representation) serializers.py from rest_framework.fields import CharField, IntegerField, ListField, JSONField from rest_framework.serializers import Serializer class OutputSerializer(Serializer): uid = CharField(max_length=36) name = CharField(max_length=100) description = CharField(max_length=100) class FlowSerializer(Serializer): uid = CharField(source='flow_uid', max_length=36) # I want 'uid' in my response not 'flow_uid' name = CharField(max_length=100) data_type = CharField(max_length=100) class Meta: fields = '___all___' def to_representation(self, instance): instance = super(FlowSerializer, self).to_representation(instance) #Here … -
Autocomplete django in visual studio code
hello everyone I am having a problem the visual studio code autocomplete for django does not work for me, because for python it does it without problems but when working with django the framework options do not work, that is when I work with views based on classes does not generate the autocomplete, such as template_name, form_class, etc ..., likewise with the models it does not generate the help of max_length, and those other things of the framework, I have selected the interpreter but it does not work for me and also python: build workspace symbols and nothing. in advance I appreciate the help. -
How to query and get a specific field within a user's related data (ManytoMany)
what I am trying to do is that I am trying to query and get all departmental_goals thats available to the user based on the departments they are in, to pass into the template as a context. So lets say, a manager creates a departmental goal, this departmental goal(that has a department field) will be available to all users based on the department they are in, defined within the department field of user.Profile. However, I have no idea how to get about this, I tried this query but it has failed and I have no idea why, can someone push me in the right direction Query I tried departmental_goals_database = Departmental_Goals.objects.get(department = request.user.profile.departments_set.all()[0].name) Views.py @login_required(login_url = 'login') @allowed_users(allowed_roles=['Employee']) def User_GnC(request): #Get user's profile and retrieve all departmental goals (Not fixed yet) departmental_goals_database = Departmental_Goals.objects.get(department = request.user.profile.departments_set.all()[0].name) #context to pass into template context ={ "departmental_goals_list":departmental_goals_database } return render(request,'GnC/HuNet_GnC.html', context) Profile models #Class profile one-to-one linked to user + many-to-many linked to department class Profile(models.Model): user = models.OneToOneField(User, null = True, on_delete=models.CASCADE) name = models.CharField(max_length = 200, blank = False, null = False) email = models.EmailField(blank = False, null = False) department = models.ManyToManyField(Departments, blank = False, null = False) def __str__(self): … -
Django Rest Framework: Validation not working when setting a "validator" inside the model field
I created a simple model for Tasks, the "days" field is supposed to be a list of integers from 0 to 6 depending on the days of the week that the tasks is supposed to be done. For example Monday, Wednesday and Friday would be 1,3,5 class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) time = models.TimeField() days = models.CharField(validators=[int_list_validator], max_length=16, blank=True) The serializer looks like this: class TaskCreateSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['name', 'time', 'days'] And the View looks like this: class TaskCreateAPI(CreateAPIView): serializer_class = TaskCreateSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) When I do a POST request with some invalid data in the "days" field it will not raise any errors: { "name": "Laundry", "time":"22:30", "days":"not an integer list" } How can I have the validation done for my API request? What is the point of adding the validation inside the model field if it's not being validated when I do a POST request? -
Optimize IN CLAUSE in django
I want to optimize the following query with a Django==1.8.5 P.S I cannot upgrade the DJNAGO version at this point and use Exists clause This is taking almost 20 seconds to execute as the number of rows in this table is 41240271 query_action = Action.objects.filter(id=user_id, verb__in=list_of_verbs) query_action.order_by("-timestamp") last_activity = query_action[0] SELECT * FROM "action" WHERE ("action"."verb" IN (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) AND "action"."id" = %s) ORDER BY "action"."timestamp" DESC LIMIT ? -
'CustomUserCreationForm' object has no attribute 'cleaned_data'
The 'cleaned_data' attribute is not working on my custom form. The same issues I am facing while I try to use 'cleaned_data' directly through views.py file. Even after searching everywhere on internet, the issue is not resolved. Please help. The error displayed once I Submit the form: 'CustomUserCreationForm' object has no attribute 'cleaned_data' forms.py shows class CustomUserCreationForm(forms.Form): username = forms.CharField(label='Enter Application number', min_length=4, max_length=150) email = forms.EmailField(label='Enter email') password1 = forms.CharField(label='Enter password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'].lower() r = User.objects.filter(username=username) if r.count(): raise ValidationError("Username already exists") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise ValidationError("Email already exists") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit=True): user = User.objects.create_user( self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'] ) return user and in views.py def register_view(request): form =CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid: roll_no = form.clean_username() email = form.clean_email() print(roll_no) print(email) context = { 'form':form } return render(request,'accounts/register_page.html',context) and in the template: <form action="" method="post"> {% csrf_token %} {{form.username}} {{form.email}} {{form.password1}} {{form.password2}} <button type="submit">Submit</button> </form> -
How to override Django Admin AutoComplete widget wrapper
I'm trying to override the AutoComplete widget in the admin and it's been a nightmare because I don't think many people have tried to customize it much. It's also wrapped in another widget RelatedFieldWrapper which I need to pass a dynamic variable to after a file has been uploaded. For context: what I do is I fetch some values from that file, and use them as initial data to create a bunch of inline formsets. This fine, but one of the columns is an Autocomplete. I can't pass data to that field since it needs a foreign key I won't know in advance, so I'm sending the data to that field as extra text in the Autocomplete's wrapper. So far this is what I have: class ChartItemForm(forms.ModelForm): hint = forms.CharField(widget=forms.HiddenInput) title = forms.ModelChoiceField(queryset=Title.objects.all()) def __init__(self, *args, **kwargs): super(ChartItemForm, self).__init__(*args, **kwargs) if 'hint' in self.initial: hint = self.initial['hint'] self.fields['title'].widget = MyRelatedFieldWidgetWrapper( AutocompleteSelect(self.instance._meta.get_field('title').remote_field, site._registry.get(Title).admin_site,), self.instance._meta.get_field('title').remote_field, site._registry.get(Chart).admin_site, hint=hint) It's ugly but it works kinda, but I'm getting this error: 'tuple' object has no attribute 'field' After much digging I saw it's because the Autocomplete widget's choices attribute don't have the field attribute. I guess in my overwrite the field is not being properly … -
Django Table Join ORM query
I have Three tables which i need to join using the django orm query if anyone could help please. These are the example models: Table1 - Debtors name = model.CharField(max_length=50) Table2 - CreditSales date = models.DateField() debtor = models.ForeignKey(Debtors, on_delete=models.CASCADE) amount = models.PositiveIntegerField() Table3 - DebtorPayment date = models.DateField() debtor = models.ForeignKey(Debtors, on_delete=models.CASCADE) amount = models.PositiveIntegerField() I tried this query in my views, but its giving duplicate results when trying to fetch a single debtor results from the three joined tables: def get_debtor_details(request, pk): results = Debtors.objects.filter(pk=pk).values('creditsales__date', 'creditsales__amount', debtorpayment__amount').distinct().order_by('creditsales__date') this query gives duplicate results. Please Help. Expected output date credit amount payment 1/1/20 50,000 50,000 2/1/20 70,000 60,000 and so on -
React-admin. Populate SelectField choices with ENUM from IntrospectionQuery (GraphQL simple data provider)?
My GraphQL backend is django-graphene, which creates ENUM kind in schema for every enumeration field (field with defined choices in django models). React-admin data provider is ra-data-graphql-simple. django model Choices are defined in Django model and this is set in stone: class Dataset(models.Model): class State(models.IntegerChoices): INIT = 0, _('Initializing') STARTED = 1, _('Started') READY = 2, _('Ready') state = models.IntegerField(choices=State.choices, default=State.INIT) django-graphene class DatasetQL(DjangoObjectType): class Meta: model = Dataset IntrospectionQuery { "data": { "__schema": { ... "types": [ ... { "kind": "OBJECT", "name": "Dataset", "description": null, "fields": [ ... { "name": "state", "description": "", "args": [], "type": { "kind": "NON_NULL", "name": null, "ofType": { "kind": "ENUM", "name": "DatasetState", "ofType": null, "__typename": "__Type" }, "__typename": "__Type" }, "isDeprecated": false, "deprecationReason": null, "__typename": "__Field" }, ... ], "inputFields": null, "interfaces": [], "enumValues": null, "possibleTypes": null, "__typename": "__Type" }, ... { "kind": "ENUM", "name": "DatasetState", "description": "An enumeration.", "fields": null, "inputFields": null, "interfaces": null, "enumValues": [ { "name": "A_0", "description": "Initializing", "isDeprecated": false, "deprecationReason": null, "__typename": "__EnumValue" }, { "name": "A_1", "description": "Started", "isDeprecated": false, "deprecationReason": null, "__typename": "__EnumValue" }, { "name": "A_2", "description": "Ready", "isDeprecated": false, "deprecationReason": null, "__typename": "__EnumValue" } ], "possibleTypes": null, "__typename": "__Type" }, ... ], "__typename": "__Schema" } … -
Django object saved while debugging but won't save when code is run with debugging
I am using nested serializers and I have overridden the update method of ModelSerializer. A Strange thing is happening when I run the code. If I debug the code line by line, the nested object is updated but if I run the code without debugging, the object is not updated. Here is my update method of serializer - try: nested_object_data = validated_data.pop('nested_data')[0] nested_object = instance.nested_object.all() for (key, value) in nested_object_data.items(): setattr(nested_object[0], key, value) nested_object[0].save() except KeyError: pass for (key, value) in validated_data.items(): setattr(instance, key, value) instance.save() return instance Thanks a lot for your time and help.