Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django1.8 or less queryset: filter multiple datetimes by hour
I have a model with a datetime field that I want to filter by hour, the problem is that there's multiple datetimes, making the datetime.now() soluction not realible for this case. Also, if we try gt/lt/gte/lte/in to the hour it doesn't work. The scenario is that if the hour is less then 12 then returns "morning", if it is between 12 and 18 returns "afternoon" and if it is greater then 18 returns "night". Model: class MyModel(models.Model): datetime_field = models.DatetimeField() name = models.CharField() Data example: 1. 2012/10/2 22:00 2. 2015/2/15 15:00 3. 2017/3/2 9:00 Expected queryset: Night = queryset.filter(datetime_field__hour__gte=18) Afternoon = queryset.filter(datetime_field__hour__lt=18, datetime_field__hour__gte=12) Morning = queryset.filter(datetime_field__hour__lt=12) Result: 1. Night 2. Afternoon 3. Morning -
django rest framework, Additional checks and saves in ViewSet and return different response depends on condition
I'm making voting. All user can vote 1 time in 24 hours. User making vote with POST request. Every time he vote I want to check the last time he voted: if he voted more than 24 hours ago I want to save his vote. if less than 24 hours I want to return bad request (or something like this). Please help me. Here is my code but it doesn't work. The object save is happening anyway, doesn't matter what I put in if condition... How to do this things right? views.py: class VoteAddViewSet(viewsets.ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteAddSerializer http_method_names = ['post',] def perform_create(self, serializer): return Response(status=status.HTTP_400_BAD_REQUEST) profile = get_object_or_404(Profile, pk=1) allow_vote_date = profile.vote_date + timedelta(days=1) if (allow_vote_date < timezone.now()):{ profile.vote_date = timezone.now() profile.save() serializer.save(user=self.request.user) } else: return Response(status=status.HTTP_400_BAD_REQUEST) serializers.py: class VoteAddSerializer(serializers.ModelSerializer): class Meta: model = Vote exclude =('id','created_date','user',) urls.py: router = routers.DefaultRouter() router.register(r'vote_add', views.VoteAddViewSet, 'vote_add') urlpatterns = [ url(r'^', include(router.urls)),] models.py class Vote (models.Model): user = models.ForeignKey(User, null=True, blank=True, related_name='girls_user_voted_for', on_delete=models.SET_NULL) girl = models.ForeignKey(Girl, null=True, blank=True, related_name='supporters_of_this_girl', on_delete=models.SET_NULL) created_date = models.DateTimeField(default=timezone.now) def __unicode__(self): return u'{}'.format(self.id) -
Use include tag to include the same template that is calling it
I have a use case where different fields of a form are rendered differently based on an include tag and arguments passed to it. To keep it DRY, sometimes I'd like to include the same template and pass it a different argument, like in a simplified example below: main_form.html {% include "./field-snippet.html" with type=list %} field_snippet.html {% include "./field-snippet.html" with type="regular" %} But that gives a TemplateSyntaxError. Alternatively, I could have different html files for different kinds of fields but that seems to be many files with not much code in each. Any ideas on how to best approach this? Is using custom Widgets the best approach here (I haven't played much with them yet) -
Django return blob form azure-storage as downloadable file
I am new to azure-storage and django My dev environment software configuration is as- django 1.10 , python 2.7.6, azure-storage-blob 0.37. I am using django application as webservice api and frontend is built using angular-2 and HTML I am using azure blob storage for storing files with any type. azure blob Container where which I am saving files have private access only.I am able to upload file successfully. The problem is while downloading file- what I am trying to achieve is- 1] When someone clicks on hyperlink on page request will go to django view with blob name. then I can get blob using container name and blob name block_blob_service._get_blob(container,blob_name) 2] I want to return that blob as downloadable file in django response. Can you suggest be solution or better approach where I can achieve this. Thanks in advance. -
I cannot show images which is url type
I cannot show images which is url type. I wrote in product.html <body> {% for product in products.all %} <h4> {{ product.product_title }}</h4> <img src="{% static product.image }} %}"/> <p> {{ product.body }} </p> {% endfor %} </body> in models.py class Product(models.Model): product_title = models.CharField(max_length=250) image = models.TextField() body = models.TextField() in views.py def product(request): products = Product.objects.order_by('product_title') return render(request, 'registration/product.html',{'products':products}) From admin site,I added product_title&image&body. image's urls is <a href="https://xxxxxx" target="_blank" rel="nofollow"> <img border="0" width="120" height="60" alt="" src="https://wwwyyyyyyyyyyyy"></a> <img border="0" width="1" height="1" src="https://wwwzzzzzzzzzz" alt=""> By using Google console,Failed to load resource: the server responded with a status of 404 (Not Found) is in Console. In Elements,img tag is like <img src="/static/wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww"> How can I show image?Am I wrong to write the way of img tag & src? -
python manage.py runserver throwing error
C:\training\webserver\webserver>python manage.py runserver 0.0.0.0:8001 Unhandled exception in thread started by <function wrapper at 0x0000000003C872E8> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, 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 251, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, 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 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 299, in <module> class AbstractUser(AbstractBaseUser, PermissionsMixin): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 279, in __new__ new_class.add_to_class(field.name, new_field) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 709, in contribute_to_class cls._meta.add_field(self) File "C:\Python27\lib\site-packages\django\db\models\options.py", line 277, in add_field self.local_fields.insert(bisect(self.local_fields, field), field) File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), File "C:\Python27\lib\functools.py", line 56, in <lambda> '__lt__': [('__gt__', lambda self, other: other < self), I am new to python. I gave the following commands. django-admin startproject webserver this created a skeleton project. after this, i gave python manage.py runserver 0.0.0.0:8001 I am getting above error. i am not able to start server. Please guide me.