Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you store general site settings in the database with django?
I am trying to decide whether I should use the settings file or store settings in the database so that other tools that hook into the database can be used. At its most basic the model will be called Setting from django.db import models class Setting(models.Model): name = models.Charfield(max_length=255, blank=False) value = models.Charfield(max_length=255) So no datatype nothing just text, which is pretty much how it is in the config file. Then getting a setting is just a matter of: my_setting = Setting.objects.get(name='my_setting') Would this way be suitable? -
Django, having Q object filter by function in model
Inside my Profile model I have the following function: It serves to return the fullname of the user (or a alternative if some data is missing). def full_name(self): first_name = self.user.first_name.strip() if first_name and self.user.last_name: if not self.middle_name: full_name = u'%s %s' % (first_name, self.user.last_name) else: full_name = u'%s %s %s' % (first_name, self.middle_name, self.user.last_name) return full_name.strip() elif first_name: return first_name return self.user.username Now for my question: I have a view where I filter a queryset based on the variable 'q' (that is returned from a searchbox in the template) Like so: qs = qs.filter(tenant_demo_purchase=True).order_by('-id') #Search users within results q = self.request.GET.get('q', None) if q: qs = qs.filter(Q(user__username__icontains=q) | Q(user__first_name__icontains=q) Q(user__last_name__icontains=q) | Q(arrangement_period__arrangement__title__icontains=q) | ).filter(tenant_demo_purchase=True).order_by('-id') else: pass return qs This filter works fine if I give it a firstname, username, or a last name. But if I give it a firstname + lastname (example: "John Doe") it returns no results. Most of my users tend to submit the fullname, so as a solution I tried to have it acces the Profile.full_name function. By adding the following line Q(user__profile__fullname__icontains=q) However, this crashes with the following error message: raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) FieldError: Related Field got invalid lookup: fullname … -
ImportError: No module named allauth. Django
in a project with django, when I do "python manage.py runserver" I get this error traceback : Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named allauth I installed allauth using pip3 install allauth. And this is my INSTALLED_APPS : INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] -
Limiting QuerySets in Django is not working
I just get no answer what is not working from Django. Django says everything is okay. I want to limit the results I get from my database. In the documentation is said that the first parameter is the offset and the second how much results I get beginning with the offset + 1. What I am doing wrong here ? When I do not limit the queries everything works fine. So the mistake should be by using the limitation. views.py def ajax_more(request): categoryid = request.GET.get('categoryid', None) query = request.GET.get('query', None) offset = request.GET.get('offset', None) if query: if categoryid == "6": advertisements = Advertisement.objects.filter(title__contains=query)[int(offset): 2] else: advertisements = Advertisement.objects.filter(category__id=categoryid, title__contains=query)[int(offset): 2] else: if categoryid == "6": advertisements = Advertisement.objects.all()[int(offset): 2] else: advertisements = Advertisement.objects.filter(category__id=categoryid)[int(offset): 2] advertisements_list = [] for advertisement in advertisements: advertisements_list.append({ 'id': advertisement.id, 'description': advertisement.description, 'title': advertisement.title, 'picture_url': advertisement.image.url, 'date': advertisement.date }) data = { 'advertisements_list': advertisements_list } return JsonResponse(data) -
Django self.cleaned_data.get("field") is None when field value is 0 : why?
I have a field : models.py class MyClass(models.Model) : myfield = models.FloatField(blank=True, null=True) and a form validation that handles conditionals controls on multiple fields and must raise an error if self.cleaned_data.get("myfield") is None. My problem is : I want to accept the value "0" as correct. but when a user inputs 0 for the field myfield, the self.cleaned_data.get("myfield") is None : Why ? and the form validation raises an error. -
How to iterate for loop with range using django template
I WANT TO USE i inside the loop means {{ posts.0.title|capfirst }} {{ posts.i.title|capfirst }} value of i is 0 to 12 but its not working with {{ posts.i.title|capfirst }} {% for i in TotalCountRange %} <tr class="even pointer"> <td class="a-center "> <input type="checkbox" class="flat" name="table_records"> </td> <td class=" "><a href="{{ post.get_absolute_url }}">{{ posts.0.title|capfirst }}</a></td> <td class=" ">{{ post.pub_date|date:"d M y h:i a" }} </td> <td class=" "><a href="{{ post.category.get_absolute_url }}">{{ post.catname }} <i class="success fa fa-long-arrow-up"></i></a></td> <td class=" ">{{ post.username }}</td> <td class=" "> <!--{% for tag in post.tags.all %}--> <!--{% with b=',' %}--> <!--{% if forloop.counter >= 2 %}--> <!--<a href="{{ tag.get_absolute_url }}">{{b}}{{ tag }}</a>--> <!--{% else %}--> <!--<a href="{{ tag.get_absolute_url }}">{{ tag }}</a>--> <!--{% endif %}--> <!--{%endwith%}--> <!--{% empty %}--> <!--<a href="">None</a>--> <!--{% endfor %}--> </td> <td class=" "><a href="#">Edit</a></td> </tr> {% endfor %} -
Annotate Custom SQL Function (similar to date_trunc) to Django ORM Queryset
I am using timescaledb which is basically just an extension for postgres. It comes with a SQL function called time_bucket. I want to use this function in combination with the ORM to generate a query as follows: SELECT time_bucket('1 minute', time) AS tb, device_id, AVG(s0) FROM measurements WHERE device_id=1 AND time >= to_timestamp(1) AND time <= to_timestamp(2) GROUP BY device_id, tb ORDER BY tb ASC; models.py: class Measurement(models.Model): device_id = models.IntegerField(primary_key=True) time = models.DateTimeField() s0 = models.FloatField(blank=True, null=True) My try so far: (Measurement.objects .values('time') # .annotate(tb=Func('time_bucket')) .annotate(s_desc=Avg('s0')) .filter( time__gte=datetime.fromtimestamp(start), time__lte=datetime.fromtimestamp(end)) .order_by('time') ) I am wondering if I would need to look into the source code of Trunc or is there an easy option I am missing? -
django+docker to elastic beanstalk
I created a super simple django app in docker, following these instructions: https://docs.docker.com/compose/django/ Everything works locally. When I try to upload the folder that includes Dockerfile and docker-compose.yml to AWS Elastic Beanstalk as a multicontainer docker, it does not work. Should I also provide Dockerrun.aws.json? here is what I have in Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ and in docker-compose.yml: version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
Django multiple values in single form field
How can I add multiple values in a single form field just like the image below -
Can't get field value in Ajax call - Django
Here is my ajax call: $.ajax({ type: 'POST', url: '{% url "userprofile:follow" %}', data: { user_to_follow: $("#follow_form").serialize(), csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function showAlertLike() { $("#success_follow").show().delay(2000).fadeOut(); }, error: function showAlertLike() { $("#error_follow").show().delay(2000).fadeOut(); } }); and my view: def post(self, request): if request.method == 'POST': user = request.user user_to_follow = request.POST.get('user_to_follow') print('USER: ', user_to_follow) user_to_follow = User.objects.get(username=user_to_follow) Following.objects.create( user_followed=user_to_follow, follower=user, ) return HttpResponse('') What is being printed on my terminal: ('USER: ', u'csrfmiddlewaretoken=wxWNjebUftJ88ekmCrIwNjJFFMoiO8l1RM2RKqZpeIvtCmIsFKtPDFBlOLUxE0BV') How can I retrieve the input entered in the form field and not the csrftoken? I tried .val() instead of .serialize() but it returns an empty string... Thanks -
Custom User Profile for New Users
{% if user.userprofile.profile %} <img src="{{ user.userprofile.profile.url }}" /> {% else %} <img src="something" /> {% endif %} If user don't have a profile picture then I wants to give them the Profile picture of very First user (means id=1). How can I do that? -
AttributeError at / 'tuple' object has no attribute '_meta'
I'm getting the above error in Django on the second line this code: survey = Survey.objects.get_or_create(organisation=organisation) form = SurveyForm(instance=survey) This is my form: class SurveyForm(forms.ModelForm): class Meta: model = Survey exclude = ['id'] widgets = { 'user' : forms.HiddenInput(), 'organisation' : forms.HiddenInput(), 'responsibleSecurityOfficer' : forms.TextInput(attrs={'class' : 'form-control'}), 'responsibleSecurityOfficerJobTitle' : forms.TextInput(attrs={'class' : 'form-control'}), 'size' : forms.Select(attrs={'class' : 'form-control'}, choices=SIZE_CHOICES), 'baseInfoSecurity' : forms.Select(attrs={'class' : 'form-control'}), 'pciCompliance' : forms.Select(attrs={'class' : 'form-control'}), 'hipaaCompliance' : forms.Select(attrs={'class' : 'form-control'}), 'internationalCompliance' : forms.Select(attrs={'class' : 'form-control'}), 'country' : forms.TextInput(attrs={'class' : 'form-control'}), 'drPlan' : forms.Select(attrs={'class' : 'form-control'}), } I really don't understand why it is not working and I do not see any erroneous commas (which seems to be the general issue based on similar posts). Any help most welcome. -
Django Websockets / Several Users on the Website
I try to get started with Django Channels. I actually have some questions: 1. I use web sockets with channels. I want to have for each frontend user which opens the website his own websocket channel without groups. I am not sure how does it works when several Users opens the website ? Has each frontend user his own consumer thread which handles the web socket messages ? How are the concept here? 2. How can I receive websocket messages in a separate task. I found in the FAQ on the Channels Site the hint to use receive_many() but I'm not sure how to use it exactly. 3. How can I start a separate task in the consumer.py after receive a message ('websocket.receive') ( for example: In Consumer I get a message via websocket from the frontend user, according to the message I start a process with some arguments, after execute the process, I get the results back and send it to the individual websocket channel client) -
Disable Fields from Editing in Django
I have a form with several fields that I would like to show to the user but prevent them from editing (should not be an edit box). My form class looks like this and I'm using the fields meta to have them automatically defined. I'm looking to prevent user from changing their username and email after registration. class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') The question In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited? doesn't provide an answer to what to do if the fields are defined automatically using meta. I've tried disabled = ('username', 'email',) And a few other options but nothing seems to work. I'm looking to prevent someone from also changing the form and submitting it (and the data getting changed) as the previous question suggested can be done. [Edit]: Using Django 1.11 -
Django - leaving blank form when session doesn't exist
I have a noobie question about filling registration forms from sessions. I have 3 step registration form that saves data to session. I am trying to fill form data with previous answers when user goes step back. I managed to do that, but now I have problem when session is empty. Here is the problematic code: if request.session['form_data_page_1']: korisnik = Forma1(initial=request.session['form_data_page_1']) else: korisnik = Forma1() when I do that I keep getting 'KeyError at /start/dadilja/1/' - 'form_data_page_1'. I also tried to do something like this: if request.session['form_data_page_1'] is not Null: korisnik = Forma1(initial=request.session['form_data_page_1']) else: korisnik = Forma1() and something like this: try: korisnik = Forma1(initial=request.session['form_data_page_1']) except: korisnik = Forma1() but when I do that, I get blank page with submit button on it. How to do this correctly, to get blank form when session is empty, and filled form with session data when session exist? Thanks in advance. Renato -
how to combine ember.js with django together
I am new to this ember and django framework ,but i wanted to try how it work out , but i have problem combine them together , i have been look though the web and noting work out. can anyone guide me to combine them both ? so how do i get them work together and how i should start ? this is the website i am following. http://timothypoon.com/blog/2016/02/16/ember-and-django-get-friendly/ -
Accessing the json values on django template
I have finally got a way to access the various values from the facebook using django-allauth. The only issue that I am facing is in the accessing of the values on the template. Here is the views.py: from allauth.socialaccount.models import SocialToken import json import requests def fb_personality_traits(request): access_token = SocialToken.objects.get(account__user=request.user, account__provider='facebook') # print access_token.token requested_data = requests.get( 'https://graph.facebook.com/me?access_token=' + access_token.token + '&fields=id,name,email,posts,about') data_FB = json.loads(requested_data) return render(request, 'home/facebook_personality_traits.html', {'fb': data_FB}) Here is the template taht I am using to display the values: <html> <body> Welcome back {{ user.name }} {{fb.name}} <!-- <img src="" height="60" width="60"> --> <a href="/">Home</a> </body> </html> I am getting the following error: Please let me know what to improve. This is the json I am storing in the json variable: gist of the json -
Django shell_plus TypeError: invalid arguments (virtualenv)
My Django project runs under a virtualenv located at Envs\newenv and I am having trouble running shell_plus: python manage.py shell_plus Raises the following error: TypeError: invalid arguments This is the full trace: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "c:\python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments The problem is happens at this point: File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') The value of that help key argument is of type unicode, but the add_option function in the optparse module expects a str: def add_option(self, *args, **kwargs): """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ if type(args[0]) is types.StringType: option = self.option_class(*args, **kwargs) elif len(args) == 1 and not kwargs: option = args[0] if not isinstance(option, Option): raise TypeError, "not an Option instance: %r" % option else: raise TypeError, "invalid arguments" types.StringType is defined as follows: StringType = str I have … -
Group by in django create wrong query
we have write down this query in django ManageInterview.objects.filter (post_id=request.data['job_id']) .order_by('-id') .annotate(total=Count('pitcher_id')) After print this we got this query SELECT *, COUNT(`pitcher_invitations`.`pitcher_id`) AS `total` FROM `pitcher_invitations` WHERE `pitcher_invitations`.`post_id` = 254555444 GROUP BY `pitcher_invitations`.`id` ORDER BY `pitcher_invitations`.`id` DESC We are doing group by pitcher_id but django query group by pitcher_invitations.id we want this query select * from `pitcher_invitations` where `post_id` =254555444 group by `pitcher_id` order by `id` desc -
ImportError: cannot import name 'setup_environ'
I am creating models in django environment. Below is the sample code. class Album(models.Model): artist = models.CharField(max_length=255) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=255) logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + ': ' + self.artist class Song(models.Model): artist = models.ForeignKey(Album, on_delete=models.CASCADE, null = True) file_type = models.CharField(max_length=255) song_title = models.CharField(max_length=255) def __str__(self): return self.song_title I was getting below error:: ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So, I got some article that suggested me to import django module from django.core.management import setup_environ import settings setup_environ(settings) So now, the above error was corrected, but I got new error as below File "<ipython-input-8-3168a50cefba>", line 2, in <module> from django.core.management import setup_environ ImportError: cannot import name 'setup_environ' I know that the django module is present in my IDE, coz, when I hovered my cursor on the warning icon near the django module it said "django imported but not used". But that is not our concern, as I happened to get rid of the warning. Spyder IDE - 3.2.3 Python - 3.6 Django - 1.11.3-py36_0 -
Accessing the profile information of facebook through Django-Allauth
I am trying to display the complete profile of the authenticated user on my webpage using Django-allauth and Django 1.11.5. I am currently using a simple template as following: <html> <body> Welcome back {{ user.first_name }} <img src="{{cover.source}}" height="60" width="60"> <a href="/">Home</a> </body> </html> Here the image tag is not getting the data. Hence, getting a broken image. But I am wondering how I can use the Django Library and access the complete profile information of the visitor who get authenticated using the Django-Allauthlibrary. Here is the settings.py of my application:-- SITE_ID = 1 LOGIN_REDIRECT_URL = '/facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'user_photos'], 'METHOD': 'js_sdk', 'FIELDS': [ 'email', 'name', 'first_name', 'last_name', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True Kindly, help me. There are many misconceptions I am facing in the usage of the Django-Allauth. I specifically wants to access the Profile URL, Profile Picture, Posts, about me, etc. My Facebook Application has access to many scope, hence there is no problem for this, but the implementation of the library is restricting me from the usage. Kindly, help me. -
How do i find a lost element with jQuery
Well I have the problem, I can't log out when i just log in (without reloading the page). And I cant log in when I just logged out (again with page reload it works). Well I think after reloading the nav, he forgets the id of logout or something? <script> logout = $('#logout') loginform = $('#loginform') logout.click(function () { $.ajax({ url: 'accounts/logout/', success: function (json) { console.log(json) }); }, }); }); loginform.on('submit', function (event) { event.preventDefault(); login(); }); function login() { $.ajax({ url: 'accounts/login/', success: function (json) { console.log(json) /* Reloades the navbar */ $('#usergui').load(document.URL + ' #usergui'); } }); } ; </script> My HTML: <div id="usergui"> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a id="logout"> </span> Logout </a></li> {% else%} <li><a> </span> Login </a></li> <li><a> </span> Register </a></li> {% endif %} </ul> </div> After Login my user gets authenticated and reloading the nav make only logout appear. -
Django Initial Value For Foreignkey Field
So I'm trying to pass some initial data to the volume field in CourseForm, but for some reason it won't work. I've tried looking at similar questions at stackoverflow, but no luck. The volume field is a ForeignKey to a table in the database. It doesn't give me errors just doesn't display any information. My model with the respective volume field: class Course(models.Model): volume = models.ForeignKey(CourseVolume) code = models.CharField(max_length=100, default=None) # ... code shortend to simplify My Modelform with its model set to Course class CourseForm(ModelForm): class Meta: model = Course fields = '__all__' My view where I'm trying to set the initial data for the CourseForm. It just doesn't seem to work. user.volume_preference returns an integer from 1-x which is the id for the specific volume. def view_course_create(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): form.save() return redirect('teaching_courses') else: user = MbsUser.get_user_from_ad(request.session['username']) if user.volume_preference is not None: volume = user.volume_preference form = CourseForm(initial={'volume': volume}) else: form = CourseForm() return render(request, 'teaching/course_create.html', {'form': form}) Anyone who knows how this can be solved? I've really looked and I'm at an impasse. Any help is greatly appreciated. -
Locally hosted Django traffic analytics
is there any known way to track locally hosted django web? I want to know who is using web, how many unique users, what is the most visited resource etc. I would use Google Analytics or smth similar, but my project is deployed offline and has to access to internet. So i need to track the specific IP Django is deployed on. I was trying to install Piwik, since it can be installed on the machine, but i didnt succeed to install mysql on my raspberry pi. I am working on raspberry pi 2 wheezy, python 3 -
How to disable queryset cache in Django forms?
I have a Django form that is supposed to filter choices using a queryset: class GenerateStudentAttendanceForm(forms.Form): selected_class = forms.ModelChoiceField(queryset=Class.on_site.filter( is_active=True, academic_year__is_active=True )) date = forms.DateField(initial=now().date()) The problem is that Class.on_site.filter is evaluated when the form is instantiated and is used for subsequent requests even if the site has changed. How can I come around this?