Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change charset for MySql
I am using MySql along with Django. I am trying to save an object containing an emoji. I have changed the charset for the table using the following commands ALTER DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE mydb.mytable CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; and when I use the command SHOW FULL COLUMNS FROM table_name; for seeing the columns I get the following output - Field: unit_text Type: longtext Collation: utf8mb4_unicode_ci Null: YES Key: Default: NULL Extra: Privileges: select,insert,update,references Comment: Here coalition is utf8mb4_unicode_ci but still, when I try to save the object I get this error - OperationalError "Incorrect string value" Please let me know what I should do -
ORA-00904: "IDENTITY_COLUMN": invalid identifier error using INSPECTDB DJANGO
I have an existing database in Oracle 11.2. I am trying to use inspectdb utility of django to automatically create the models but I am getting the error:- ORA-00904: "IDENTITY_COLUMN": invalid identifier There is no column named "IDENTITY_COLUMN' in any of the tables and since I am not directly accessing the database the chances of misspelling a column name or accessing a wrong column is not possible. It would be very helpful if someone can give a direction as to what to fix to solve this error. -
Hosting Media files when Django DEBUG = False
I'm getting a little issue in order to serve Media files in my webserver. My web application is in production mode, so I have to set DEBUG = false. This is my project : Astrophotographie | |_ Accueil |_ Articles |_ Astrophotographie |_ Astro_Database |_ manage.py |_ Media | |_ Media | |_ list of pictures |_ static |_ templates |_ virtualenv My settings.py file : Well, it's done and I know that Django can't host Media files like this, so I have Apache2 in order to do that. I configured Apache2, so all my website sounds like, but I don't overcome to display pictures. Apache2 config : Alias seems to be good right ? I miss something in my configuration in order to display pictures correctly ? This is what I get on my website : -
How to Django models filefield parametric storage?
My code: from django.db import models from private_storage.fields import PrivateFileField from private_storage.storage import private_storage from aratarikan_com.settings import public_storage class File(models.Model): published = models.BooleanField() @property def storage(self): if self.published == True: return public_storage elif self.published == False: return private_storage file = PrivateFileField(storage=storage) ValueError: Cannot serialize: There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/2.0/topics/migrations/#migration-serializing You must understand what I want to do. Does anyone have an idea? -
django error management form is missing or has been tampered with
hi i can't solve this error:ValidationError: [ManagementForm data is missing or has been tampered with'] please help me.I can not understand where the error is, i tried to remove 'formset1C_list' and 'formsetHC_list' but the error persist this is my view: def manage_score(request,pk): ScoreFormSetSR = formset_factory(ScoreForm,min_num=12,max_num=12) ScoreFormSetTTT = formset_factory(ScoreForm,min_num=12,max_num=12) ScoreFormSetGC = formset_factory(ScoreForm,min_num=12,max_num=12) ScoreFormSetPC = formset_factory(ScoreForm,min_num=6,max_num=6) ScoreFormSetGPM = formset_factory(ScoreForm,min_num=6,max_num=6) ScoreFormSetHC = formset_factory(ScoreForm,min_num=8,max_num=8) ScoreFormSet1C = formset_factory(ScoreForm,min_num=8,max_num=8) sr_formset = ScoreFormSetSR(request.POST, request.FILES, prefix='SR') ttt_formset = ScoreFormSetTTT(request.POST, request.FILES, prefix='TTT') gc_formset = ScoreFormSetGC(request.POST, request.FILES, prefix='GC') pc_formset = ScoreFormSetPC(request.POST, request.FILES, prefix='PC') gpm_formset = ScoreFormSetGPM(request.POST, request.FILES, prefix='GPM') stage = DailyStage.objects.get(pk=pk) formsetHC_list = [] formset1C_list = [] for n in range (stage.hc): formsetHC_list.append(ScoreFormSetHC) for k in range (stage.UNOc): formset1C_list.append(ScoreFormSet1C) if request.method == 'POST': if stage.tipo=='SR': return render(request, 'game/score.html', {'sr_formset': sr_formset, 'gc_formset': gc_formset, 'pc_formset': pc_formset, 'gpm_formset': gpm_formset, 'formset1C_list':formset1C_list, 'formsetHC_list':formsetHC_list}) if stage.tipo=='TTT': return render(request, 'game/score.html', {'ttt_formset': ttt_formset, 'gc_formset': gc_formset, 'pc_formset': pc_formset, 'gpm_formset': gpm_formset, 'formset1C_list':formset1C_list, 'formsetHC_list':formsetHC_list}) else: if stage.tipo=='SR': return render(request, 'game/score.html', {'sr_formset': sr_formset, 'gc_formset': gc_formset, 'pc_formset': pc_formset, 'gpm_formset': gpm_formset, 'formset1C_list':formset1C_list, 'formsetHC_list':formsetHC_list}) if stage.tipo=='TTT': return render(request, 'game/score.html', {'ttt_formset': ttt_formset, 'gc_formset': gc_formset, 'pc_formset': pc_formset, 'gpm_formset': gpm_formset, 'formset1C_list':formset1C_list, 'formsetHC_list':formsetHC_list}) this is my template: {% extends 'game/base.html'%} {% block content %} <h1>Score page</h1> <form method="POST" > {% csrf_token %} <div style="border-style: solid;width:50%;float:left;"> <h3>FORMSET HC LIST</h3> {% … -
Configuring Django App with Braintree
I am in the process of building a django application and was wondering how I could bring the braintree API into my application so my users can make payments. -
Making web app from Python scripts
I hope this is not too broad question and belongs here. I have made Python scripts that do several things. They get data from web and that data is used to draw things on top of Google Maps. Lastly html file is generated which opens in browser to view the results. I have successfully made this desktop application using Qt (pyqt5) where I control few inputs with drop down lists, numeric inputs etc. and have push button to generate the html file and open it. So now I am wondering what technologies should I use in order to make all this possible on web. I would probably need the possibility to log in and out to the service, some kind of dashboard to control inputs and then have the result html show in the same page at minimum. I have read a little about django and Flask. Am I cool further digging into them? Happy to hear some advice. -
Wagtail: Template tag with call to routablepageurl throwing AttributeError
I'm trying to build a simple blog in Wagtail, and trying to figure out how everything in it fits together and why things don't work is driving me up the wall. I keep getting AttributeError: 'str' object has no attribute 'relative_url' when I try to load an 'About' page, and I think it has to do with a navbar.html I'm bringing into base.html with an inclusion tag. I can't make sense of the error, can anyone help break it down? Navbar.html {% load static wagtailcore_tags blogapp_tags wagtailroutablepage_tags %} <div class="container" id="nav-container"> <nav class="navbar navbar-expand-sm py-0 px-0" id="main-nav"> <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <form role="search" method="get" class="form-inline pt-3 form-search" action="{% routablepageurl home_page 'post_search' %}"> <input type="text" name="q" id="search-bar" class="form-control mr-sm-2 search-query" type="search" placeholder="Search&hellip;" title="Search for:" aria-label="Search"> <button class="btn btn-outline-danger my-2 my-sm-0" name="submit" id="search-button" type="submit" value="Search">Search</button> </form> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mt-2 ml-auto"> <li class="nav-item"> <a href="/about" class="nav-link">About</a> </li> <li class="nav-item"> <a href="#" class="nav-link">Archive</a> </li> </ul> </div> </nav> </div> Models.py class HomePage(RoutablePageMixin, Page): description = models.CharField(max_length=255, blank=True, null=True) content_panels = Page.content_panels + [ FieldPanel('description', classname='full') ] def get_context(self, request, *args, **kwargs): context = super(HomePage, self).get_context(request, *args, **kwargs) context['posts'] = self.posts context['home_page'] = self context['search_type'] = getattr(self, 'search_type', '') … -
Django: Changing model attributes via shell creates an empty copy of said model, but doesn't change original
from app.models import Person person = Person.objects.get(name='Carl') person.name = 'John' person.save() Now, there is a new, empty Person entry in the database with the name John, but none of the other attributes that 'Carl' has (age, address, etc.). Furthermore, the original Carl object isn't changed at all. How can I just change what the person's name attribute is? -
Need optimize query using annotate
Have 2 models : MyItem and Category This works, but how do I do this with a single query using annotate: for cat in Category.objects.all(): cat.count = MyItem.objects.filter(category=cat).count() cat.save() Like some: Category.objects.annotate(_items_count=Count('myitem').update(count=_items_count) -
Django: Unable to login on site but on local server it works, not on site.
I have tried to check my code, but I can't find the solution or bug... On local server the site runs normally, login works. but I have installed it on A2 hosting server, and the site runs but I can't login, I have logged in with correct user and password. But it always returned to wrong page and I'm not logged in, the session id cookie is set... Can someone help me? here the code of my settings Django settings for signbank project. import os from signbank.settings.server_specific import * from datetime import datetime DEBUG = True PROJECT_DIR = os.path.dirname(BASE_DIR) MANAGERS = ADMINS TIME_ZONE = 'Europe/Amsterdam' LOCALE_PATHS = [BASE_DIR+'conf/locale'] SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = WRITABLE_FOLDER MEDIA_URL = URL+'/media/' MEDIA_MOBILE_URL = MEDIA_URL # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '/home/signbank/SB/static/' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = URL+'/files/static/' # Additional locations of static files STATICFILES_DIRS = ( os.path.join(STATIC_URL, "static"), ) # List of finder classes that know how to … -
Django - AJAX - Why do I need url parameter?
It's my first time using AJAX and I don't understand why I need to specify url parameter in a JS Ajax call. {% block javascript %} <script> $("#id_username").change(function () { $.ajax({ url: '/some_new_url/', data: { 'something': ... }, success: function (data) { if (data.is_taken) { alert("Data is already in DB"); } } }); }); </script> {% endblock %} To my understanding, AJAX is used to do something on the server side without refreshing a page. So it shouldn't redirect to a new url upon sending a data to the server, and stay on the same url. And yet AJAX call requires url parameter. And I don' really like this, because setting a new url means I have to add another url pattern in my app/urls.py. re_path(r'^create/$', views.Some_View.as_view(), name='create'), And as a consequence, make another view in my views.py class Some_View(ListView): model = SomeModel fields = '__all__' But, I already have a CBV that generates form fields on the user side and accepts user inputs. I only want to make my existing CBV to save data to DB using AJAX call. Since I don't understand what the purpose of the url is, I don't know how to set up my new … -
Django Form Dropdown List Not Show
I have listView that contain form, I do manual form like <input type="text" id="shift"> on my template.html here the listview on views.py class EmpShiftListView(ListView): context_object_name = 'empshifts' model = models.EmpShift here my models.py class Shift(models.Model): .... name = models.CharField(max_length=255) .... def __str__(self): return self.name class RShift(models.Model): .... shift = models.ForeignKey(Shift, null=True, on_delete=models.SET_NULL, related_name='rshifts_shift') employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='rshifts') .... def __str__(self): return self.name I know <input type="text" id="shift"> will show empty form. What I need is like image below. its dropdown and contain list of item from other model, but I don't want use forms.py I wan't to create it mannualy, but the content is from other model. -
Django: Create One-to-One instance on model creation
So I know I can use signals to automatically create a one-to-one related instance. (For example: Create OneToOne instance on model creation). My situation is that the related model contains a non-null, non-blank field. class Company(models.Model): name = models.CharField() class UserProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL ) company = models.ForeignKey( Company ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_user_profile( sender, instance, created, **kwargs ): if created: UserProfile.objects.create(user=instance) When a user is created, create_user_profile is triggered. But this causes an error Column company_id cannot be null. How do I pass company_id into the receiver? Would I need to create a custom manager in the User model? If so, would that just remove the need for signals since I can create UserProfile in the manager? -
BaseModelFormSet "metaclass conflict"
While following django docs I end up with this error : metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Only thing I change is passing an argument to filter the queryset. The doc shows an easier case. forms.py : class BaseEducationFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): id = kwargs.pop('curriculum_fk') super().__init__(*args, **kwargs) self.queryset = Education.objects.filter(curriculum__id=id) views.py : def cv_edit(request, pk): EducationFormSet = modelformset_factory(Education, fields = ('title', 'institution', 'place') , formset=BaseEducationFormSet(curriculum_fk=pk)) I though that "modelformset_factory" would handle this job... -
Django REST framework cannot encode object
I want to create Django REST framework API to get a list from a database,but always get 'cannot encode object' error: def getData(Input): try: IP='2.2.2.66' Port=27017 dbs=DbsRD.RData(IP,Port) out = dbs.getName(Input) station=out[2] #This is a list return Response(station) #Even if a string will get 'cannot encode' error except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) -
I'm getting an keyError in main while making project using django? i m not able to resolve this error
import requests from django.shortcuts import render from .models import City def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=bd5e378503939ddaee76f12ad7a97608' city = 'Jaipur' cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data' : city_weather} return render(request, 'weather/weather.html', context) -
Django-haystack (elastic search) boost field based on value?
I'm indexing a large list of products. In the simplified example below, I would like to boost all featured products that returns a value of "True" by 1.5. Is this possible? class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='/home/<path>/search/indexes/product_text.txt' ) title = indexes.CharField(model_attr='title') slug = indexes.CharField(model_attr='slug') featured = indexes.BooleanField(model_attr='featured') I'm using django-haystack 2.5.0 and elasticsearch 2.3.1. -
Django - Get the first and last names of an user
When a user is created, one can add the first and last name in the user's profile. My question is: how can I access this information? If I only wanted the username I would do it with user.get_username. How should I access first name and last name? -
Permission denied for image upload on Django rest wsgi with apache2
Main problem When user uploads image to the rest admin portal, permission error is thrown. The backend model is a simple one with only ImageField and TextField. My setup Ubuntu 16.04 LTS Python 3.6 Apache2 with mod_wgsi compiled for python3.6 The upload destination is owned by my account and wwwdatagroup(I created this group for www-data and grant 760 on the upload destination) Here is the output of ls -l This folder is under my home directory, the image is uploaded to a subfolder of media folder. drwxrw---- 3 MYUSERNAME wwwdatagroup 4096 Jul 30 17:48 media This was set by chmod -R 760 media I suppose this will set the permission recursively. Question My wsgi process has no specific user set, so it should run under the user which apache is running on. In my case www-data. As shown above, obviously this folder and all is subfolders can be read, written(rw) by wwwdatagroup which contains www-data. So WHY PERMISSION DENIED? -
Optimal Structure for Django App
I am building a music application with Django that I want to port to desktop and mobile. I was curious what the best folder hierarchy or structure would be if I want it to rival something like Splice.com. Also, is it smart/possible to integrate the django app with some go and node js as well as apache web server and postgres database. Essentially, I need some form of template to start me off as I build this app. -
A Python Decimal equivalent isclose method
I'm trying to compare two Decimals in Python with a tolerance of 0.01. When using Math isclose I receive False because of floating point inaccuracy. For example: d = Decimal('123.12') d1 = Decimal('123.11') print(isclose(d,d1,abs_tol=0.01)) Will print out False. I know the reason for this I'm just trying to understand if there is a good way to compare Decimals in Python. -
NoReverseMatch form view pass slug
I don't know what is wrong. I get huge traceback, but without any file in my project. I get error when submitting form: django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)\\/$'] What can I do with slug in form or view? views.py class UserDetailView(DetailView): model = User slug_field = 'slug' slug_url_kwarg = 'slug' def post(self, request, *args, **kwargs): view = ReviewUserFormView.as_view() return view(request, *args, **kwargs) class ReviewContractorFormView(FormView): form_class = ReviewUserForm template_name = 'users/users_detail.html' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['slug'] = self.kwargs['slug'] return kwargs forms.py class ReviewUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.slug = kwargs.pop('slug') super().__init__(*args, **kwargs) class Meta: model = ReviewUser fields = '__all__' urls.py path('<slug:slug>/', view=views.UserContractorView.as_view(), name='detail'), -
How to create Django dynamic model fields
I want to create such a django model that can dynamic create,delete and update django model fields. Like the above image,I want to create a model named EnrollCourse and this model will have fileds like registration number,course code etc.Course code fileds will not pre-defined.I will create it whenever I need it. -
Django how to render sub-classes of an abstract model class in one view
Let's first see what do I have. In my models.py I have: class Category(models.Model): name = models.CharField(max_length=50, unique=True) class Parent(models.Model): class Meta: abstract = True category = models.ForiegnKey(Category, related_name="%(class)s_set") name = models.CharField(max_length=50) class Foo(Parent): foo = models.PositiveInteger(default=1) class Bar(Parent): bar = models.CharField(max_length=20) class Baz(Parent): baz = models.BooleanField(default=True) As you see, I have 3 model sub-classes Foo, Bar, and Baz which inherit from the abstract model Parent. Each unique category can only have one parent_set which is either a foo_set, a bar_set, or a baz_set. (Assume so far I have 3 categories with unique names as foo, bar, and baz). I have the following views in my views.py: class FooListView(ListView): # template: foos/foo_list.html model = Foo class BarListView(ListView): # template: bars/bar_list.html model = Bar class BazListView(ListView): # template: bazs/baz_list.html model = Baz def index(request): return render('index.html, context={"categories": Category.objects.all()}) and in my urls.py I have: url_patterns = [ path('foo/list', FooListView.as_view(), name='foo_list'), path('bar/list', BarListView.as_view(), name='bar_list'), path('baz/list', BazListView.as_view(), name='baz_list'), ] Now in my index.html for each category, I want to render the parent_set (which is either foo_set, bar_set, or baz_set) related to that category. I do not know how can I do this elegantly. What I don't like to do is this (which requires …