Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework APi return value from function
I use the Django Rest Framework to create a little API. This is my current views.py: from django.shortcuts import render from django.http import HttpResponse from rest_framework.renderers import JSONRenderer from rest_framework.decorators import api_view from .models import Repo, Category from .serializers import repoSerializer, categorySerializer, releaseSerializer # Just wraps a simple HTTP Response to a JSON Response class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def index(request): return HttpResponse("<h3>Welcome to DebGen API v1.0</h3>") @api_view(['GET']) def repos(request): repos = Repo.objects.all() serializer = repoSerializer(repos, many=True) return JSONResponse(serializer.data) Now I added this part: @api_view(['GET']) def random(request): return JSONResponse(random()) But when I call this part in the API, I get this error: TypeError at /api/random/ view() missing 1 required positional argument: 'request' So what can I do show the random number in the API call? -
RuntimeError: Model class products.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Mac OS Python 3.7.3 Django 2.0.7 I'm trying to import in Ipython, this happens: (trydjango) (base) MacBook-Pro:src qizhilin$ python manage.py shell Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from products.models import Product Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/qizhilin/Dev/trydjango/src/products/models.py", line 4, in <module> class Product(models.Model): File "/Users/qizhilin/Dev/trydjango/lib/python3.7/site-packages/django/db/models/base.py", line 108, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class products.models.Product doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I've searched Stackoverflow, a lot of people mentioned add to INSTALLED_APPS but I have it already. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party # own 'pages', 'products', ] what should i do? here's some (maybe)relevant code, if helps: admin.py: from django.contrib import admin # Register your models here. from .models import Product admin.site.register(Product) apps.py: from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py: from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length = 120) #max_length = required description = models.TextField(blank=True,null=True) price = models.DecimalField(decimal_places=2,max_digits=1000) summary = models.TextField(blank=False,null=False) featured = models.BooleanField() # null=True, default=True -
Why heroku saying couldn't find that app even when the build is successful?
I am trying to deploy my django app on heroku. I created an app, connected my app with github, selected automatic deploy and then manually deployed from my github master branch. The activity saying build successful and deployed. But whenever I'm trying to open the app it is raising an error. When I'm checking my logs it is saying "Couldn't find that app" My build log: -----> Python app detected -----> Clearing cached dependencies -----> Installing python-3.6.10 -----> Installing pip -----> Installing SQLite3 Sqlite3 successfully installed. -----> Installing requirements with pip Collecting django==3.0.4 Downloading Django-3.0.4-py3-none-any.whl (7.5 MB) Collecting folium==0.10.1 Downloading folium-0.10.1-py2.py3-none-any.whl (91 kB) Collecting pandas==1.0.3 Downloading pandas-1.0.3-cp36-cp36m-manylinux1_x86_64.whl (10.0 MB) Collecting pytz Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) Collecting asgiref~=3.2 Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting branca>=0.3.0 Downloading branca-0.4.0-py3-none-any.whl (25 kB) Collecting numpy Downloading numpy-1.18.2-cp36-cp36m-manylinux1_x86_64.whl (20.2 MB) Collecting requests Downloading requests-2.23.0-py2.py3-none-any.whl (58 kB) Collecting jinja2>=2.9 Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB) Collecting python-dateutil>=2.6.1 Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting six Downloading six-1.14.0-py2.py3-none-any.whl (10 kB) Collecting certifi>=2017.4.17 Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB) Collecting chardet<4,>=3.0.2 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 Downloading urllib3-1.25.8-py2.py3-none-any.whl (125 kB) Collecting idna<3,>=2.5 Downloading idna-2.9-py2.py3-none-any.whl (58 kB) Collecting MarkupSafe>=0.23 Downloading MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl (27 kB) Installing collected packages: pytz, asgiref, sqlparse, django, … -
Using sendgrid api I am getting a getaddrinfo error?
guys, I have to build a simple contact form in django,I have done that job a thousand times before but today it's giving me a wierd error. I tried to do def post(self,request,*args,**kwargs): request_data = request.POST message = Mail( from_email="from_email@gmail.com", to_emails='to_email@gmail.com', subject='Email recieved from salesproject', html_content="hey what's up") sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) This is an integration test that SendGrid gives us, this doesn't require us to use email_host and other stuff... After doing it I'm now getting this weird error. Traceback (most recent call last): File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "D:\projects\python\salesproject\app\views.py", line 55, in post response = sg.send(message) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\sendgrid\sendgrid.py", line 98, in send response = self.client.mail.send.post(request_body=message.get()) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\python_http_client\client.py", line 262, in http_request self._make_request(opener, request, timeout=timeout) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\python_http_client\client.py", line 174, in _make_request return opener.open(request, timeout=timeout) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 526, in open response = self._open(req, data) File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 544, in _open '_open', … -
PUT and PATCH request on same api in django rest framework
i am creating a crud where user can update data using put request and he can also update only particular column that i was trying to integrate with PATCH method but it updates all data Is there any example or documentation which i can refer to do this. -
How to pass argument to form in updateview?
I want to use UpdateView in my model Event. This model had this field: employee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='event_employee') My view : class UpdateEvent(UpdateView): model = Event template_name = 'dashboard/pro_update_event.html' form_class = UpdateEventForm other_variable = None def get_form_kwargs(self): kwargs = super(UpdateEvent, self).get_form_kwargs() names_clients = Particulier.objects.filter(professionnels=self.request.user) kwargs.update({'names_clients': names_clients}) return kwargs def get_success_url(self, *args, **kwargs): return reverse_lazy('pro_details_event', kwargs={'pk': self.object.pk}) My Form : class UpdateEventForm(forms.ModelForm): """ edit an event """ class Meta(): model = Event fields = ('employee', 'date_start', 'date_end') def __init__(self, names_clients, *args, **kwargs): super(UpdateEventForm, self).__init__(*args, **kwargs) self.fields['employee'] = forms.ChoiceField(choices=tuple([(client.pk, client) for client in names_clients])) It seems work, the widget "select" contain the correct values. example : <option value="2">Dupond Jean</option> But when I submit the form : Cannot assign "'2'": "Event.employee" must be a "User" instance. I don't understand because if remove "get_form_kwargs" in my view and "def init" in my form, the value passed is the same (the pk of the employee). It's works with this way. But the problem is all employee are selectable and the username is display not the firstname and lastname. -
How to define django app specific exception handler
For my django app I am creating a custom exception handler as defined in https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling Is there a way to define REST_FRAMEWORK variable in some app specific settings file instead of global settings.py -
Develop a DIY video creator
I want to develop a video creator using Python (Django). I am not sure about the packages to be used. I tried working with moviepy but it did not satisfy all the requirements Inputs : Text Images Expected output: The text entered must be converted to voice with the slideshow of images which should be exported to mp4. The text should be flexible with the duration and position with the images -
Django parse date to dd-mm-yyyy in QuerySet
I have the following QuerySet to retrieve all dates with a count of records out of a MSSQL database. def get_amount_per_day(self): return self.extra(select={'time': 'CONVERT(DATE, starttime)'}).values( 'time').annotate(amount=Count('starttime')).order_by('time') The output is: { "time": "2019-03-07T00:00:00", "amount": 216 }, { "time": "2019-03-07T01:00:00", "amount": 178 } } But I want to parse the date to 07-03-2019, does anyone kwow how I can achieve this? I tried to convert the date to varchar but then the order_by doesn't work correctly. It has to be of type DATE. -
Django channels and nginx - error during handshake
I'm trying to deploy a Django/Django Channels application to a VPS. The django part of the project works, i can visit any url and the templates are loading, but the Django Channels part of it doesn't work. Whenever i try to reach the websocket i either get connection refused or WebSocket connection to 'ws://54.39.20.155/receiver' failed: Error during WebSocket handshake: Unexpected response code: 404 Can someone help me find what i'm doing wrong and tell me what do i need to do in order to run Django Channels? Here is my setup: Environment: virtualenv django django-channels gunicorn nginx systemd /etc/nginx/sites-available/myproject server { listen 80; server_name 54.39.20.155; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { include proxy_params; proxy_pass http://unix:/WaitingRoomVenv/WaitingRoomEnv.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/WaitingRoomVenv/WaitingRoomEnv.sock WR.wsgi:application [Install] WantedBy=multi-user.target To start gunicorn: sudo systemctl start gunicorn To start nginx: sudo systemctl restart nginx -
Access a table C from table B which are unrelated but hava a common related table A in Django ORM
class A(models.Model): product=models.CharFiels(...) class B(models.Model): product = models.ForeignKey(A) b_name = models.CharFiels(...) class C(models.Model): product = models.ForeignKey(A) c_name = models.CharFiels(...) I want to access name in table B from table C having a product id as per the filter in C: something like this: objC = C.objects.filter(c_name="abc").values('product_id').first() respective_name_in_B = B.objects.filter(product_id = objC['product_id']).values('b_name') How can i achieve the same output in Django ORM using one query(as here I have to use two queries), hitting the database once. -
How to pass argument from previous View to a Form?
Im trying to pass the "test" argument from this View to a Form: class ListCreateFormView(CreateView): template_name = 'armybuilder_list_create.html' model = List form_class = CreateListForm def form_valid(self, form): form.instance.author = self.request.user self.test = Faction.objects.get(title="Blood Angels") return super().form_valid(form) def get_success_url(self): return reverse_lazy('add_unit_to_list', kwargs={'pk': self.object.pk, 'test': self.test.id}) To this View and Form: class AddUnitsToListFormView(LoginRequiredMixin,CreateView): model = SoldierToList form_class = SoldierToListForm template_name = 'armybuilder_add_unit_to_list.html' def form_valid(self, form): form.instance.author = self.request.user form.instance.list_id = self.kwargs['pk'] return super().form_valid(form) class SoldierToListForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # factions_obj = Faction.objects.get(pk=my_test) self.fields['soldier'].queryset = Soldier.objects.filter(factions=4) class Meta: model = SoldierToList fields = ('soldier',) Im hardcoding the value 4 in my form but I would like to use the argument test that I defined in the previous View ListCreateFormView, can you please tell me how to do it ? Thanks -
I start coding with Django and I want to using input from page1 into page 2. How to do that ? and I want to export it to pdf file as well
I have a Document page that user need to input there information (like ERP) and export it into an Export page to pdf format -
How do you set a default value for django-filter select field instead of a blank field?
I'm using the django-filterapp to filter items on my front end and i can't seem to understand how to populate the first value on my dropdown select field with a default value instead of the blank -------- space on the field, its really bad for user experience since im not using labels and therefore users wont be able to identify a field without a placeholder of some sort. Here is what i'm getting. -
Integration of video calling functionality with Django and Django Channels
I have created a chat application with Django using Django-Channels, but for enhancement I want to add video calling functionality as well. I'm not getting any Idea how i can achieve this task. Please provide me some references so that i can implement it. Currently after searching the only option I'm getting is WebRTC. But there is not proper documentation of it's interrogation with Django. -
Why am I not being able to save my addresses? django/ajax
I'm trying to develop an e-commerce website with django. I want to use ajax to handle my checkout form. When I added Ajax, after filling out the form and clicking the submit button, I am seeing that my form and data is not getting saved by going into my admin. It's also not being redirected to return HttpResponseRedirect(reverse(str(redirect))+"?address_added=True"), rather it's being redirected to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=u6hDPBVuOZbDmoHvRFWb2PvfK1YamCIKGSaDkKdVTviWvJODgY5lM6rKppoW1oeP&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on. Can anyone please help me out with what's wrong? My accounts.views.py: from django.shortcuts import render, HttpResponseRedirect, Http404 from django.contrib.auth import logout, login, authenticate from django.contrib import messages from .forms import LoginForm, RegistrationForm, UserAddressForm from django.urls import reverse def add_user_address(request): try: redirect = request.GET.get("redirect") except: redirect = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if redirect is not None: return HttpResponseRedirect(reverse(str(redirect))+"?address_added=True") else: raise Http404 My urls.py: path('ajax/add_user_address/', accounts_views.add_user_address, name='ajax_add_user_address'), My checkout.html: <form method="POST" action="{% url 'ajax_add_user_address' %}?redirect=checkout"> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-dark" type="submit">Place Order</button> </div> </form> -
Which is the best way to make backend for a small website? [closed]
Good afternoon! I'm currently working on a website, and front end is mostly done, now i want to implement authorization form. I got curious which way is better, i want to make a a back end system on a virtual machine using ubuntu. I just thinking which environment is better for simple website. I'm thinking of nodejs since i was using it for some API's or to use Python + Django. MongoDB as a database. Is there any resources that i can look into how to connect back end with front end when back end on virtual machine? And is it good way of doing it? Or better to do back-end internal? -
Djongo Using ArrayField throws Apps No Loaded Error on makemigrations
I am trying to create a django model using djongo which uses ArrayField class SubModel(models.Model): i = models.IntegerField() class Meta: abstract = True class BiggerModel(models.Model): subarr = models.ArrayField(model_container=SubModel) When I run makemigrations, I get the error AppRegistryNotReady("Models aren't loaded yet.") This is happening only if I use ArrayField. Not with any other fields I am using django 2.1.5 and djongo 1.3.2 -
Django Psycopg2 Error When Running Migrations in Testing
I developed a basic version of a Django app in SQLite3. Then, it came time to switch it to Postgres and put in production. When doing so, I noticed that I was able to create and run migrations for the new database. However, when trying to run tests for the Postgres version, I run into an issue. Here it is. I run tests with coverage run --source='.' manage.py test; however, the same thing happens when running via python manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "test_app_web" already exists Type 'yes' if you would like to try deleting the test database 'test_app_web', or 'no' to cancel: yes Destroying old test database for alias 'default'... Creating test database for alias 'extra'... Traceback (most recent call last): File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column aldryn_people_person.name does not exist LINE 1: SELECT "aldryn_people_person"."id", "aldryn_people_person"."... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/base.py", line … -
Django does not find static on all pages except the main
The project is hosted (support say to solve the problem yourself and therefore my friends hope for your help) and you can find it at: https://caparolcenterspb.ru All styles, pictures and js appear on the main page, but not on other pages. You can see the errors directly in the browser, but just in case I give a screen: -
How to measure latency of API calls?
I am building an API with Django. And I need to record the time it takes each user to ping the nearest server. The users communicate with the API through an Android app. The app uses a load balancer that assigns the user to the nearest server. I know that it's possible to ping the server with a computer to get the RTT, but I cannot find a way to get latency from an arbitrary user, which can only communicate with the server using the app. -
how to fetch data from database in django using phpmyadmin
model.py from django.db import models class Reg(models.Model): First Name = models.CharField(max_length=10) Email ID = models.CharField(max_length=20) TUID = models.CharField(max_length=10) Password = models.CharField(max_length=8) how to fetch data from database without using underscore in first name -
How to get fields of foreign key
In models.py: class Comment(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField() rating = models.FloatField(null=True) aggregate = models.FloatField(null=True) date = models.DateTimeField(auto_now_add=True) class Item(models.Model): id_item = models.AutoField(primary_key='true') item_name = models.CharField(max_length=100, null=False) slug = models.SlugField(max_length=250, blank=True, null=True) item_description = models.TextField() item_img = models.ImageField(blank=True, null=True, upload_to="static/item/cover/") tags = TaggableManager() In views.py: def detail(request, slug_text): details = Item.objects.filter(slug=slug_text) if details.exists(): reviews = Comment.objects.filter(item=slug_text) details = details.first() average = reviews.aggregate(Avg("rating"))["rating_avg"] average = round(average, 2) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST, author=request.user, item=details) if form.is_valid(): form.save() return HttpResponseRedirect(slug_text) else: return HttpResponse('<h1>Trang không tồn tại</h1>') return render(request, 'homepage/detail.html', {'detail': details, 'form': form, 'average': average}) What if I want to get the item.slug = slug_text field in here? reviews = Comment.objects.filter(item=slug_text) -
TypeError at /gym/ninja/ninja() got an unexpected keyword argument
actually i am trying to sumbit the details from my contact from to them of my django app but i am facing same error with all the varriable i am am able to get the details from my html page and can print it in my vs code cmd but when i try to save it in my model i face same error for all variable so please can anyone help me with it enter code here html code <form method="POST" action=""> {% csrf_token %} <div class="container"> <div class="form-row"> <div class="col"> <label for="inputEmail1">E-mail</label> <input type="text" class="form-control" name="emails" id="emails" placeholder="Enter your E-mail"> </div> <div class="col"> <label for="inputEmail2">Phone-Number</label> <input type="text" class="form-control" name="phones" id="phones" placeholder="Enter your phone number"> </div> </div> <div class="form-row"> <div class="col"> <label for="inputEmail1">Age</label> <input type="text" class="form-control" name="ages" id="ages" placeholder="Enter your age"> </div> <div class="col"> <label for="inputEmail2">Height</label> <input type="text" class="form-control" name="height" id="height" placeholder="Enter your height"> </div> </div> <div class="form-row"> <div class="col"> <label for="inputEmail4">Weight</label> <input type="text" class="form-control" name="weight" id="weight" placeholder="Enter your weight"> </div> <div class="col"> <label for="inputEmail3">Food Habit</label> <input type="text" class="form-control" name="habit" id="habit" placeholder="Are you veg/non-veg/vegan"> </div> </div> <br> <div class="form-group"> <label for="exampleFormControlTextarea1">Enter other important detail's</label> <textarea class="form-control" placeholder="Enter your message here....." id="messagess" name="messagess" rows="5"> Submit </form> my model that i have … -
proper name for custom User and Manager in Django
In my django project I've created a customized models for User and its manager class. I named them User (which inherits from AbstractUser) and UserManager (which inherits from BaseUserManager). Given that these are the default django's name for those models, is there any problem in that? I run the following form django shell: >>>from django.contrib.auth import get_user_model >>>user = get_user_model() >>>user.objects These are the outputs: <class 'myapp.models.models.User'> <class 'myapp.models.models.UserManager'> Apparently no conflicts are shown, so it seems to be all right. I hope some django experts could confirm me I won't have any surprise later on through the development.