Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter SQL elements with adjacent ID
I don't really know how to properly state this question in the title. Suppose I have a table Word like the following: | id | text | | --- | --- | | 0 | Hello | | 1 | Adam | | 2 | Hello | | 3 | Max | | 4 | foo | | 5 | bar | Is it possible to query this table based on text and receive the objects whose primary key (id) is exactly one off? So, if I do Word.objects.filter(text='Hello') I get a QuerySet containing the rows | id | text | | --- | --- | | 0 | Hello | | 2 | Hello | but I want the rows | id | text | | --- | --- | | 1 | Adam | | 3 | Max | I guess I could do word_ids = Word.objects.filter(text='Hello').values_list('id', flat=True) word_ids = [w_id + 1 for w_id in word_ids] # or use a numpy array for this Word.objects.filter(id__in=word_ids) but that doesn't seem overly efficient. Is there a straight SQL way to do this in one call? Preferably directly using Django's QuerySets? -
Calling filters in django-graphene with GraphQL
I've been following the documentation for Graphene-Python in Django, and have just made it to the section on custom filters. While a tutorial is provided for how to write custom filters, there isn't a reference on how to call them in GraphiQL. If I have the following example code: class AnimalNode(DjangoObjectType): class Meta: # Assume you have an Animal model defined with the following fields model = Animal filter_fields = ['name', 'genus', 'is_domesticated'] interfaces = (relay.Node, ) class AnimalFilter(django_filters.FilterSet): # Do case-insensitive lookups on 'name' name = django_filters.CharFilter(lookup_expr=['iexact']) class Meta: model = Animal fields = ['name', 'genus', 'is_domesticated'] @property # make your own filter like this def qs(self): return super(EquityFilter, self).qs.filter(id=self.request.user) class Query(ObjectType): animal = relay.Node.Field(AnimalNode) # We specify our custom AnimalFilter using the filterset_class param all_animals = DjangoFilterConnectionField(AnimalNode, filterset_class=AnimalFilter) My question is, what would I need to type in GraphiQL to use this filter? Any help is greatly appreciated. -
Get token after login google
How can I collect token after login with google and use this token for authorization for other view . When I will click the login with google then it will response the token and after receive the token by ajax call I can use this for authentication for other view -
Embedding pyplot graph into html on django framework
I am new to python and django but have a bit of code that works in displaying my graph but as a separate popup window. I am calling this line of code from my html page: {% block content %} <h1>Title: {{ report.title }}</h1> <div> {{ report.show_graph }} //THIS PORTION IS CALLING THE GRAPH WHICH IS RESULTING IN A POPUP OF IT IN A SEPARATE WINDOW </div> <p><strong>Summary:</strong> {{ report.summary }}</p> <p>Date Created: {{ report.date_created }}</p> {% endblock %} It triggers a request and calls the graph but as a separate standalone window. The code I am calling is: class Report(models.Model): """Model representing a report""" title = models.CharField(max_length=200) date_created = models.DateField("Date", default=datetime.date.today) summary = models.TextField(max_length=1000, help_text='Enter a brief summary of the report.') def __str__(self): """String for representing the Model Object""" return self.title def get_absolute_url(self): """Returns the url to access a digital record of this Report""" return reverse('report-detail', args=[str(self.id)]) def show_graph(self): style.use('ggplot') pfizer_data = quandl.get("NSE/PFIZER", authtoken="....") pfizer_data['Close'].plot() return plt.show() I am trying to have the graph be returned as html so it is embedded in the div instead of a separate window. Thanks. -
using wagtailmedia application by torch box in my wagtail application - How do I add the included media into my template after creating a page for it?
I am writing wagtail application that uses an S3 object store to retrieve and upload media and static files. Now in this configuration, I wanted to work with 'wagtailmedia' package, created by torchbox (https://github.com/torchbox/wagtailmedia). I've already defined the model using Blocks and StreamField (as specified on their readme - I did this because the MediaChooserPanel does not work with wagtail >v2.0; see https://github.com/torchbox/wagtailmedia/issues/34). My question is, how do I include the media object and its attributes (like fileurl, name, tags etc) in my template? is there a special tag for wagtailmedia objects like we have for {% image %} in the wagtail templating specifications? Thanks! -
Django: Change settings value during run-time in migrations
I am trying to change a value in settings.py during run-time while creating migrations. settings.py: ... magicVar = "initValue" 0002_init: ... def change_magicVar(apps, schema_editor): settings.magicVar = "newValue" ... operations = [ migrations.RunPython(change_magicVar), ] ... 0003_changed_migrations: ... def print_magicVar(apps, schema_editor): # Yay! It prints the correct value print (settings.magicVar) # prints: newValue ... operations = [ migrations.RunPython(print_magicVar), migrations.CreateModel( name='MagicModel', fields=[ ('someMagic', models.ForeignKey( # Oops! This still has the old value, i.e *initValue* # I want to achieve the *newValue* here! default=settings.magicVar, ... )), I want the changed value in migrations, but it looks like the value is already been cached. Does django provide an abstraction to refresh the migrations cache and put a new value in it? If not, what possible options do i have to achieve that value in the defaults? Note: I am trying to avoid this solution because my database might give millions of records and iterating over them isn't ideal. For external reasons i am also trying to avoid django-livesettings Thank you! -
python django email set correct sender gunicorn
This is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' # mail service smtp EMAIL_HOST_USER = 'xx@xx.com' # email id EMAIL_HOST_PASSWORD = 'sdjlfkjdskjfdsjkjfkds' #password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'xx@xx.com' I am sending password reset email It works fine on localhost but on production server as sender I get webmaster@localhost What do I do? -
Django Oscar External CSS
I just created a store using Django-Oscar - and I am getting a hard time to add external CSS, I mean, I want to replace the whole default style to a more fancy one with nice futures. -
django python password reset email subject with non-english characters
urls.py: url(r'^password_reset/$', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html', email_template_name = 'accounts/email/password_reset.html', html_email_template_name = 'accounts/email/password_reset.html', subject_template_name = 'accounts/email/password_reset_subject.html'), name='password_reset'), In my password_reset_subject.html I have this: Восстановление пароля But I get this subject when sending a email: Subject: =?utf-8?b?0JLQvtGB0YHRgtCw0L3QvtCy0LvQtdC90LjQtSDQv9Cw0YDQvtC70Y8=?= What do I do? -
POST request with Postman to login in Django
I'm sending a POST request to my url http://127.0.0.1:8000/accounts/login/ to login in Django. To send this request i get csrftoken from my browser cookies, and i add it to the cookies in the request. I also tried to add it to the headers. I get CSRF token missing or incorrect. Request type is www-form-urlencoded, with username and password in the body section. -
Django ORM Query for Sum of positive and negative values Separately
I have a column in a database, let's call it as dummy_column. It has values both positive and negative. I want to calculate the sum of all the positive numbers as well as the sum of all the negative numbers as well as the whole sum(positive+negative) i.e. I want the output in 3 separate values. Calculating the sum of both can be done by using Sum('dummy_column') Tried with Case and When, but can't understand what to put in the 'then' clause. Saw this answer related, but I want to avoid the 'extra'. - 'Django queryset SUM positive and negative values' Wasn't much to write the code, so didn't. Any help would be appreciated. -
What Django CBV to change after converting RedirectView to return JsonResponse
I have a Django class based view(CBV) for Like/Dislike toggle feature on a Post model. Works perfectly fine without Ajax. Now that I added Ajax to the View I have to remove the RedirectView from PostLikeToggle. What View do I add instead of in PostAjaxLikeToggle Below a working code for my CBV class PostLikeToggle(LoginRequiredMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get('slug') print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) print(url_) return url_ I have added AJAX to this for asynchronous like/dislike. The below code gives me a Page not found at Error. I was advised to remove the Redirect view and use something else. I am not sure What? Can anyone guide me in the right direction and tell me what view should replace RedirectView in PostAjaxLikeToggle class PostAjaxLikeToggle(LoginRequiredMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get('slug') print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) context = { "post": obj, } if self.request.is_ajax(): html = render_to_string("posts/like_section.html", context, request=self.request) print(html) return JsonResponse({"form": html}) The complete code should you need it is below Page not found error … -
Django rest framework execute custom function without viewset (remote procedure call)
I'm triying to do a remote procedure call (regular call to server by ajax) from AJAX to a Django server with Django Rest Framework (DRF) for maintenance tasks. Problem I only have model viewsets and only need to execute a basic server task, for example, delete all items in one model. Solution Use generic apiview from DRF. See code on answer below. -
How to check if a new file was selected in django admin using a pre_save signal?
I have a model that has an ImageField attribute. I update the model objects using the django admin and I needed something to delete the old image when a new image is uploaded while trying to update an object. So I created a pre_save signal that should delete the old image file from the server when the user attempts to update the model object. The problem is: When the user updates object's attributes other than the ImageField attribute, the signal still deletes the locally saved image file.. How can I change the signal to delete the file only if a new file was selected in django admin? In other words, I need to check if the user uploaded a file while trying to update the object in django admin. IMPORTANT NOTE: My signal works with many models.. and I need to keep it like that. Here is the signal code: @receiver(pre_save) def pre_save_image_delete(sender, instance, **kwargs): if not valid_model(sender.__name__): return # Get file path on the server path = get_photo_path(sender.__name__, instance.pk) # delete the file if it exists if path and file_exists(path): delete_file(path) -
Django DRF browseable API not sending data correctly / breaks browser
I have created a simple Django Rest Framework API to try and get my data out of a postgresql to a django website I am building. I am getting to the browseable API in my django and see the first few lines in the correct json format, but then the browser (Firefox) complains that the site is slowing down my browser and just cycles - never finishes. The same happens when I don't use the browser to GET request the API for data. I have a lot of data: 15k lines x 14 columns = 210k data points - can this be the problem? Version: Django = 2.1.1 DjangoRestFramework = 3.8.2 Code: models.py from django.db import models # Create your models here. class dbrealestate(models.Model): hash_id = models.BigIntegerField(primary_key=True, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) yields = models.FloatField(blank=True, null=True) price = models.BigIntegerField(blank=True, null=True) garden_area = models.FloatField(blank=True, null=True) parking = models.TextField(blank=True, null=True) terass = models.TextField(blank=True, null=True) loggia = models.TextField(blank=True, null=True) cellar = models.TextField(blank=True, null=True) elevator = models.NullBooleanField() garage = models.TextField(blank=True, null=True) balcony_size = models.TextField(blank=True, null=True) num_floor = models.BigIntegerField(blank=True, null=True) num_rooms = models.BigIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'realestate' serializer.py from .models import dbrealestate from rest_framework import serializers … -
{"detail":"Authentication credentials were not provided."}
I am following an online tutorial on authentification with drf (knox), but I have a problem. (link to the tutorial) I am working on the login api and when I test it with curl, it returns {"detail":"Authentication credentials were not provided."} When I looked on other questions, the problem seemed to be that they forgot to write REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), } in their settings, but I haven't. This is my Login Serializer : ` class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Unable to log in with provided credentials.")` And this is my Login Api: class LoginAPI(generics.GenericAPIView): serializer_class = LoginUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) And this is my curl request: curl --request POST \ --url http://localhost:8000/api/auth/login/ \ --header 'content-type: application/json' \ --data '{ "username": "user1", "password": "hunter2" }' What is the problem? Please help me and don't hesitate if you need anything else to help you helping me :D -
Create a new column using computed values in query set in Django?
I am working on top of existing project, I am not allowed to make migrations to the current model. Suppose I have a model like this: class Things(models.Model): name = models.CharField(max_length=255) objs = Things.objects.values('name') will give me the following result |objs| |----| |apple| |orange| |banana| |fruits| |car| |bus| |motorcycle| |autombiles| so if i do : somequery = objs.some_function(), how do i get the following result, assuming its possible. |cats | objs | |------------------ | |automobiles|car | |automobiles|bus | |automobiles|motorcycle| |fruits |apple | |fruits |orange | |fruits |banana | ------------------------- from what i read about this so far, there isn't a straight way of solving this without altering the models.py. Any help/suggestion will help me tremendously. -
Django not rece ving telegram webhook
I am trying to build a telegram bot. I am using django application for it. I hosted my django application it is working fine. I am running on pythonanywhere server with https. I successfully set my web hook and it is working completely fine. But I don't know why my django server is not receiving any responses. This is my views.py code from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import requests @csrf_exempt def telegram_bot(request): # print(request.GET) # print(request.POST) print("this is sample") if request.method == 'POST': requests.get('https://api.telegram.org/bot<token>/sendMessage?chat_id=<id>&text=this is a sample text') return HttpResponse(status=200) I am just printing some sample message to my log and sending a sample message back to the telegram to the corresponding chatID. But this code is not getting triggered, I am not sure why this is happening. Finally, I tried this https://api.telegram.org/bot/getWebhookInfo It is displaying me about 22 messages are not sent yet in pending_update_count. Any help is acceptable, thanks -
Django; How to insert the spaces between the output of the form data in the browser?
How can I insert spaces in form data? For example, when I submit this data, it outputs like this. views.py is like this. if request.method != 'POST': form = CommentForm(entry=entry, user=request.user) else: form = CommentForm(request.POST, entry=entry, user=request.user) if form.is_valid(): form.save() forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['text'] def __init__(self, *args, **kwargs): self.entry = kwargs.pop('entry') self.user = kwargs.pop('user') super().__init__(*args, **kwargs) def save(self): comment = super().save(commit=False) comment.entry = self.entry comment.user = self.user comment.save() return comment How can I fix this? -
Django Submit Form and keep searchresults
I'm using Django for a page in which the user can search for images and add them to a list. On the top, there is a dropdown with all available lists, and in the pages "body" there is a search form where the user can search for images by tag. <form action="{% url 'qwe:search' %}" method="get"> {% csrf_token %} <input type="text" name="q" placeholder="Search..." {% if query_string %} value="{{query_string}}" {% endif %}> <input type="submit" value="Search"> </form> On submit the user gets the same page with a list of search results. def search(request): query_string = request.GET["q"] if (query_string == None): return HttpResponseBadRequest() search_results_list = img_search(query_string, max_results=25) list_list = helpers.get_lists() context = {"search_results_list" : search_results_list, "query_string" : request.GET["q"], "lists " : list_list } return render(request, 'qwe/index.html', context) I want the user to be able to create other lists, so i added a button next to the dropdown. When the user clicks on it, it opens a dialog (div) with a form containing an input for the new lists name. The Problem: What is the best way, to submit the form for creating a new list, without loosing the search results. I do this mainly for learning purposes, so every hint is welcome. Thank … -
Error during installing dependencies for django's test suite
I'm following the tutorial on how to contribute a patch to Django for the first time from here. I've encountered an error during installation of dependencies for django's test suite. I've followed everything mentioned in the docs up to this point. When I execute this command: (djangodev) apoorv@apoorv:~/django_dev_copy/django/tests$ pip install -r requirements/py3.txt I get an error midway during installation: running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/pylibmc copying src/pylibmc/test.py -> build/lib.linux-x86_64-3.6/pylibmc copying src/pylibmc/__init__.py -> build/lib.linux-x86_64-3.6/pylibmc copying src/pylibmc/client.py -> build/lib.linux-x86_64-3.6/pylibmc copying src/pylibmc/__main__.py -> build/lib.linux-x86_64-3.6/pylibmc copying src/pylibmc/consts.py -> build/lib.linux-x86_64-3.6/pylibmc copying src/pylibmc/pools.py -> build/lib.linux-x86_64-3.6/pylibmc running build_ext building '_pylibmc' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/src gcc -pthread -B /home/apoorv/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DUSE_ZLIB -I/home/apoorv/.virtualenvs/djangodev/include -I/home/apoorv/anaconda3/include/python3.6m -c src/_pylibmcmodule.c -o build/temp.linux-x86_64-3.6/src/_pylibmcmodule.o -fno-strict-aliasing -std=c99 In file included from src/_pylibmcmodule.c:34:0: src/_pylibmcmodule.h:42:10: fatal error: libmemcached/memcached.h: No such file or directory #include <libmemcached/memcached.h> ^~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/home/apoorv/.virtualenvs/djangodev/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install- wjutkj18/pylibmc/setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install -- record /tmp/pip-record-pveaeajs/install-record.txt --single-version- externally-managed --compile --install-headers /home/apoorv/.virtualenvs/djangodev/include/site/python3.6/pylibmc" failed with error code 1 in /tmp/pip-install-wjutkj18/pylibmc/ I've no idea why is this happening. On tutorial it says "If you encounter an error … -
FieldField Auto delete file on change or delete
I implemented auto delete image from the media files when post is deleted using below guides. Below guides works perfectly for me but when I try to add images in the previous post having empty image fields, its throwing some. https://djangosnippets.org/snippets/10638/ -
face problem to import css, js files link in django
I am a newbie in Django 2.11.1 and using macbook as my platform. I have a problem to link my css, images and js to django templage, Here is my project structure sentiment_analysis |-zeta | |-.vscode | |-users | |-manage.py | |-venv | |-static | |-zeta | | |-_pycache_ | | |-__init__.py | | |-setting.py | | |-wsgi.py | | |-urls.py | |-advertising | | |-_pycache_ | | |-migrations | | |-__init__.py | | |-admin.py | | |-models.py | | |-tests.py | | |-urls.py | | |-views.py | | |-tests.py | | |-app.py | |-templates | | |-advertising | | | |-index.html | | |-users -
Django; How to insert spaces in form data
How can I insert spaces in form data? For example, when I submit this data, it outputs like this. How can I fix this? -
Django do something with each different value in a model field
I know I've seen this before, but I can't find now that I am ready to implement it. I'm trying to list items on a page by category and subcategory, but I only want 1 category and then the subcategories in the category. Hopefully my code will make sense. class Objects(models.Model): # Main Checkbox. category = models.CharField( max_length=100, blank=True, ) # Checkboxes under Main Checkbox. subcategory = models.CharField( max_length=100, blank=True, ) So my objects are stored as: category1, subcategory1 category1, subcategory2 category2, subcategory1 category2, subcategory2 And when displayed should give me: category1 subcategory1 subcategory2 category2 subcategory1 subcategory2 How do I set my query so that my results show me each "different" category?