Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Crontab job does not load virtualenv settings for working with django.setup()
Well, I have a project structure like this one: my_project |-scripts | |- my_script.py | |-django_project |- myApp | |- models.py | |- ... |- django_project |- settings.py |- ... I run Django inside a virtualenv and in my_script.py I have to use some of myApp.models So, here is how I did: my_script.py: import django django.setup() from myApp.models import foo # do things Since I am inside a virtualenv, to make django.setup() work properly I set in my virtualenv ($VIRTUAL_ENV/bin/postactivate): DJANGO_SETTINGS_MODULE = django_project.settings and I added django_project to the path: $ workon my_virtualenv $ python -c "import sys; print sys.path" ['', '/my_project/django_project', ...] And that's all. If I activate my virtualenv and then I run my_script.py all works fine. But If I schedule a similar crontab job: 00 00 * * * /.../.virtualenvs/my_virtualenv/bin/python /my_project/scripts/my_script.py >> /.../test/test.log 2>&1 I get this error: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. It seems like my_virtualenv extra settings are not properly loaded. Why does this happen, and how can I fix? -
is it possible to dynamically change field name within django-rest-framework serializer?
I have Product and ProductCategory models. Let's say I have ProductCategory TV, which has Sony, Samsung as its products. I also have MobilePhone category with Apple and Nokia as its products. Using DRF, I would like to get JSON output using serializers, which is similar to the below: { 'TV': [ 'Sony': { 'price': '$100', 'country': 'Japan', }, 'Samsung': { 'price': '$110', 'country': 'Korea', } ] 'mobile_phone': [ 'Apple': { 'price': '$300', 'country': 'USA', }, 'Nokia': { 'price': '$210', 'country': 'Finland', } ] } The problem here is that the field names('TV', 'mobile_phone') in serializer have to be dynamic. I know I can get the following JSON type { [ { 'product_category': 'TV', 'manufacturer: 'Sony', 'price': '$100', 'country': 'Japan', }, { 'product_category': 'TV', 'manufacturer: 'Samgsung', 'price': '$110', 'country': 'Korea', } ] [ { 'product_category': 'mobile_phone', 'manufacturer: 'Samgsung', 'price': '$300', 'country': 'USA', }, { 'product_category': 'mobile_phone', 'manufacturer: 'Apple', 'price': '$210', 'country': 'Finland', } ] } with class CategorySerializer(serializers.Serializer): product_category = serializer.CharField() manufacturer = serializer.CharField() price = serializer.CharField() country = serializer.CharField() But the dynamically-changing-field-names is difficult to achieve. Is there any way I can do this? -
Django TypeError -> not all arguments converted
not all arguments converted during string formatting Here's my code : avatar="https://www.gravatar.com/avatar/" % hashlib.md5(self.normalize_email(email)) -
Django Models - How to store fields in a dict
I have a fairly simple user-model perfectly working. In order to reduce code redundancy, I try to store fields inside a dictory for reasons you can easily guess. Example: def get_social_token(self,social_net=""): return self.social_dict[social_net]["token"] If I don't do such a structure I must do some "if/then ... elif... else". And of course I need to modify my code whenever I decide to add a new social network to my app. I have tried two different approaches, both of them give me the same result: No error No field is actually detected and created in the DB I'd like to mention that if I use a "conventional manner" to implement this behaviour such as: twitter_social_token = EncryptedCharField(max_length=500, default='', blank=True, null=True) It perfectly works, so it comes from the use of a dictionary. Any idea to solve this ? Btw. I would prefer avoiding using a new model and a foreign key... Only a One-to-One association, I would prefer not having to perform any "join" or select in another table... Bellow, you'll find the two attempts I made which doesn't work (and I don't know why): Thanks for the help dear friends, Jonathan -
Django project 'site cant be reached'
I've created a Django project and a virtual environment where I installed python on my Ubuntu server. When I try to run the development server by typing $ ./manage.py runserver 0.0.0.0:8000 I get the usual Performing system checks... System check identified no issues (0 silenced). April 01, 2017 - 11:36:55 Django version 1.10.6, using settings 'myproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. However, when I go to the site [my ip address]:8000 I get a 'This site can’t be reached' message, anyone know any causes for this? thanks -
Mezzanine/Django 1.10 migrations: Database tables does not much with migrations
I am using Mezzanine (Django 1.10) so I can't see a "db.sqlite3" I searched similar questions as mine and most of the solutions provided were not effective. I created a new model and later decided to add a new field. I did "python manage.py makemigrations ", and when I looked at my migrations folder, it's there; the new field exists. Now, when I ran the app and looked into admin, it gave me error where it said "No such column exists". Therefore, I think, my database is not synced with the migrations I have. This is what I did: 1. deleted everything in the migration folder and recreated the "init.py". 1.1 ran "python manage.py makemigrations <app_name>" 1.2 ran "python manage.py migrate <app_name>" 1.3 ran "python manage.py runserver" I can actually just rename my model into a different name with the same fields, however, sometimes Django would give error such as "no such table exist". It would also be quiet tedious to do because if I rename my model, I have to rename it in every file where I have imported the model such as in admin.py, forms.py, views.py, etc. I heard about South, but its not applicable to Django 1.10. … -
How to build a personal website (tools related)?
I want to build a personal website to share content and to promote some work done. I have some programming knowledge but there are so many technologies that I don't know where to start and which steps to follow. I would like to have something like a main landing page, contact options, some static information and a "blogging" section to share posts. I was thinking about Wordpress, SPA's mixed with wordpress but there are other technologies as HTML5+Bootstrap, Angular, Django and so on. What would you recommend me to do? -
Auth2 and following links when connected
When you do authentication with google or facebook, here's what's happening (that's from my tests, if I'm wrong correct me): you send google (or fb) a return URL + some information for authentication google authenticate the user (enter password + credentials) if everything is ok, google brings the user back to the URL you've provided From Django point of view: the problem is that in the URL you can't add parameters in the GET. so for example, the user is on the page "/client" he clicks on "login" button provided by Django core system then you are redirected to the page "/login?next=clients" when you want to authenticate, you're not authenticated, right? So the current session is right now an anonymous session because it's anonymous, you can't remember something the session (this doesn't work and is removed as soon as the user is authenticated: req.session['url_back'] = req.GET.get('next')) so you send everything to google (or fb) but you can't add parameters in the GET so you have to remove the "next=clients" parameters, so you loose where the user wants to come when google redirects the user, there's no information where you can bring the user back to the original URL. I have … -
In Django cannot download a file stored in static
i have a .xls file stored in static/paper and when using <a href="{% static 'paper/template.xls'%}" download> the error is file could not be downloaded the file structure is MyPrj/static/paper/template.xls what should i do? -
Requests in authenticated session are sometimes sent by AnonymousUser in Django
I've a django application which runs on gunicorn behind nginx proxy. When users log in, I redirect them to a single page application which is developed by Angular. I'm using @login_required decorator for all functions used in SPA. While using the application, one random function call suddenly is sent as AnonymousUser, so the @login_required decorator does not work, so I log out the user, or show error. I'm using a custom user profile, with session engine as cached_db run by memcached & postgresql behind pgbouncer My authentication relative settings are as follows: ps: get_env_variable() function gets the variable from the OS environment. AUTH_USER_MODEL = 'main.User' AUTH_PROFILE_MODULE = 'main.User' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.sessions', *** ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #Sessions SESSION_SAVE_EVERY_REQUEST = True SESSION_COOKIE_NAME = 'sesid' SESSION_COOKIE_PATH = '/' SESSION_COOKIE_DOMAIN = 'domain.com' SESSION_COOKIE_SECURE = True SESSION_COOKIE_AGE = 1800 SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' CSRF_COOKIE_NAME = 'csrftkn' CSRF_COOKIE_PATH = '/' CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_DOMAIN = 'domain.com' CSRF_COOKIE_AGE = 1800 CSRF_TRUSTED_ORIGINS = ['domain.com'] SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = "SAMEORIGIN" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env_variable("DATABASE_NAME"), 'USER': get_env_variable("DATABASE_USER"), 'PASSWORD': get_env_variable("DATABASE_PASSWORD"), 'HOST': get_env_variable("DATABASE_HOST"), 'PORT' : get_env_variable("DATABASE_PORT"), 'CONN_MAX_AGE': None, 'OPTIONS': … -
jquery chosen not showing dropdown in django admin
I tried to use jquery chosen in django admin and it is not showing dropdown after implementing. With some debug I can confirm that the dropdown is there but not showing due to some css issue. Any help ? -
django-bower: Static files to be loaded by BowerFinder not found
For some reason, the static files which are to be loaded by djangobower.finders.BowerFinder are not loading (getting a 404 Not Found in the server) settings.py STATIC_ROOT = "/root/Desktop/django-DefectDojo/static/" STATIC_URL = '/static/' STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'djangobower.finders.BowerFinder', ) BOWER_COMPONENTS_ROOT = '/root/Desktop/django-DefectDojo/components/' BOWER_INSTALLED_APPS = ( 'jquery-ui', ) INSTALLED_APPS = ( 'djangobower', ) template <script src="{% static "jquery-ui/jquery-ui.min.js" %}"></script> project structure -project root -static -components -vendor -assets -bower-components -jquery-ui -jquery-ui.min.js I do a ./manage.py bower install followed by a ./manage.py collectstatic Now, on running the server, I get a Not Found. However, when I make STATICFILES_DIRS = ('/root/Desktop/django-DefectDojo/components/vendor/assets/bower_components/',) then the static files get loaded. But this shouldn't be the case as BowerFinder is supposed to be doing this. -
TypeError: "'ForeignKey' object does not support indexing"
I am working on a django project and I am trying to do something like this: In the admin interface for user model I just want to show those fields whose area shown in the dropdown are decided by the function get_area(). Also I am passing the userzone object that user will select for the user model, because to get the area I need the id of selected zone object. models.py def get_area(zone): area = Area.objects.filter(radius = "NONE") areas = {} z = Area.objects.get(zone) class user(models.Model): userzone = models.ForeignKey(Zone) area = models.ForeignKey(Area, on_delete=models.CASCADE, choices = get_area(userzone)) When I am doing z = Area.objects.get(zone) to get the id for the zone object, I am getting the error: TypeError: "'ForeignKey' object does not support indexing" Can someone let me know what I am doing wrong. Or is there a better way to do this? -
how to associate django with adsense?
I paste the code snippet in a template. But nothing's shown except for a white space. according to google's instruction I placed the ad's code in a div between body tags. here is my site I can see the code in developer Tools of chrome, but it displays nothing in the broswer's view. -
Update Django model using Django forms
I'm trying to update user profile in Django. That is the user model and extended member model. The RegistrationForm is as follows: class RegistrationForm(forms.Form): first_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("First name *"), 'class': 'form-control'})) last_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Last name *"), 'class': 'form-control'})) email = forms.EmailField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Email address *"), 'class': 'form-control'})) password = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Password *"), 'class': 'form-control'})) password_confirm = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Re-type your password *"), 'class': 'form-control'})) company_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Company name *"), 'class': 'form-control'})) member_id = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Member number *"), 'class': 'form-control'})) vat_number = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("VAT number *"), 'class': 'form-control'})) address = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Address *"), 'class': 'form-control'})) postcode = forms.CharField(label='', max_length=7, widget=forms.TextInput(attrs={'placeholder': _("Postal code *"), 'class': 'form-control'})) city = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("City *"), 'class': 'form-control'})) telephone = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Telephone *"), 'class': 'form-control'})) mobile = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Mobile *"), 'class': 'form-control'})) terms = forms.BooleanField(label="", required=False, widget=forms.CheckboxInput(attrs={'class': 'magic-checkbox'})) def clean(self): password = self.cleaned_data.get("password") password_confirm = self.cleaned_data.get("password_confirm") if password != password_confirm: msg = _("The passwords do not match.") self.add_error('password', msg) self.add_error('password_confirm', msg) def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(username=self.cleaned_data['email']).exists(): raise forms.ValidationError(_("User with the given email address already exists.")) return email def clean_member_id(self): member_id … -
ctrl+O and ctrl+shit+t is not working in eclipse of django project
Why shortcut keys ctrl+O and ctrl+shit+t is not working in eclipse of django project, Is any settings need to be done for this ? Using eclipse neon and also install pyDev in eclipse -
How do I print each individual array item as a template variable in Django?
I got a field in a Django modal as the following: tags = models.CharField(null=True, blank=False, max_length=50) and within that field I have the value of: ['One', 'Two', 'Three'] I'm currently trying to have it print out "One", "Two", and "Three" separately in a Django template using a for statement such as follows: {% for tag in posts %} {{ tag }} {% endfor %} But it seems to be printing each individual charter from the array instead of the word itself. I know I'm over looking something here. Can someone by any chance help me or point me in the right direction? Thanks in advance. -
How do I fix the margins on PDFs created by Sphinx easily?
I have a Django Project where I used Sphinx to create my documentation. I went through sphinx-apidoc and ran 'make latexpdf'. The resulting documentation has a quite a few lines that flow out of the margin. On top of margin issues, lines in the index start overflowing onto each other. Overflowing Lines Margin Issues :( Is there an easy way to fix these issues (or an easier way to create PDF documentation)? ELI5 if possible (I'm not well-versed in LaTeX) -
python set specific locale for date as a string
I am using python 3.4 & django 1.10. I have some code that sets and then dynamically displays strings to the user depending on the language they select on the template, via a select list of languages. For example, if user selects de, the German values are displayed, en displays English (US) details, etc. I am trying to localise the today's date string to different language codes. I have searched google and SO, but cannot figure this out, or even if this is possible. Does any one have any suggestions? Thanks. Here is my code: from django.template.defaultfilters import date as _date from datetime import datetime GENERIC_DETAILS_LIVE_PREVIEW_LABELS = { 'ar': { .... 'nac_generic_descriptor': u"موظف السنة", # Employee of the year 'nac_generic_preview_date': _date(datetime.now(), "N j, Y"), # todays date localised .... }, 'en': { .... 'nac_generic_descriptor': u"Employee of the year", # Employee of the year 'nac_generic_preview_date': _date(datetime.now(), "N j, Y"), # todays date localised .... }, 'it': { .... 'nac_generic_descriptor': u"Impiegato dell'anno", # Employee of the year 'nac_generic_preview_date': _date(datetime.now(), "N j, Y"), # todays date localised .... }, 'de': { .... 'nac_generic_descriptor': u"Mitarbeiter des Jahres", # Employee of the year 'nac_generic_preview_date': _date(datetime.now(), "N j, Y"), # todays date localised .... }, 'fr': … -
Django forum website with multiple app-instance
i'm trying to create a forum that has a similar function with piazza.com However, right now i have an django-app that is a functional forum, but how do I have multiple instances of this forum app such that users can create their own forums (i.e. a forum just for english class, and another for math class) all sharing the same django app features? Thank you! -
Static files folder in Django project
The folder of my django project is as follows. prj_name |---prj_name |---settings.py |---app1 |---views.py |---app2 |---templates |---app1 |---ta.html |---app2 |---tb.html Template files for app1 and app2 are put under templates folder. And the definition of TEMPLATES in settings.py is as follows. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(BASE_DIR, 'templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And in views.py of app1 to render the template ta.html I used the follows function. def function1(request, template_name='app1/ta.html'): ... return render_to_response(template_name, locals()) The above codes work fine for me. Now I want to adopt bootstrap to make the pages more beautiful, where I use public css, js, img folders for all the template pages. Then my folder list becomes: prj_name |---prj_name |---settings.py |---app1 |---views.py |---app2 |---static |---css |---bootstrap.min.css |---js |---img |---templates |---app1 |---ta.html |---app2 |---tb.html And the static files definition in settings.py is as follows. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] And in ta.html: {% load static %} <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> When I runserver and visit the page, django cannot find my css file and the error is: Not Found: /app1/css/bootstrap.min.css That is, django tries to find css file … -
what is django, how to study djangdo
Our situation is: First we have a kernel thread (say KS) that starts to run when kernel starts to run; Then when system is ready, we create another namespace (say NS1) that has a different mntns with LXC. Our requirement is the KS need to write something in a path that can only seen by NS1. So I'm thinking can I move the KS to the NS1 namespace (at least change the mount namespace)? If yes, how? I have checked the setns() syscall and its kernel source code, but still don't know how to do it (either in user-space or change the KS source code), and even not sure if this is the right way to solve the problem. My other question is: my understanding is that a kernel task (e.g., kernel threads) aware "namespace" if it is in process context, but my friend thinks that the "namespace" is a user-space concept, all kernel staff knows only about the root namespace. Which one is correct? -
Getting RelatedObjectDoesNotExist after checking user type in Get_Success_URL
After my users have finished logging in, I wanna check what type of user He is and then show a page based on the type of user He is. Look in my code how I'm doing, Everything seems to be okay, But I get RelatedObjectDoesNotExist If I log in as a Teacher it's gonna say that User has no Student. Because of it I'm thinking only the first if is being checked and the others ignored. I'm new to django, Any help is a help. class LoginView(UserPassesTestMixin,generic.FormView): form_class = AuthenticationForm template_name = "acc/login.html" def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() return form_class(self.request, **self.get_form_kwargs()) def form_valid(self, form): login(self.request, form.get_user()) return super().form_valid(form) def get_success_url(self): if self.request.user.student: return reverse("StudentPage") elif self.request.user.teacher: return reverse("TeacherPage") else: return reverse(HttpResponseForbidden) def test_func(self): return self.request.user.is_anonymous def handle_no_permission(self): if self.request.user.teacher: return reverse("TeacherPage") elif self.request.user.student: return reverse("StudentPage") else: return reverse(HttpResponseForbidden) -
Running django-admin tutorial erros: no module named django
just started to try and install/run django on my cmd prompt and faced with this issue although environment variables are set up for django Besides getting a solution, can someone help me understand the root cause of the error below? Thank you! C:\Python>django-admin startproject test Traceback (most recent call last): File "C:\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "C:\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\windows\syswow64\scripts\django-admin.exe__main__.py", line 5, in ModuleNotFoundError: No module named 'django' -
Django Timezone Issue
so I have model with a DateTimeField. Now when I store it in the database it gives me the correct time. However, when I print out the time, the time is ahead by 4 hours. This is probably due to some timezone issue. So I did some research and in my settings.py I have set a timezone: TIME_ZONE = 'Canada/Eastern' But it still doesn't work. Any ideas on how to solve this issue?