Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CBV or Functional View for JsonResponse
I am new to creating API endpoints using Django. Which is a better way to handle API requests and process JsonResponse? Should I do it in a Class-Based View? Or a Functional View? I would assumed CBV would be an overkill since people tend to use CBV for the generic-view inheritance. Since I am merely sending back a Json object, i would consider it unnecessary and thus a Functional view would suffice. However, I am not too sure what exactly are the other components of CBV and FV that would matter and make the difference. If there is one view better over another view, can you please tell me with reasons why one is preferred over another. Cheers. -
How can I change email sender's name in django
I'm creating email system in my django project and faced to next question: Send email from custom email sender name, f.e. sending email from gmail(btw it works in my project) requires sending messages only from gmail account, same thing with smtp-pulse, sendgrid and etc. . My question is: May I use any of already configured smtp servers in my case, or I only need to create my own using smtplib(f.e) and configure it? Tried: DEFAULT_FROM_EMAIL = 'support@site.com' SERVER_EMAIL = 'support@site.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 2525 EMAIL_USE_TLS = False EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'password' This one doesn't work. Same with mail.ru/smtp-pulse.com -
Django convert raw SQL ordering to QuerySet API
I'm trying to perform natural ordering on CharField for model (here simplified version): class House(models.Model): number = models.CharField(max_length=32) def __str__(self): return str(self.number) >>> House.objects.all() <QuerySet [<House: 2>, <House: 1>, <House: 4>, <House: 3>, <House: 1b>, <House: 2b>, <House: 1c>, <House: 13c>, <House: 10>, <House: 2e>, <House: 3ab>]> I have managed to order it by raw SQL query: House.objects.raw("SELECT * FROM entry_house ORDER BY(substring(number, '^[0-9]+'))::int, substring(number, '[0-9].*$')") But I need to get QuerySet object not RawQuerySet (for our current pagination implementation). Iterating over all raw queryset is not an option because of huge amount of data. How can I convert result of RawQuerySet to QuerySet or even better, how to convert this raw SQL query to Django QuerySet API? -
Pass attributes from a Cutom Field to a Custom Widget template
I want to create a custom Field and a custom Widget. I'm trying to do this using ModelForms. How can I pass arguments from the Field to the Widget but not as widget attributes, similar to how {{ widget.name }} is passed. field_name = CustomField(obj_original=ALPHA, obj_type=100) I want to use this values in the widget template as conditional and/or as values for template tags(do some manipulation), so this is why I don't want them in attributes(the attribute will appear in the html elements), this don't. I know I can pass multiple attributes in widget, but I need then to remove them from attributes and attached as direct properties/attributes of the widget. I want to be passed in the Field, not in Widget. I check in django source ChoiceField and SelectField but it is not very clear for me. -
updated file name in django
This is an admin form handler, for example I upload a test.txt file in the django admin panel: def save_model(self, request, obj, form, change): if 'torrent_file' in form.changed_data: print("file has changed: ") print(obj.file) else: print("file has not changed") super(FileAdmin, self).save_model(request, obj, form, change) here I get the original file name from the upload form, but by fact the file is saved with another name if there is already a file with this name, but in the above code i get only the original name in all cases, how to can I get the changed/updated file name that was saved?.. -
Django boolean choice field
How can I make a django form of Yes and No. for example I want my django website to have a question like: "Do you use Django?" -Yes -No the - sign is the radio buttons. How can i do this in django -
Modifying a Django Rest Framework Request
I have a Django rest framework api set up, and I'm trying to insert the current time into incoming PUT requests. I currently have: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.filter(done = False).order_by('-time') serializer_class = ItemSerializer paginate_by = None def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(self.object_list, many=True) return Response({'results': serializer.data}) This handles partial updates, but I would like to be able to send a request setting an Item to done = True and have the api also insert a unix timestamp into the data sent to the serializer. Could I alter the request object like this, or is there a better way? def put(self, request, *args, **kwargs): request.data['time'] = time.time() return self.partial_update(request, *args, **kwargs) -
Why does my django cache return nothing? Not even 'None'
I have the following three functions. The bottom function calls on the top two functions. I will get an error when multiplying the variables c=m*b 'unsupported operand type(s) for *: 'NoneType' and 'float'' and as you can see m returns nothing. So my two problems are that btc_to_hourl3 does not show 'None' or a value (and therefore skips the if statement). And secondly when printing totalUserL3hours(user1) in last function it prints nothing even though the function called shows a cached variable? def btcToHourL3(): btc_to_hourl3 = cache.get('btc_to_hourl3') print("btc to hourl3 cached is : ".format(btc_to_hourl3)) #shows as nothing when is something? if btc_to_hourl3 is None: main_api = 'https://api.nicehash.com/api?method=balance&id=keyhere' json_data = requests.get(main_api).json() balance1 = json_data['result']['balance_confirmed'] print("Nice hash L3 balance is: {}".format(balance1)) btc_to_hourl3 = float(balance1)/totalMachineHoursWorkedMonthL3() m = float(btc_to_hourl3) print("Total btc to every hour is: {}".format(btc_to_hourl3)) cache.set('btc_to_hourl3', m, 900) #cache for 15 mins return float(btc_to_hourl3) def totalUserL3hours(user1): user_L3_hrs = cache.get('user_L3_hrs'+user1.username) print("User l3 cache hours are {}".format(user_L3_hrs)) ####Prints 'None' when it is none ie after 1800secs. Prints 511 when works if user_L3_hrs is None: a=0.0 l3_total = user1.L3s.all() for l3 in l3_total: x = l3.indivMachineHoursWorked() a=a+x cache.set('user_L3_hrs'+user1.username, float(a), 1800) print("User l3 hours are {}".format(a)) return user_L3_hrs def TotUserL3Mined(user1): # a = 0.0 # l3_total = request.user.L3s.all() … -
How can I add the `order_status_count` to as the same level as the `results` list?
I want to add the order_status_count to as the same level as the results list: I tried bellow code: serializer: class OrderFilterSerializer(ModelSerializer): order_type = serializers.CharField(write_only=True, allow_null=True) order_user_name = serializers.SerializerMethodField() order_status_count = serializers.SerializerMethodField(read_only=True) def get_order_status_count(self, order): ..... return order_status_count view: class OrderSerializerListAPIView(ListAPIView): serializer_class = OrderFilterSerializer # pagination_class = OrderPageNumberPagination ..... But the bellow is like this: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 140, "next": "http://localhost:8000/api/abc/order/list/?page=2", "previous": null, "results": [ { "id": 1, "order_user_name": "test01", "order_status_count": { "paid_finished_count": 5, "paid_unfinish_count": 68, "unpay_count": 49 }, "order_num": "15108988238922", ..... }, ...... You see the order_status_count in every item now: "order_status_count": { "paid_finished_count": 5, "paid_unfinish_count": 68, "unpay_count": 49 }, This is not fit my envision. How can I add the order_status_count to as the same level as the results list? -
Does migrations directory in django project should be pushed to git repo?
In django project, when models changed the migrations file will be changed, if add migrations directory to git will raise conflict to others, if not add sometimes will raise server error when migrated. How do you solve this? -
Calling api from django view error. forbidden (csrf token is missing or incorrect)
I seen alot of other solution, tried it but problem still persist. When i do a requests.get, it works fine but when i'm doing requests.post. I got this forbidden (csrf token is missing or incorrect) error. Here is my code models.py class TestPost(models.Model): # reminderId = models.AutoField() book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) serializer.py class TestPostSerializer(serializers.ModelSerializer): # valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] # time = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True) date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p") class Meta: model = TestPost fields = ('id', 'book', 'author', 'date') views.py from django.http import HttpResponse import requests def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET) if r.status_code == 200: return HttpResponse('Yay, it worked') return HttpResponse('Could not save data') class TestPostViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = TestPost.objects.all() serializer_class = TestPostSerializer I did a POST method on the url of the function but error Forbidden (CSRF token missing or incorrect.): /test/ [22/Jan/2018 16:59:09] "POST /test/ HTTP/1.1" 403 2502 -
"http method not bound to view" when documenting class-based view in drf_yasg
Previously, I documented my function-based views like this: @swagger_auto_schema( operation_id='ChangePassword', methods=['POST'], request_body=ChangePasswordSerializer, responses={ '200': 'empty response body', }) def change_password(request): # code here We then switched our views to class-based, so I simply copy-pasted the documentation decorator over to the post method: class UserChangePasswordView(APIView): @swagger_auto_schema( operation_id='ChangePassword', methods=['POST'], request_body=ChangePasswordSerializer, responses={ '200': 'empty response body', }) def post(self, request): # code here However, on running this decorator, drf_yasg threw the exception File "/usr/local/lib/python3.6/site-packages/drf_yasg/utils.py", line 126, in decorator assert all(mth in available_methods for mth in _methods), "http method not bound to view" What is going on? What does this error message mean? -
Django generic date based views How to get the date lookup?
There is a function in a generic class based view called _make_single_date_lookup(self, date) def _make_single_date_lookup(self, date): """ Get the lookup kwargs for filtering on a single date. If the date field is a DateTimeField, we can't just filter on date_field=date because that doesn't take the time into account. """ date_field = self.get_date_field() if self.uses_datetime_field: since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(date + datetime.timedelta(days=1)) return { '%s__gte' % date_field: since, '%s__lt' % date_field: until, } else: # Skip self._make_date_lookup_arg, it's a no-op in this branch. return {date_field: date} I am interested in the lookup part: return { '%s__gte' % date_field: since, '%s__lt' % date_field: until, } How do you get access to the lookup for the month in a MonthArchiveView? -
Setting up Django on a clean VM: issue linking runserver to VM's ip
I'm setting up my Django site on a clean Ubuntu VM. Gone through the process of installing the necessary tools, I follow this tutorial and apart from the additional python packages I've added for my site it's the same process. According to this instructional guide to check whether everything is running smoothly you run python manage.py runserver 0.0.0.0:8000 and it should then run on the IP:8000 of the site. above is the instance of this running and this above shows the external ip of the google cloud instance running this. However when i try to visit http://35.227.49.155:8000/ I get This site can't be reached and it's double confirmed with no activity on the shell on a request picked up. -
How to create dynamic webscraper in Django using BeautifulSoup
I am trying to a dynamic webscraper using Django. I have a html button in which it has buttons so it is like when i will press the button it will start webscraper and will save the data into database and later on from another button i can download that data into CSV format. Now I have prepared the html page for buttons. I have written webscraper script and in my views.py i have imported that scraper file and called that function but when i type python manage.py runserver scrapers starts but my web page is not reachable. First how can i solve this problem. Second how can i connect my scraper with the html button Third how i can save the data into database Fourth how can i download them into csv when i press the button Below is my Views.py from django.shortcuts import render from django.conf.urls import url from django.conf.urls import include from django.http import HttpResponse from bs4 import BeautifulSoup import requests import Up# this is the web scraping file # Create your views here. #def index(request): # first = {"here":"will enter more details"} # return render(request, "files/first-page.html", context=first) #return HttpResponse("<em>Rera details will be patched here</em>") #uncomment this … -
Django, inline and nested, formsets in a single form
A part the broader problem of a great and mature framework not fully complete at some of its edges ( but this is mostly a rant...), my current issue is not with inline formsets but with inline nested formsets. For example: 1) a warehouse registration heading, with: number, date, type, etc. 2) several related articles (1 to many), with: code, upload/download flag; 3) several line items related to the article (1 to many): quantity, volume of container, identification of container, etc. So two levels of relationships to be maintained through a single form, that is: created and updated. Should I keep trying with something like: https://www.yergler.net/2013/09/03/nested-formsets-redux/, which the author itself warns to be careful at, or should I think of implementing just this form in Vue, let’s say, and use Django only as a backend engine? -
Replicate databases within AWS RDS
I have two database (db1) and (db2) created in one Postgres RDS, Is it possible to configure one as master and another as a slave to replicate data. -
Fields not sent in POST for ModelForms are overwritten as blank values
Just realised that we have been silently losing data on our web platform because some of the fields in the ModelForm are hidden in some contexts and not being sent in the POST request. As a result, these fields were being overwritten as blank values and erasing the previous value. (Thank God, we use django-reversion to track changes, though we need to spend some time to recover the data). I saw this old post on django-developers group that discusses exactly this issue. Has anyone been able to figure out a good work around for this yet (apart from not using Model Forms) so that fields that are not sent in the POST request in ModelForms remain untouched? (Note that we do need these fields in the Meta class in the ModelForm since they are used in some contexts but not all) -
Django in shared hosting/cpanel
hey guys i have the issue with my django app so what should i do?i have shared hosting account on which i am trying to upload my django app, please help this is the code of .htaccess file DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/dasawork/store" PassengerBaseURI "/test" PassengerPython "/home/dasawork/virtualenv/store/3.5/bin/python3.5" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END it worked at night first and then in the morning it wasn't working and giving the error "/home/dasawork/public_html/test/.htaccess: Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration". hosting providers changed my root dir name! like when it worked it was "'/newhome/dasawork/...." but on the morning it was changed to "/home/dasawork/..." so can this cause the problem ? please help -
How to make loop variables accessible from block-endblock
I am trying to write code for the index page of a blogging site. The index page will fetch blog title, date, author details and blog content and put it on the index page. I am having an issue making jinja2 templates work for this. Here is my base.html templates, which will be used site wide. <head> <meta charset="UTF-8"> <link type="text/css" rel="stylesheet" href="{{ static ('css/style.css') }}"/> <title>{% block title_block %}{% endblock %}</title> </head> <body> <div class="jumbotron"> <div class="container-fluid"> <div class="row"> <div class="col-2"> </div> <div class="col-10"> <h3 class="hdr hrborder">{% block posttitle scoped %}{% endblock %}</h3> </div> </div> <div class="row"> <div class="col-2 vrborder text-right"> Published: {% block postdate %}{% endblock %} Author: {% block postauthor %} {% endblock %} </div> <div class="col-10"> {% block postcontent %}{% endblock %} </div> </div> </div> </body> And here is the child template {% extends 'core/base.html' %} {% block title_block %} Blogs {% endblock %} {% for post in posts %} {% block posttitle scoped %}{{ post.post_title }}{% endblock %} {% block postdate scoped %}{{ post.post_date }}{% endblock %} {% block postauthor scoped %}{{ post.post_author }}{% endblock %} {% block postcontent scoped %}{{ post.post_content }}{% endblock %} {% endfor %} But this is not workin. I am … -
Django. Error in "create_superuser()"
I got error when i trying to create "super user" by "manage.py createsuperuser". Traceback: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() got an unexpected keyword argument [model.py] from time import timezone from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class TemporaryBanIp(models.Model): class Meta: db_table = "TemporaryBanIp" ip_address = models.GenericIPAddressField("IP адрес") attempts = models.IntegerField("Неудачных попыток", default=0) time_unblock = models.DateTimeField("Время разблокировки", blank=True) status = models.BooleanField("Статус блокировки", default=False) def __str__(self): return self.ip_address class TemporaryBanIpAdmin(admin.ModelAdmin): list_display = ('ip_address', 'status', 'attempts', 'time_unblock') search_fields = ('ip_address',) class AuthUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, patronymic, birth_day, inn_id, passport_s, passport_n, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=AuthUserManager.normalize_email(email), username=username, last_name=last_name, first_name=first_name, patronymic=patronymic, birth_day=birth_day, inn_id=inn_id, passport_s=passport_s, passport_n=passport_n, ) user.is_admin = True user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, patronymic, birth_day, inn_id, passport_s, passport_n, … -
Run program on server forever without manually starting it
I have created an application which resides on a server. The application uses Django to connect. So, if I want to access the web page I have to run the following command to start the server - python manage.py runserver ip adress:port number What is the way to keep it running all the time even after shutting down my computer? -
django no module name 'config'
I wrote these apps using python2 and now am using python 3. I've tried: 1) Changing to a new virtualenv and reinstalling requirements 2) pip install config -> returns a new Syntax error in an Exception... 3) pip install django-config 4) I keep getting the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' I'm really stuck because i can't run these project that … -
How to synchronise algolia with database only when deleteing, adding and updating model instance
According to algoliasearch-django document: 'AUTO_INDEXING: automatically synchronize the models with Algolia (default to True).' For my understand, if I set AUTO_INDEXING to True, whatever I update a model instance or update model (e.g. add a new field), it will synchronise Algolia with my own database (or model). However, what I want to do is synchronise Alogolia on demand, for example, only synchronise them when a model instance is change, added or deleted. Are there any way to implement this? Thanks. -
Make detail page for each A/B test experiment result
I have been making A/B testing system using Django and dashboard using django controlcenter. Now I have a dashboard page including results of all active experiments. What I want to do is spliting a dashboard page for each experiment. I have tried a way using urlpatterns = [url(r'^admin/dashboard/mydash/(?P<exp_id>[0-9])/$', views.exp_dashboard), ] in urls.py and def exp_dashboard(request, exp_id): exp = get_object_or_404(Experiment, pk=exp_id) exp = Experiment.objects.get(pk=exp_id) return HttpResponse('experiment %s'%exp_id) in views.py But I do not know how to return dashboard page from exp_dashboard, not returning HttpResponse as usual. Do you have any advice to do this?