Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing image PIL object from view to other view django
How do I pass a PIL Image object from one view def to other view def? It is posiible with use reverse() function. I would like to display the changed image on the imageSizeConverter view without saving. My code is def imageSizeConverter(request): if request.method == 'POST': item = request.FILES.get('imgInp') width = int(request.POST.get('width')) height = int(request.POST.get('height')) proportion = request.POST.get('proportion') root = tk.Tk() root.withdraw() file_path = filedialog.askdirectory() name = request.POST.get('fname') print(file_path) img = Image.open(item) if(proportion == 'on'): img.thumbnail((width, height)) else: img.resize((width, height)) resultFileName, file_extension = os.path.splitext(name) if not file_extension: filename, file_extension = os.path.splitext(item.name) nazwa = file_path + "/" + resultFileName + file_extension img.save(nazwa) response = HttpResponse(content_type="image/png") img.save(response, "PNG") return render(request, "app/imageSizeConverter.html", { 'title':'Zmiana rozmiaru', 'year':datetime.now().year, 'image': reverse('show_image') }) def show_image(request): response = HttpResponse(content_type="image/png") img.save(response, "PNG") return response -
Parent module '' not loaded, cannot perform relative import
This is the project structure. --KP --app --api --views --mpg.py --gtt.py mpg.py: def cmcid(): ..... ..... gtt.py: from .mpg import cmcid def main(): variable = cmcid() if __name__ == "__main__": main() when I run from views directory, i.e kp/app/api/views$python gtt.py I get an error as: Parent module '' not loaded, cannot perform relative import Any help is appreciated. Thanks.. -
How do I make a query inside a form based on other model?
I have two models: Teacher and Course. I want that my form will display the courses list only for the logged in teacher. Example: teacher A has courses X and Y, but doesn't have course Z, so only X and Y will be displayed in the form options. I don't know how to build the query set. A course actually has 2 teachers (course teacher and seminar teacher), so if teacher is one of those, the course will be shown in form choices. class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, verbose_name="Course Teacher", related_name='%(class)s_course_teacher') teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True, verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher') slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name class TeacherData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) teacher_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) class Meta: verbose_name = "Teacher Data" verbose_name_plural = "Teachers Data" def __str__(self): return self.surname class LectureForm(forms.ModelForm): lecture_title = forms.CharField(max_length=100, required=True) course = forms.ModelChoiceField(queryset=Course.objects.filter(pk=Teacher.teacher_ID)) class Meta: model = Lecture fields = ('course', 'lecture_category', 'lecture_title', 'content') -
Django restframework, extra_kwargs not working
I have a custom user model. I have created an api for user registration. Following is my serializer. class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[ UniqueValidator(queryset=get_user_model().objects.all()) ] ) password = serializers.CharField(min_length=8) class Meta: model = get_user_model() fields = ('email', 'password') extra_kwargs = {'password': {'write_only': True}, } def create(self, validated_data): email = validated_data.pop('email') password = validated_data.pop('password') user = get_user_model().objects.create_user(email, password, **validated_data) return user Here is my view: class Registration(generics.CreateAPIView): serializer_class = UserSerializer queryset = get_user_model().objects.all() There are two inputs email and password. password field is given as write_only field. But after creating the user, the api returns the hashed password. How can I prevent the password being returned? -
Widget used in forms is not appearing on web page. Django 1.11.5
So I have forms.py extensions/forms.py from django import forms from .models import SipExtension from xmpp.models import xmpp_buddy_groups class ExtensionForm(forms.ModelForm): xmpp_buddy_groups_choices = xmpp_buddy_groups.objects.values_list('group_name',flat=True) # xmpp_buddy_groups_names = forms.ModelMultipleChoiceField(queryset=xmpp_buddy_groups_choices,widget=forms.CheckboxSelectMultiple,required=False) class Meta: model = SipExtension fields = '__all__' widgets = { 'xmpp_buddy_groups_names': forms.CheckboxSelectMultiple } My model for extension app and xmpp app are below: extensions/model.py class SipExtension(models.Model): sip_extension = models.PositiveIntegerField(unique=True) sip_secret = models.CharField(max_length=32) commlink_push = models.BooleanField(default=False) real_name = models.CharField(max_length=32,unique=True) xmpp = models.BooleanField(default= False) xmpp_username = models.CharField(max_length=50,default='username') xmpp_password = models.CharField(max_length=32,default='password') xmpp_buddy_groups_names = models.ManyToManyField('xmpp.xmpp_buddy_groups',blank=True) def __str__(self): return '%s : %s' % (self.sip_extension, self.real_name) xmpp/models.pyclass xmpp_buddy_groups(models.Model): group_name = models.CharField(max_length=30) def str(self): return '%s' % (self.group_name) I want checkboxes in my gut as written in extensions/forms.py But what I am getting is below: -
My custom RegisterSerializer doesn't work with django-rest-auth
I'm using django-rest-auth and I want to add registration with my own User model. So I add allauth and create my own RegisterSerializer as it was mentioned in docs. serializers.py class RegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True) def validate_email(self, email): email = get_adapter().clean_email(email) if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password(self, password): return get_adapter().clean_password(password) def get_cleaned_data(self): return { 'password': self.validated_data.get('password', ''), 'email': self.validated_data.get('email', '') } def save(self, request): user = get_user_model() cleaned_data = self.get_cleaned_data() user.create_user(**cleaned_data) return user settings.py REST_AUTH_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.RegisterSerializer', } AUTH_USER_MODEL = 'users.User' Unfortunately django-allauth still uses the default serializer -
displaying the pdf file in django
Hi I am new to django framework when the user click i need to display the pdf file the code i am using is with open(file_path+file_name, 'rb') as pdf: response = HttpResponse(pdf.read(), mimetype='application/pdf',contenttype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' error i am getting is File "/usr/local/lib/python3.4/dist-packages/rest_framework/viewsets.py", line 90, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py", line 489, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "/home/tritwdapp/tribalwelfare/inspection/inspectdataview.py", line 290, in getSubmitReport response = HttpResponse(pdf.read(), mimetype='application/pdf',contenttype='application/pdf') File "/usr/local/lib/python3.4/dist-packages/django/http/response.py", line 283, in init super(HttpResponse, self).init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'contenttype' can any one please help me -
How do I convert a SQL query function into a django queryset
I have the following sample query from a .sql file how,do I convert it into a django queryset: Just a sample query set will do. CREATE OR REPLACE FUNCTION getAdjustment(int, int, int) RETURNS float AS $$ DECLARE adjustment float; BEGIN IF ($3 = 1) THEN SELECT SUM(exchange_rate * amount) INTO adjustment FROM Employee_Adjustments WHERE (Employee_Month_ID = $1) AND (adjustment_type = $2); ELSIF ($3 = 2) THEN SELECT SUM(exchange_rate * amount) INTO adjustment FROM Employee_Adjustments WHERE (Employee_Month_ID = $1) AND (adjustment_type = $2) AND (In_payroll = true) AND (Visible = true); ELSIF ($3 = 3) THEN SELECT SUM(exchange_rate * amount) INTO adjustment FROM Employee_Adjustments WHERE (Employee_Month_ID = $1) AND (adjustment_type = $2) AND (In_Tax = true); ........................... ; -
printing values without quotes in a nested dictionary
I used json.loads(jsonfile) to convert my json file to dictionary. The output is as below: {'id': '2', 'city': 'x', 'country': 'Y', 'phone': 'z', 'open': [{'weekday': 'Mon-Sun', 'open': '00:00', 'close': '24:00'}], } But while printing the nested values, say for 'open', it prints as [{'weekday': 'Mon-Sun', 'open': '00:00', 'close': '24:00'}] I tried using isinstance() to correct it, but it doesn't work either -
Depolying old Django project to new host
I have Django 1.6 project and is run using the Gunicorn web application server behind the Nginx web server. Now i want to transfer that project to new host. For that i have copied all code across the new machine and install all required dependencies using pip install -r requirements.txt that went successful. But after that if i am trying to do either of below python manage.py migrate or python manage.py runserver 0.0.0.0:8000 itt gives below error: Unhandled exception in thread started by <function wrapper at 0x7f9a114e1938> Traceback (most recent call last): File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper fn(*args, **kwargs) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 102, in inner_run self.validate(display_num_errors=True) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate num_errors = get_validation_errors(s, app) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors self._populate() File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate self.load_app(app_name, True) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app models = import_module('%s.models' % app_name) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module __import__(name) File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/__init__.py", line 2, in <module> from filer.models.clipboardmodels import * File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/clipboardmodels.py", line 7, in <module> from filer.models import filemodels File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/filemodels.py", line 13, in <module> from polymorphic import PolymorphicModel, PolymorphicManager File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/polymorphic/__init__.py", line 13, in <module> _version_ = … -
Django rest framework how toupdate nested user & user profile?
I've a problem, I'm developing a API with Django & DRF (I'm newbie, 'm learning), so my problem is when I try to update my user (default user from django) and the user profile nested with user, I'm using for authentication "djangorestframework-jwt" and "Django-rest-auth", my users are created correctly with a email confirmation but, I've no idea how to update them, only owner user have permission for updated his owner profile but idk how to do this.... models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) matricula = models.CharField(max_length=13, blank=True, null=True) birth_day = models.DateField(blank=True, null=True) etc..... ...... serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', ) class ProfileSerializer(serializer.ModelSerialzer): user = UserSerializer() class Meta: model = Profile fields = ('matricula', 'birth_day', 'etc....') """ this part is extra was trying this """ def update(self, instance, validated_date): user = validated_data.get('user') instance.user.username = user.get('username') instance.user.first_name = user.get('first_name') instance.user.last_name = user.get('last_name') ..... ..... instance.user.save() return instance Here comes a part of my problem "views", before coming and asking I searched and informed myself about this and saw that many people with problems similar to mine use the method "POST" to update and not the method "PUT" not Whatever … -
Lists in django: show a certain tag after 3 items
I'm using Django and I'm trying to generate Bootstrap rows and columns to display records from a database. After every three records, a new row should be added. So if I have 9 records, this is the code that should display: <div class="row"> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> </div> <div class="row"> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> </div> <div class="row"> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> </div> Right now I have this code: <div class="row"> {% for info in list %} <div class="col-lg-4">{{ info.title }}"></div> {% endfor %} </div> This generates: <div class="row"> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> <div class="col-lg-4">item</div> </div> How do I make the extra row tags appear after every 3 records? -
Django PasswordChangeForm wont load widget attributes
I am trying to make a "Change Password"-page by using the PasswortChangeForm (with old_password, new_password1, new_password2. The function itself works perfectly, but it will not load any widget attribute. I did the same thing with the RegistrationForm (to create a user) and it worked fine. forms.py class PasswordChangeForm(SetPasswordForm): old_password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', 'autofocus': 'autofocus', } ) ) new_password1 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) new_password2 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) class Meta: model = User fields = ( 'old_password', 'new_password1', 'new_password2', ) def clean_old_password(self): old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect('accounts:change_password_done') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) change_password.html {% load widget_tweaks %} <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <table style="margin-bottom: 1.5em;"> <tr><td><label for="{{ form.old_password.id_for_label }}">Altes Passwort*</label></tr></td> <tr><td><field>{{ form.old_password }}</field></tr></td> <tr><td><label style="margin-top: 1.5em;" for="{{ form.new_password1.id_for_label }}">Neues Passwort*</label></tr></td> <tr><td><field>{{ form.new_password1 }}</field></tr></td> <tr><td><label style="margin-top: 1.5em;" for="{{ form.new_password2.id_for_label }}">Neues Passwort bestätigen*</label></tr></td> <tr><td><field>{{ form.new_password2 }}</field></tr></td> </table> <button class="btn btn-success btn-sm" … -
(1048, "Column 'offer_id' cannot be null") django
I have a problem that I can not solve. Even with data, I always get this error (1048, "Column 'offer_id' cannot be null". Here are my codes: views.py from django.shortcuts import render, get_object_or_404 from .models import * from .forms import * from django.http import Http404 def save_data(request): form = ApplicationForm(request.POST or None, request.FILES) application = Application() if form.is_valid(): application.name = form.cleaned_data['name'] application.firstname = form.cleaned_data['firstname'] application.mail = form.cleaned_data['mail'] application.phone = form.cleaned_data['phone'] application.message = form.cleaned_data['message'] application.cv = form.cleaned_data['cv'] application.cover = form.cleaned_data['cover'] application.offer_id = form.cleaned_data['offer'] return render(request, 'oki.html', {'form':form, 'sauvegarde':application.save()}) Can I have a help please? -
"get() got an unexpected keyword argument 'pk'" in Django
I'm receiving TypeError at /wa-opinion/1/ get() got an unexpected keyword argument 'pk' as an error when running WaOpinion.objects.get(pk=kwargs['pk']) When printing the objects' keys like so print([x.pk for x in WaOpinion.objects.all()]) above, there are objects running with 'pk's from 0 to 9. And the debug information from Django about the kwargs argument contains an integer argument. -
Does django-el-pagination query objects again on page changing?
I use django-el-pagination on 9k+ documents, page loads slowly on both opening site and loading more. (I query data not only from database.) Is there any way to make it faster? class IndexView(AjaxListView): template_name = 'news/index.html' context_object_name = 'news_list' page_template = 'news/news_list_page.html' def get_queryset(self): <--My code to get objects--> return <objects> -
Common JSON Format for Django Rest Framework responses for Android client
I am developing the rest apis for an android app using Djnago Rest Framework. The android guys told me that it would be nice if I could provide the responses in a common format, like { “Status”:””, “Message”:””, “Data”:[] } Guys, is it the right approach? If so, how to achieve this? My assumption is that using a middleware would be an option. Thanks in advance. -
Django model form validation across full form
I'm using django model forms in my app. Anyway it does not seem validating the values for choice fields as shown below. **models.py** class Customer(models.Model): PASSPORT = 'PP' NIC = 'NIC' DLIC = 'DLIC' NA = 'NA' CHOICE_CUSTOMER_ID_PROOF = ( (PASSPORT, 'Passport'), (NIC, 'NIC'), (DLIC, 'Driving License'), (NA, 'Not Available'), ) id_proof_type = models.CharField(max_length=4, choices=CHOICE_CUSTOMER_ID_PROOF, default=PASSPORT, verbose_name='Identity') id_no = models.CharField(max_length=20, verbose_name='ID No.', blank=True) **forms.py** class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = '__all__' def clean(self): if (self.cleaned_data['id_proof_type'] != 'NA') and (self.cleaned_data['id_no'] == ''): raise ValidationError('ID number not provided.') I don't get any validation error when I select value not NA. Can anyone help on this? -
Heroku app global variable error
I am trying to get pagination to work, the following code works locally but not in heroku, sometime on page 2 or 5 I get : Exception Type: NameError Exception Value: name 'd' is not defined It sometimes goes away if I refresh the page. class AdvancedSearch(ListView): template_name= 'saferdb/AdvancedQuery.html' global e def get(self, request): global e if request.GET.get('page'): #passes original search params and request of next page return paginated_search_results(request, e) form = QueryForm() return render(request, self.template_name , {'form': form}) def post(self, request): global e #post request are only used for new searches #so if its a new search clear out d e = None e = request.POST.getlist('opeclass') return paginated_search_results(request, e) -
Can't sync django database and elasticsearch using django-elasticsearch-dsl-drf
I'm building a rest api with django rest framework. Now I want to connect my django database and elasticsearch to perform some operation. I decided to use django-elasticsearch-dsl-drf which I think is interesting. I was able to do their example project correctly. I filled the database and I made everything work, but when doing : http://localhost:8000/search/books/ http://localhost:8001/search/books/?ids=54|55|56 http://localhost:8001/search/books/?summary__contains=photography http://localhost:8001/search/books/?tags__contains=ython http://localhost:8001/search/books/?state=published http://localhost:8001/search/books/?pages__gt=10&pages__lt=30 the elasticsearch documents contain nothing from database, in fact they're empty. And I don't know why, while I've performed: ./manage.py search_index --create -f and ./manage.py search_index --populate -f Here is my python stack : Django==2.0.1 django-elasticsearch-dsl==0.4.4 django-elasticsearch-dsl-drf==0.6.3 django-nine==0.1.13 django-ormex==0.2 django-rest-elasticsearch==0.3.4 djangorestframework==3.7.7 drf-extensions==0.3.1 elasticsearch==5.5.2 elasticsearch-dsl==5.4.0 factory-boy==2.10.0 Faker==0.8.11 ipaddress==1.0.19 Pillow==5.0.0 psycopg2==2.7.3.2 python-dateutil==2.6.1 pytz==2017.3 PyYAML==3.12 six==1.11.0 text-unidecode==1.1 urllib3==1.22 I used a ubuntu 16.0.4 virtualenv with elasticsearch 5.5.3 Thanks for your help -
Django unable to migrate
I'm trying to work on a Django project, and I'm trying to migrate the tables over using the python migrate.py migrate command. However, it doesn't work, and I'm getting this error message. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 223, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/core/management/sql.py", line 51, in emit_post_migrate_signal **kwargs File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send for receiver in self._live_receivers(sender) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp> for receiver in self._live_receivers(sender) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/contrib/auth/management/__init__.py", line 59, in create_permissions ctype = ContentType.objects.db_manager(using).get_for_model(klass) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 51, in get_for_model ct = self.get(app_label=opts.app_label, model=opts.model_name) File "/Users/ifly6/Documents/Dropbox/Developer/PycharmProjects/infoeurope/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: get() got an unexpected keyword argument 'app_label' I've tried searching elsewhere, but it doesn't seem that I can find anyone else with a TypeError or something of this sort. -
Django Rest Serializer: Use nested serializer on GET but not POST
The problem is as follows: In the code below I have a PreguntaSerializer. As it is coded now if I post a JSON like this: { "categoria_pregunta": 1, "titulo": "Pregunta de Prueba", "descripcion": "Esta es la pregunta que mando por Postman", "persons": [1, 3, 5, 3050] } everything works, but when I retrieve the data I get categoria_pregunta and persons the same way I have posted them (as int and array respectively). I would like to be able to get those fields using Categoria_preguntaSerializer and PersonForPreguntaSerializer, but if I change categoria_pregunta and persons in PreguntaSerializer for their respectives serializers, I get errors when posting the before mentioned JSON. Is there a way I can use the same PreguntaSerializer for both actions or should I separate my views for GET and POST and use different serializers? models.py class Categoria_pregunta(models.Model): nombre = models.CharField( 'Descripcion', null=True, blank=True, max_length=150, default='') status = models.IntegerField( 'Estado', null=True, blank=True, choices=STATUS_CHOICES) class Pregunta(models.Model): titulo = models.CharField(max_length=200, null=False, blank=False, default='') descripcion = models.TextField(null=False, blank=False) categoria_pregunta = models.ForeignKey( Categoria_pregunta, null=True, blank=False, max_length=20) usuario = models.ForeignKey(User, null=True, blank=False, max_length=20) persons = models.ManyToManyField(Person, blank=False, max_length=20) class Person(models.Model): name = models.CharField('Nombre', null=True, blank=False, max_length=1000, default='') lastname = models.CharField( 'Apellido', null=True, blank=False, max_length=1000, default='') … -
how can i use SQL subquery with django orm
i want do this query for get recent avg data with django orm select product_name, AVG(price) as avg_price from ( select procuct_name, price, deal_date from deal_history order by deal_date desc ) R so, i tried this orm DealHistory.objects.all().order_by('-deal_date')\ .values('product_name').annotate(avg_price=Avg('price')) but this django-orm return below SQL query select product_name, deal_date, avg(price) as avg_price from deal_history order by deal_date desc group by product_name, deal_date how can i do i want -
Django: avoiding race condition during aggregation (SUM)
I have these following models, even though I used select_for_update in the aggregation, I'm still encountering race condition in this withdraw method : How do I lock the entries until withdraw() method finished? class BalanceHandler(): def withdraw(account, amount): # race condition happened here where multiple withdrawals happenning concurrently # can't use entries.select_for_update().get_total() because it's not available for QuerySet if account.entries.get_total() < amount: raise Exception("not enough balance") # do something with the amount class LedgerEntry(models.Model): amount = models.DecimalField(max_digits=18, decimal_places=6) ledger_account = models.ForeignKey(LedgerAccount, related_name='entries') class LedgerEntryManager(models.Manager): def get_total(account, *args, **kwargs): return self.select_for_update().filter(*args, **kwargs).aggregate(Sum('amount'))['amount__sum'] class LedgerAccount(models.Model): account_number = models.CharField(max_length=20, editable=False) -
Django/Wagtail psycopg2 error Expected in: flat namespace
I finished my website, and about to deploy it. I was following this guide to deploy my Django/wagtail site https://wagtail.io/blog/wagtail-heroku-2017/ . I was following along until the Using Postgres section. I did exactly what the article said, but I got an error when I try to createdb project_title_db Referenced from: /Users/jerrylee/Desktop/my_site/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so Expected in: flat namespace If you know how to solve this, please help me out. Much appreciated.