Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cloudinary multiple image upload in django?
I have an image upload defined as follows in my Django app with Cloudinary package, class Photo(models.Model): photo = CloudinaryField('image') I Would like to make this field upload mutliple images. How do I do this? -
Use Django with SSL in order to integrate PayPal
I want to use PayPal in a Django Project and in order to do this I need Django to work with TSL 1.2. Since I haven't worked with such encryption yet, I need advice on how to setup Django in a way that works with an https version that works with PayPal. I already have a working ssl certificate and was able to use django-sslserver to make Django work with https, but PayPal still does not work with it. Could someone give a hint were I should be looking into for this kind of thing? -
How can I add additional top level JSON fields using the ModelSerializer
I am using the ModelSerializer from the Django Rest Framework to create an API. The ModelSerializer works great for returning JSON lists of whatever I query the database for. But I need to have some additional fields at the root level of the JSON response. How can I bump the query result to another level and add custom fields at the root of the JSON object? This is what the API query returns: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "user": { "username": "myuser" }, "content": "Another tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/3/", "id": 3 }, { "user": { "username": "myuser" }, "content": "a tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/2/", "id": 2 } ] This is what I want: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "custom_field": "custom value", "result": [ { "user": { "username": "myuser" }, "content": "Another tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/3/", "id": 3 }, { "user": { "username": "myuser" }, "content": "a tweet", "timesince": "2 weeks, 3 days", "url": "/tweet/2/", "id": 2 } ] } serializer.py: from django.utils.timesince import timesince from rest_framework import serializers from tweets.models import Tweet from … -
How do I paginate for every slug?
I was wondering what is the right way to paginate items from a slug page. I tried something, but I can't seem to figure out how to properly pass Courses that belong to that Faculty and to paginate them by 1 course per page. Here is what I tried: def faculty_filter(request, faculty_slug): qr = get_object_or_404(Faculty, faculty_slug=faculty_slug) query_list = Course.objects.get(qr) query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.filter(faculty_slug=faculty_slug), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), } return render(request, 'courses/filters/faculty_filter.html', context) Note: Courses do not directly belong to a Faculty. I have four models bound by foreign keys in this order: Faculty > Department > StudyProgramme > Courses. -
html form and successfully message
hello i have a simple html form with select option choose. I want after form submit the user get successfully message like this <p>your request is complete</p> in the position of html form. and if user press refresh then html form come back in page. here the code : <form action="" method="POST"> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <br> <br> <input class="btn btn-primary btn-lg btn-block" type="submit"> </form> any idea ?I am stack now I know this method action="other.html" but I want to work in the some html page without create other html page. -
invalid literal for int() with base 10: 'edycja' Django
I have a little problem. I've create a app where I can added the new records and edit. And now in edit this problem appear. When I select from list the record to edit -> form loading me properly the filled fields with datas. But when I click on Edit button to update the datas, the Django return me a error: **invalid literal for int() with base 10: 'edycja'** I don't know exacly where is a problem. Maybe somebody could help me? Here is the part of my views.py @login_required def szczegoly_pracownik(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) return render(request, 'cudzoziemiec/szczegoly_pracownik.html', {'link_pracownik': link_pracownik}) @login_required def edycja_pracownika(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) if request.method == 'POST': edycja_pracownika = CudzoziemiecForm(request.POST, instance=link_pracownik) if edycja_pracownika.is_valid(): link_pracownik = edycja_pracownika.save(commit=False) link_pracownik.save() return render('szczegoly_pracownik', id=link_pracownik.id) else: edycja_pracownika = CudzoziemiecForm(request.user, instance=link_pracownik) return render(request, 'cudzoziemiec/edycja_pracownika.html', {'edycja_pracownika': edycja_pracownika}) And when I read the log the error is somewhere in def szczegoly_pracownik -
Constructing Django templates from strings within Python code
I'd like to test a custom filter I wrote in Django, label_with_classes. My basic approach is to instantiate a 'snippet' of my actual template using by instantiating a django.template.Template with a string, rendering it with some context, and asserting that the generated output is what I would expect. I would also like to be able to write tags, etc. on new lines like I do in the actual template. The problem is that when I do this, lots of whitespaces appear in the rendered output. Here is a test case so far: from ..templatetags.label_with_classes import label_with_classes from django.test import SimpleTestCase from django.template import Context, Template from ..forms.sessions import SessionForm class CustomFilterTest(SimpleTestCase): def test_1(self): form = SessionForm(data={}) template = Template("\ {% load label_with_classes %}\ {{ form.session_number|label_with_classes }}") context = Context({'form': form}) output = template.render(context) upon which I drop into the debugger using import ipdb; ipdb.set_trace(). Here I see that output has lots of leading whitespaces: ipdb> output ' <label class="invalid" for="id_session_number">Session number:</label>' It seems like this whitespace comes from me writing on new lines in the string in the Template() constructor. However, in the actual HTML whitespaces between HTML tags are ignored. Is there a way to 'write HTML within' Python … -
Suggesting compatability level based on min and max value
I am stuck with a somehow reasonable request from a client but harder to implement (and downvotes for sure :p). The application includes State, City, County etc. Each one has weather related information for a range of month. A typical model is now: class County(models.Model): min_temp=models.DecimalField() max_temp=models.DecimalField() class Person(models.Model): prefer_min_temp=models.DecimalField() prefer_max_temp=models.DecimalField() So basically, when a person choses a county, we want to tell him his comptabiity based on the min and max temperature he has declared he prefers on a scale of 0-30 (Weak),31-50 (Good), 51-70 (Fair), >71 (Excellent) E.g. prefere_min_temp=50, max=90 County: min_temp=30, max_temp=100 How do I go about handling this for temperatures that can vary significantly with low percentage of error, since it is an a recommendation? -
django views.py search query un sorts my dataframe
I'm having a unique problem with my Django program. I have a problem where I need to get user input, query the database and return the results to the screen. I have written a custom function: get_cust_info(first_name, last_name, middle_name, address, state, zip) that takes in those respective inputs, queries the database and returns a list of suggested names in the event the user has typed his name wrong. The function works, returning the 10 largest values (names are sorted by their score, higher the score, better the match). I tested this function in a conda python 3 environment and it works as it should. But, when I try this in django, for some reason, it unsorts the values. Not sure what is going on. In my views.py, i have: #views.py from django.shortcuts import render from .name_matching import get_cust_info # Create your views here. def search_form(request): return render(request,'search_form.html') def search(request): first_name = request.GET['fname'] middle_name = request.GET['mname'] last_name = request.GET['lname'] address = request.GET['address'] zip_code = request.GET['zip'] state = request.GET['state'] df = get_cust_info(firstName=first_name, middleName=middle_name, lastName=last_name, address=address, zip_code=zip_code, state=state) path = 'H:\\work\\projects\\scoville_name_match\\scovilleapp\\templates\\search_results.html' df = df.nlargest(10, ['score_first', 'score_second', 'score_third']) df.to_html(path) return render(request,'search_results.html') #urls.py from django.conf.urls import url from django.contrib import admin from scovilleapp import views … -
django The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
I'm deploying a Django application on heroku. In my settings module, I have configured to host static files like STATIC_ROOT = os.path.join(BASE_DIR, 'static_my_project') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_project') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root') and urls.py urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But on deployment to heroku, it gives error as SystemCheckError: System check identified some issues: ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting. -
How do I get elements from a Django Queryset starting from a specific position?
I have a queryset in a Python/Django project: articles = ArticlePage.objects.live().order_by('-date') If I wanted to get only the first 50 elements I'd do: articles[:50] But also I need to get elements from position 5, this is to ignore the first 4 elements. I was expecting it to have something like articles[5:][:50] but I can't seem to find anything like that in the docs. Is there any way to achieve this? -
django-channels webSocketBridge read data sent by consumers
I am having a simple setup with testing channels 2.0. I have a routed consumer with three methods: consumers.py from channels.generic.websocket import JsonWebsocketConsumer from datetime import datetime # class Feedback_001_Consumer(JsonWebsocketConsumer): def connect(self,text_data=None, bytes_data=None): self.accept() self.send_json("Connection for Feedback 1 ready.") # def receive(self,text_data=None): #self.accept() self.send_json("{}".format(datetime.now())) print(datetime.now()) # def disconnect(self,close_code): pass and my js looks like this: const webSocketBridge = new channels.WebSocketBridge(); #... webSocketBridge.connect('my_route/etc...'); #... console.log(webSocketBridge.send('')); While the datetime is printing in the console, I cannot get the one sent by self.send_json in the receive method of the consumer. What would be the proper way to do this? -
Django: form.is_valid() is always false
I'm just a beginner in Django and I am currently developing user login functionalities. I've come across a bug and I cannot find out what is wrong. I've read other questions and solutions from that topic, but those solutions do not apply to my problem. I tried them but they do not work. My problem: form.is_valid() is always false views.py def login_view(request): form = UserLoginForm(request.POST or None) print(request.user.is_authenticated) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) print("Works") print(request.user.is_authenticated) return render(request, "music/login.html", {'form': form}) forms.py User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exists") if user.check_password(password): raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("Tjis user is not longer active") return super(UserLoginForm, self).clean(*args, **kwargs) login.html <h3>Login</h3> <form class="form-horizontal" action="" method="POST" enctype="multipart/form-data"> {% include 'music/form-template.html' %} {% csrf_token %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> Thanks for help! -
django post method to get all value with same name
Hi i am trying to build a application using Django. I have a form under which i let the use to enter n number of input as they wish. but i am not able to retrieve the data as expected when the submit. Here is my view def sample(request): if request.method == 'POST' form_value = request.POST.copy() print form_value #This print statement print me <QueryDict: {u'csrfmiddlewaretoken': [u'gAxkEq1bVk5hQicPGmFo4DTIOxomOUdtaOiimW5Bel1kvFaYyECp5JzPqk4yzJe8'], u'userinput': [u'asddsaf', u'asfsadf', u'asfsdf', u'asfdsaf', u'asfasdf']}> print form_value['userinput'] # but this print statment print me only the last value asdfsaf my HTML <form action='.' method='post'> {% csrf_token %} <input type='text' name='userinput'> <input type='text' name='userinput'> <input type='text' name='userinput'> <input type='text' name='userinput'> <button type='submit'>Submit</button> </form> How can i get the list/array of input with the name 'userinput' -
In Django, how to filter a model using a list of values but each value can be used only once?
I'm new to Django. I have a Postgres database of details about movies. I want to display 10 movies on a page. I have 2 issues: Each movie must be from a different country. So far, I can only get a list of 10 random countries from a larger list. I don't know how to use .objects.filter() in a way that makes sure there are no repeated countries. Some movies are produced by more than one country, and they are contained as strings in the database, for instance 'Tajikistan,Papua New Guinea,Korea'. But the .objects.filter() function only returns movies with a single country in it. My current code in views.py: from .countries import countries # this is a Python list of countries class MoviesListView(generic.ListView): model = Movies def get_queryset(self): random_countries = [] i = 0 while i < 10: country_choice = random.choice(countries) if country_choice in random_countries: pass else: random_countries.append(country_choice) i += 1 for i in random_countries: print(i) print(len(random_countries)) return Movies.objects.filter(production_countries__in=random_countries)[:10] I've googled around and looked into the Django documentation but haven't been able to find solutions. What's the best way to do this? Must I connect to the database with psycopg2, use sql to get 10 movies that fit my criteria … -
How to edit form in Django
I'am trying to create a edit form in my project but my code do not working well. I can't find the error. Maybe somebody help me? My views.py is: @login_required def szczegoly_pracownik(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) return render(request, 'cudzoziemiec/szczegoly_pracownik.html', {'link_pracownik': link_pracownik}) @login_required def edycja_pracownika(request, id): link_pracownik = get_object_or_404(Cudzoziemiec, id=id) if request.method == 'POST': edycja_pracownika = CudzoziemiecForm(request.user, request.POST) if edycja_pracownika.is_valid(): link_pracownik = edycja_pracownika.save(commit=False) link_pracownik.save() return render('szczegoly_pracownik', id=link_pracownik.id) else: edycja_pracownika = Cudzoziemiec(request.user) return render(request, 'cudzoziemiec/edycja_pracownika.html', {'edycja_pracownika': edycja_pracownika}) the def szczegoly_pracownik is responible for getting the details from record When I click in html file on the button "Edit" the url works ok, because is redirecting me in to the edycja_pracownika.html , but in edycja_pracownika.html i see only the button, without forms. -
Form not showing up Django 1.8
I am making a project using python 3.5 and Django 1.8 ,there is a feature for login and signup, so login and signup are two different apps THIS image shows my directory structure of apps Now in login app's form , I import from signup.models allusers1 (a class in signup.models) Using view I pass the form but nothing is showing up ,but the submit button shows nothing else This is login/forms.py from django import forms from signup.models import allusers1 from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) User=get_user_model() class UserLoginForm(forms.Form): class Meta: model = allusers1 fields=['username','password'] widgets = { 'password': forms.PasswordInput(), } def clean(self ,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean(*args,**kwargs) This is signup/models.py from django.db import models from django import forms # Create your models here. class allusers1(models.Model): username=models.CharField(max_length=40) password=models.CharField(max_length=40) phoneno=models.CharField(max_length=10,primary_key=True) otp=models.IntegerField(blank=True,null=True,default=0000) def __str__(self): return self.username login/views.py def login(request): form1=UserLoginForm(request.POST or None) if form1.is_valid(): username=form1.cleaned_data.get("username") password=form1.cleaned_data.get("password") user=authenticate(username=username,password=password) auth_loginwa(request,user) print(request.user.is_authenticated()) return redirect("home2") context= { "form1": form1, } return render(request, "login.html",context) login.html <form action="" … -
Django - DROP and CREATE DB - No changes detected
I'm moving my project from Sqlite3 to MySQL database. I've connected new MySQL database to Django and run manage.py migrate. There were some errors but tables were created so I decided to DROP the database and recreate it. The problem is that even when I DROP the database DROP DATABASE mydb; And then create it CREATE DATABASE mydb; And deleted migrations Django's manage.py makemigrations says no changes detected which is very weird since it should track changes inside recreated database which is empty. Do you know what to do and why it behaves this way? mysql> DROP DATABASE keywords_search; Query OK, 13 rows affected (0,19 sec) mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 4 rows in set (0,00 sec) mysql> CREATE DATABASE keywords_search; Query OK, 1 row affected (0,00 sec) mysql> use keywords_search; Database changed mysql> show tables; Empty set (0,00 sec) mysql> -
DRF: creating new object in a model with 'ManyToMany' field and 'through' table
I have the following Django models: class Product(models.Model): name = models.CharField(max_length=250, unique=True) quantity = models.IntegerField(default=0) class Order(models.Model): products = models.ManyToManyField( Product, through='PositionInOrder' ) discount = models.CharField(max_length=50, blank=True) total_sum = models.DecimalField(max_digits=11, decimal_places=2, default=0) class PositionInOrder(models.Model): sale = models.ForeignKey(Order) product = models.ForeignKey(Product) quantity = models.PositiveIntegerField() price = models.PositiveIntegerField() And the following serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class PositionInOrderSerializer(serializers.HyperlinkedModelSerializer): sale = serializers.ReadOnlyField() product = serializers.ReadOnlyField() class Meta: model = PositionInOrder fields = "__all__" class OrderSerializer(serializers.ModelSerializer): products = PositionInOrderSerializer(many=True) def create(self, validated_data): products = validated_data.pop('products') order = Order.objects.create(**validated_data) return order class Meta: model = Order fields = '__all__' I want to create new Order. Send post query which contains this json: { "products": [{"id": 2606, "name": "Some name", "quantity": 140, "price": 250}], "discount": "15", "total_sum": 500 } And in the create() method of a class OrderSerialization I obtain that products=: [OrderedDict([('quantity', 140), ('price', 250)])] and there are no information about product_id and product_name. How can I get them? -
how to list files in digitalocean server with django?
I make cloud panel projects with django but i have a problem. i am click to manage button after this page show: https://s18.postimg.org/lj7qwc8p5/Ekran_G_r_nt_s_2018-02-21_19-22-33.png I make connect to paramiko. Paramiko is right work but this is not connect yet. so we will make first with connect paramiko after then, later on the directory make verification on server. This code piece is wrong: from django.shortcuts import render from explorer.models import Servers from django.http import HttpResponse import paramiko import logging import csv paramiko.util.log_to_file("filename.log") # Create your views here. def listfiles(path,ssh,server,sftp): cmd = "cd "+path lf = "ls -p | grep -v /" f = open('dumps/' + server + 'traverse.sh','w+') f.write('#!/bin/bash\n') f.close() f = open('dumps/'+ server + 'traverse.sh','a+') f.write(cmd + "\n") f.write(lf) f.close() sftp.put('dumps/' + server +'traverse.sh ','traverse.sh') ssh.exec_command("chmod 777 traverse.sh") stdin,stdout,stderr = ssh.exec_command("./traverse.sh") data = stdout.read() ssh.exec_command("rm -rf traverse.sh") return data.split() line 37 = lf = "ls -p | grep -v /" manage.py inside: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cloudpanel.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) How to be solution my problem? Do not look for my bad english. -
Dynamic get_absolute_url using url query parameters
Big picture: I'd like my reverse method in get_absolute_url (see below) to return a url with a query parameter appended to it at the end, e.g. <url>?foo=bar. Further, I'd like bar to be specified by the POST request that triggered the call to get_absolute_url, either as an input to the form (but not a field represented by the model, something temporary) or as a url query parameter. I am easily able to access bar in my view using either method, but I can't seem to figure out how to access it in my model. The motivation here is that my detail page splits up the fields from my model into different tabs using javascript (think https://www.w3schools.com/howto/howto_js_tabs.asp). When the user is updating the model, they choose which tab they want to update, and then the update template only renders the fields from the model which are related to that tab. More importantly, after the user submits the update, I want the detail page to know to open the specific tab that the user just edited. (I understand how this works if the field is a part of the model; in get_absolute_url with parameters, the solution is pretty straightforward and involves using … -
Why CRUD Operations Using Ajax and Json for Django powered app is so slow ?
I am performing operations on remote legacy MySQL database having about 7000 records.Currently, it's taking around 1.5 minutes for the Update / Delete / Create operation. Should I use Rest? OR some other some other API. Any suggestions will be appreciated! Here is the code: plugin.js $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-book').modal('show'); }, success: function(data){ $('#modal-book .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#book-table tbody').html(data.book_list); $('#modal-book').modal('hide'); } else { $('#modal-book .modal-content').html(data.html_form) } } }) return false; } // create $(".show-form").click(ShowForm); $("#modal-book").on("submit",".create-form",SaveForm); //update $('#book-table').on("click",".show-form-update",ShowForm); $('#modal-book').on("submit",".update-form",SaveForm) //delete $('#book-table').on("click",".show-form-delete",ShowForm); $('#modal-book').on("submit",".delete-form",SaveForm) }); Views.py @login_required() def book_list(request): books = AvailstaticCopy.objects.all().order_by('-row_date') page = request.GET.get('page', 1) paginator = Paginator(books, 144) try: books = paginator.page(page) except PageNotAnInteger: books = paginator.page(1) except EmptyPage: books = paginator.page(paginator.num_pages) context = { 'books': books } return render(request, 'books/book_list.html',context) @login_required() def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True books = AvailstaticCopy.objects.all() data['book_list'] = render_to_string('books/book_list_2.html', {'books':books}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) @login_required() def book_create(request): if request.method == 'POST': form … -
DRF How to serialize models inheritance ? (read/write)
I have some models class RootModel(models.Model): # Some fields class ElementModel(models.Model): root = models.ForeignKey(RootModel, related_name='elements', on_delete=models.CASCADE) class TextModel(ElementModel): text = models.TextField() class BooleanModel(ElementModel): value = models.BooleanField() a viewset class RootViewSet(viewsets.ModelViewSet): queryset = RootModel.objects.all() serializer_class = RootSerializer and serializers class TextSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() class Meta: model = TextModel fields = '__all__' def get_type(self, obj): return 'TEXT' class BooleanSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() class Meta: model = BooleanModel fields = '__all__' def get_type(self, obj): return 'BOOL' class RootSerializer(WritableNestedModelSerializer): elements = ... class Meta: model = RootModel fields = '__all__' WritableNestedModelSerializer comes from drf_writable_nested extension. I want to GET/POST/PUT a root containing all data example with GET (same data for POST/PUT) { elements: [ { type: "TEXT", text: "my awesome text" }, { type: "BOOL", value: true } ], ... root fields ... } What is the best way for elements field in RootSerializer ? I also want to have information with OPTIONS method Thanks -
Impossible to install gettext for windows 10
I have followed all the steps shared in all stackoverflow and other questions out there to install gettext for windows (10), but still, I get the error: "Can't find msguniq, make sure you have gettext tools installed" when using internationalization in django. I have tried to download the files directly and added them to the PATH, and even an installer that had already compiled everything and added to the path automatically, but it still doesn't work, and I don't know what else to do... Help please! Thank you for your time. -
Django - validate model before saving to DB
in Django 1.10 - I want to create multiple objects by importing. Before creating them I want to validate fields to make sure as much as I can that creation will pass successfully and collect as much data as I can about invalidate fields. For example, to find out whether a char field is too long. I can use 'if' statement for each field but it's not robust. I thought of using the model Serializer. The problem is that there are models to create that uses other models that also should be created. So when trying to validate the model that depends on the other one - it fails since it's not existed yet. For example: class FirstModel(BaseModel): title = models.CharField(max_length=200) identifier = models.CharField(max_length=15) class SecondModel(BaseModel): identifier = models.CharField(max_length=15) firstModel = models.ForeignKey(FirstModel, related_name='first_model') Any idea how to validate the data?