Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to understand inline_formset
Someone know how to do like this image on django. I want to create project like it but I don't know what should I do even if I have learn all tutorial on django. please see this image1 and it this is the last image I'm sorry Stackoverflow tell me that I'm no allowed to post image so that the reason why all image is in link. -
How to save FileField with None in Django
I have an issue hope your guy help. I have model Profile with Avatar field use FileField. class Profile(models.Model): avatar = models.FileField("Uploaded avatar of profile", storage=OverwriteStorage(), upload_to=avatar_photo_upload, null=True, blank=True) I write function to remove avatar, which set avatar = None def remove_avatar(self, request): profile = Profile.objects.get(user=request.user) profile.avatar = None profile.avatar.save() return Response({ 'status': 'ok', 'message': 'Avatar successfully removed' }, status=status.HTTP_200_OK) In my database, avatar stored as '', not null. Why and how can I fix it? -
How to update two models with one form?
I want to be able to have a user update two models with one submit button. The first model will house all of the book titles (unique) and pages that users submit. The other will show which users submitted which books. Ideally, I'd like to do something like this: if request.method == "POST": form = AddBookForm(request.POST) if form.is_valid(): books = form.save(commit=False) ub = UserBooks() books.book_title = form.cleaned_data['book_title'] books.book_total_pages = form.cleaned_data['book_total_pages'] ub.user = request.user ub.book_title = form.cleaned_data['book_title'] ub.save() books.save() return redirect('new_book') But that's giving me the error: Cannot assign "'Some Book Title'": "UserBooks.book_title" must be a "Books" instance. What would be the best way to update two models with one form? Here are the other files. models.py class Books(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) book_title = models.CharField(max_length=100, unique=True) book_total_pages = models.IntegerField() class Meta: ordering = ('-created',) def __str__(self): return '{0}'.format(self.book_title) class UserBooks(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) book_title = models.ForeignKey(Books, on_delete=models.CASCADE, null=False, blank=False) views.py def new_book(request): user = request.user if request.method == "POST": form = AddBookForm(request.POST) if form.is_valid(): books = form.save(commit=False) books.book_title = form.cleaned_data['book_title'] books.book_total_pages = form.cleaned_data['book_total_pages'] books.save() return redirect('new_book') else: form = AddBookForm() return render(request, 'main/addanewbook.html', { 'form': form, 'allBooks': allBooks, 'userbooks': userbooks, }) forms.py class … -
Solution To create or update static pages in Django
How can I create interface or solution to the website owner to be able to create or update static pages in Django without open source code, for example, a website owner needs to update text in aboutus page or want to create a new static page like new promotion details. -
Django: How to join tables based on a lookup tables' value
I am trying to do what one might consider an advanced sql query and would like to know if its possible in Django without resorting to raw sql (I will if its necessary). I want to join 1 or another table based on a value located in a table lookup table and would like to do this entirely in python/django. The following are rough examples of the models I am using: class SpecificProduct(models.Model): specific_product_id = models.AutoField(primary_key=True) a_field = models.TextField() something_specific_to_this_model = models.CharField() class GeneralProduct(models.Model): other_product_id = models.AutoField(primary_key=True) text = models.TextField() TABLE_CATEGORIES = { 1 : SpecificProduct, 2 : GeneralProduct, } class ProductCategory(models.Model): category_id = models.AutoField(primary_key=True) table_category = models.IntegerField() # Technically represents a table. category_text = models.CharField(max_length=20) class Inventory(models.Model): inventory_id = models.AutoField(primary_key=True) product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) product_pk = models.IntegerField() # Technically foreign key to a product table. quantity = models.IntegerField() What I want is a method like: def get_product(category_id, product_pk): # SQL query magic return one_object_of_a_specific_product_type This method should be able to do things like... Give me the product (model) where the product_category = 1 and the product_pk = 1. (returns a SpecificProduct model) Give me the product where product_category = 2 and the product_pk = 50 (returns a GeneralProduct model) … -
Django translate refers to wrong URL
I am using Django (version 2.1.3) in one of my project and currently struggle with a weird bug. I use the build in internationalization module and included a language toggler in my main menu which is loaded on every page {% get_current_language as LANGUAGE_CODE %} <form id="form" action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path|strip_lang }}" /> <input id="form_lang" name="language" type="hidden" value="{{ LANGUAGE_CODE }}"/> </form> <ul role="menu" class="dropdown-menu"id="lang-dropdown"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <li> <a href="#" onClick='(function(){ document.getElementById("form_lang").value = "{{ language.code }}"; document.getElementById("form").submit(); return false;})();return false;'> {{ language.name_local }} ({{ language.code }})</a> </li> {% endfor %} </ul> I created a special tag "strip_lang" to strip the language identifier from the current URL. @register.filter @stringfilter def strip_lang(value): """Removes all values of arg from the given string""" lang = getattr(settings, "LANGUAGES", None) url = value.split('/') if url[1] in [l[0] for l in lang]: return urllib.parse.unquote('/' + '/'.join(value.split('/')[2:])) else: return urllib.parse.unquote(value) This all works well. However, for one of my apps, I always get rerouted to a different app. ie if I am at path /en/app1/mypage1 and toggle the language i suddenly end up at … -
django tenant schemas and django test without migrations
How could use these two applications? django-tenant-schemas django-test-without-migrations -
phantom "ń" in django admin
I'm getting a unicode error in django admin for a character not present -- ń -- and am at a lost for how to fix the issue. Its not an issue of "str" or "unicode". Some models work perfectly fine with the same code and others don't. I haven't changed my code and it had been working fine for months. Suddenly, I'm getting this error today. It appears to be an issue in the django forms. Here is the error below for you to review Exception raised while rendering {% include %} for template 'admin/change_form.html'. Empty string rendered instead. Traceback (most recent call last): File "/home///local/lib/python2.7/site-packages/django/template/loader_tags.py", line 216, in render return template.render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 209, in render return self._render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home///local/lib/python2.7/site-packages/django/template/defaulttags.py", line 216, in render nodelist.append(node.render_annotated(context)) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home///local/lib/python2.7/site-packages/django/template/defaulttags.py", line 216, in render nodelist.append(node.render_annotated(context)) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home///local/lib/python2.7/site-packages/django/template/defaulttags.py", line 322, in render return nodelist.render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) … -
Django psycopg2 Permission Denied error when serving via wsgi/Apache
The problem: I have a Django 2.1.3 application living at /var/www/webapps/my-app that works just fine when started on the server like so: nohup ./manage.py runserver localhost:8080 & (from within my app directory and after activating my virtualenv) I'm now trying--and failing--to serve it with CentOS/Apache v2.4.6 via wsgi The error I get (/var/log/httpd/error_log) when attempting to load any page is: [wsgi:error] mod_wsgi (pid=3455): Failed to exec Python script file '/var/www/webapps/my-app/pit/wsgi.py'. [wsgi:error] mod_wsgi (pid=3455): Exception occurred processing WSGI script '/var/www/webapps/my-app/pit/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/var/www/webapps/my-app/venv/lib64/python3.6/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> [wsgi:error] import psycopg2 as Database [wsgi:error] File "/var/www/webapps/my-app/venv/lib64/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module> [wsgi:error] from psycopg2._psycopg import ( # noqa [wsgi:error] ImportError: /var/www/webapps/my-app/venv/lib64/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object: Permission denied Things I've checked or tried: all files in my web app directory and my venv directory belong to devop/devop verified that user 'apache' belongs to group 'devop' have tried loosening permissions chmod 777 _psycopg.cpython-36m-x86_64-linux-gnu.so have restarted apache, of course have tried pip install-ing various flavors of psycopg2 (binary, non-binary) semanage fcontext -a -t httpd_sys_script_exec_t /var/www/webapps/my-app/venv/lib64/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/webapps/my-app(/.*)?' restorecon -R -v /var/www/webapps/wwami-pit have added directives to /etc/httpd/conf.d/my-app.conf, such as: <Directory /var/www/webapps/my-app/venv/lib64/python3.6/site-packages> Require all granted … -
AttributeError - 'NoneType' object has no attribute 'username' - django
I am using django-excel to upload the data - filefield The error is AttributeError - 'NoneType' object has no attribute 'username' and the username field in blank Model - class samples(models.Model): transaction_Gldescription = models.CharField(max_length=30) transaction_GlCode = models.CharField(max_length=15) username = models.ForeignKey(User, on_delete=models.CASCADE, null=True) View - def import_data(request): if request.method == "POST": form = SamplesForm(request.POST,request.FILES or None) if form.is_valid(): instance= request.FILES['samplesfile'].save_book_to_database( models=[samples], initializers=[None], mapdicts=[ ['transaction_Gldescription', 'transaction_GlCode']]) instance.username= request.user instance.save(commit=True) return redirect('question_list') else: return HttpResponseBadRequest() else: form = SamplesForm() return render( request, 'upload_form.html', { 'form': form, 'title': 'Import excel data into database example', 'header': 'Please upload sample-data as per the format' }) Form - class SamplesForm(forms.Form): samplesfile = forms.FileField( label = 'Upload samples as per the format' ) -
pass the selected option from one form to another in the same html page using Django for backend
I have tow forms. I want to pass selected option from the first form to the other form as a hidden input. How can I do that. I tried the following solution but did not work. <form id="headerform" method="GET" action="{% url 'some url' %}"> {% if all_p_cities %} <select id='pre_sel_city' name="h_qc" onchange="headerform.submit()"> {% for city in all_p_cities %} {% if city.city_name == post_city %} <option value="{{city.city_name}}" selected > {{post_city}} </option> {% else %} <option value="{{city.city_name}}"> {{city.city_name}} </option> {% endif %} {% endfor %} </select> {% else %} <select id='pre_sel_city' name="h_qc" onchange="headerform.submit()"> <option value="{{post_city}}" selected > {{post_city}} </option> </select> {% endif %} </form> the second form is as follow: <form id='query-box'> <!-- predetermined search fields --> <input id='sel_city' type="hidden" name="h_qc" value=''> <input type="text"> <button type="submit"> </form> I used the javascript to pass the value of first form to the other form: <script type="text/javascript"> //get the input elements from HTML DOM for preselected input from the main search to customized header search var sel_city = document.getElementById("sel_city"); var pre_sel_city = document.getElementById("pre_sel_city"); //Get the value of inputs from first form var pre_sel_city_value = pre_sel_city.value; //Assign the values of first form to the second pre_sel_city.value = pre_sel_city_value; </script> -
Why does nocaptcha recaptcha show incorrect error every time?
I integrated Django-nocaptcha-recaptcha with my site. It works on my development server, but when I push to Heroku it shows the error "Incorrect, please try again." No matter if the captcha is completed right or wrong it shows this error. My site key and secret key are config variables, and I've triple checked that they are correct. Anybody know what might be wrong? -
How to setup django logging to console
I know there is a very similar question. That one is six years old and the answer in that one doesn't help me. All I want is to know how to configure django so that it can log to the console. This are my settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } And in my view I have this: class Home(TemplateView): template_name = "inicio/magic_py.html" def get_context_data(self, **kwargs): logger = logging.getLogger("Home") logger.debug("home!!!!!!") print("home?") The console doesn't show the log.debug, it only shows the print. What am I missing? please help. I use django 1.10 -
Real time ranking and stats django
I am making a real time sports ranking application using django and Postgressql and my performance time seems to be alright as of one user. However, I use save signals to update related models entirely without any cache. I was wondering how I could maintain the real time ranking and updating aspect but take the load off of my server and database. I have looked into django-channels, PUSHER, and redis but am unsure of where to go. Any help is appreciated. -
Don't save this request http in database on django
Client: I send my post on django import requests payload = {'datax':['12', '15'], 'datay':['22', '23'], 'timestamp':['1', '2'], 'data':['20', '19'], 'timestamp1':['1', '2'], 'mission':['Mission01', 'Mission01']} r = requests.post("http://127.0.0.1:8000", data=payload) Server(Django): I receive http post from client and i save data on database. This my models models.py from django.db import models class Mission(models.Model): name = models.CharField(max_length=250) description = models.CharField(max_length=1000) type = models.CharField(max_length=500) date = models.DateField() def __str__(self): return self.name + '-' + self.description class SensorLog (models.Model): mission = models.ForeignKey(Mission, on_delete=models.CASCADE) data = models.CharField(max_length=50) timestamp = models.CharField(max_length=50) class PositionLog(models.Model): mission = models.ForeignKey(Mission, on_delete=models.CASCADE) datax = models.CharField(max_length=50) datay = models.CharField(max_length=50) timestamp = models.CharField(max_length=50) this my view view.py from django.shortcuts import render from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Mission, SensorLog, PositionLog @csrf_exempt def home(request): if request.method == 'POST': data = request.POST.getlist('datax') datass = request.POST.getlist('datay') timestampss = request.POST.getlist('timestamp') datas = request.POST.getlist('data') timestamps = request.POST.getlist('timestamp1') missions = request.POST.getlist('mission') for i in range(len(data)): mission = Mission.objects.get(name=missions[i]) post1 = PositionLog.objects.create(datax=data[i], datay=datass[i], timestamp=timestampss[i], mission=mission) post = SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission=mission) return HttpResponse() def index(request): all_mission = Mission.objects.all() context = {'all_mission': all_mission} return render(request, 'mission/index.html', context) def detail(request, mission_id): try: mission = Mission.objects.get(pk=mission_id) except Mission.DoesNotExist: raise Http404("Mission dose not exist") return render(request, 'mission/detail.html', {'mission': mission}) I receve … -
Telepot + Django. How to polling the messages from the bot correctly? Thread or ...?
How to properly run telepot.loop—>MessageLoop ? How to start it in background without django-views? How do you user it or give me some another way/best practice about polling messages from the bot correctly? -
django error: ModuleNotFoundError No module named 'siteerrors'
I'm getting this strange error in my logs. Instead of getting a stacktrace in my browser, I'm getting an internal server error. Is this an app I need to install in my settings? -
how to resolve UnicodeEncodeError on django admin form
I ran into an unexpected unicode error on admin with production for some models on the object detail page. My local admin page works fine for all of the object pages. Production works for some and this error is thrown for others. It's not an error of str(self) since that error would be present on the object list page, not the detail. The curious thing is the unicode character --- u'\u0144' --- isn't even present. I'm not sure how to make sense of this error. Here are the details: Exception raised while rendering {% include %} for template 'admin/change_form.html'. Empty string rendered instead. Traceback (most recent call last): File "/home///local/lib/python2.7/site-packages/django/template/loader_tags.py", line 216, in render return template.render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 209, in render return self._render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home///local/lib/python2.7/site-packages/django/template/defaulttags.py", line 216, in render nodelist.append(node.render_annotated(context)) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home///local/lib/python2.7/site-packages/django/template/defaulttags.py", line 216, in render nodelist.append(node.render_annotated(context)) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home///local/lib/python2.7/site-packages/django/template/defaulttags.py", line 322, in render return nodelist.render(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home///local/lib/python2.7/site-packages/django/template/base.py", line 957, … -
Update instance for author in Django REST
I would like to update a instance of a model only if the request author is same than instance author. I guess can do it in the update method: def update(self, request, *args, **kwargs): if request.user == self.get_object().user How can I do it? Is it obligatory to write an update en every ModelViewSet or ListAPIView? or is there a method to write a custom permission to accomplish this. -
Django not parsing query string if the question mark is escaped
Shouldn't Django be able to parse an escaped query string like so: localhost:8000/sampleurl/myurl%3Fkey=value like it was this: localhost:8000/sampleurl/myrurl?key=value Instead I'm getting a 404. This is the URL: url(r'^sampleurl/(?P<slug>[-\w]+)/$', ... I was able to partially solve it by setting the url like so: url(r'^sampleurl(?P<slug>[-\w]+)(.*?)$', ... But doesn't work 100% and it seems unnecessary. -
Django Rest Framework POST fails: null value in column "cat_id" violates not-null constraint
I've recently converted my views to generic class-based views, however I've just noticed that POST requests fail on classes that have foreign-keys. The following is my code, followed by the error message. models.py class Category(models.Model): name = models.CharField(max_length=25, blank=False) class Meta: ordering = ('id',) class Task(models.Model): name = models.CharField(max_length=25, blank=False) cat = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: ordering = ('id',) serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'name', 'cat_id') class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') views.py class TaskList(generics.ListCreateAPIView): """ List all Tasks (OR for specified cat_id) """ queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('cat_id',) urls.py path('tasks/', views.TaskList.as_view()), Error returned django.db.utils.IntegrityError: null value in column "cat_id" violates not-null constraint DETAIL: Failing row contains (51, buy-some, null). REQUEST content: JSON Object { "name": "buy-some", "cat_id": 1 } Additionally, Content-Type, Accept headers are set to application/json. Category with id=1 exists -
Manual Template Setup of Django Formset Causes Validation Error
So I've been struggling with this for sometime now: The Context: I have a formset of relocation fees for various suburbs in a city. If a driver prefers to quote on request, he will leave the relocation fee for that suburb blank. When editing his relocation fees, a driver may also delete a fee if he wants to start quoting on request. Currently: I've gotten this to work using the formset's can_delete argument. However, when rendering the individual forms like so: <table> <th>Area</th><th>Relocation Fee</th><th>Remove</th> {% for relocation_form in relocation_form_set %} <tr> {{ relocation_form }}</td> </tr> {% endfor %} </table> The layout isn't ideal. The delete checkbox and its label seems to be created on a separate row of the table, when I want it in the same row as the suburb and relocation fee entry field which looks like this: Ideal Layout So, I can achieve this by laying out the form manually: <table> <th>Area</th><th>Relocation Fee</th><th>Remove</th> {% for relocation_form in relocation_form_set %} <tr><td>{{ relocation_form.price.label }}</td><td>{{ relocation_form.price }}</td><td>{{ relocation_form.DELETE }}</td></tr> {% endfor %} </table> However, this causes a new issue. In the first template code, empty formsets weren't required (which is what I want). With the new block, the formset is … -
Mixing and iterating list of tuples into a text template
I got a list and a list of tuples, each containing strings: names = ['joseph', 'parker', 'john'] interests = [('apples', 'design'),('bananas','economy'),('pears','medicine')] text_template = 'hi my name is {name}, i like {interests}, im studying {interests} everytime / ' I'm trying to achieve this: hi my name is joseph, i like apples, im studying design everytime / hi my name is joseph, i like bananas, im studying economy everytime / hi my name is joseph, i like pears, im studying medicine everytime hi my name is parker, i like apples, im studying design everytime / hi my name is parker, i like bananas, im studying economy everytime / hi my name is parker, i like pears, im studying medicine everytime hi my name is john, i like apples, im studying design everytime / hi my name is john, i like bananas, im studying economy everytime / hi my name is john, i like pears, im studying medicine everytime thanks, all!! -
store several images in the file system and all the references in the database
I use ImageField fields in my form and model to upload images, but I need to be multiple images and that just store one image and one reference in de database, this is my code: #models.py class mymodel(models.Model): imgs = models.ImageField(upload_to='uploads/%Y/%m/') #forms.py class myform(forms.Form): imgs = forms.ImageField(widget=forms.ClearableFileInput(attrs={'id': 'file', 'accept': 'image/*', 'multiple': True})) #views.py def myview(request): if request.method == 'POST': form = myform(request.POST, request.FILES) if form.is_valid(): modelo = mymodel() modelo.imgs = form.cleaned_data.get('imgs') modelo.save() When I do that only store one image even if I select 5 and in the database just store the path of the image that is stored How can I store the 5 imagen on disk and in the database in one register store the references of the 5 images using something like ',' to separete sorry for my bad english, If you need more information please ask me -
Django 1.11. How to get date to update itself daily
I would like for the date to update itself daily. Here I named it today's date. It will later be used in subtraction to get the difference btwn today and a "book_before" date. Models.py class JoinedSafaris(models.Model): book_before=models.DateField(default=date.today) today_date=models.DateField(auto_now_add=True) def datediff(self): date1 = self.today_date date2 = self.book_before delta= date2 - date1 return delta.days