Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models relation with primary key add extra "_id" to the column
these are my two data tables, when I try to open City page on Django I got an error called : "column city.country_id_id does not exist". I dont know why python add extra _id there.. country_id = models.CharField(primary_key=True,max_length=3) country_name = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'country' class City(models.Model): city_id=models.CharField(primary_key=True,max_length=3) city_name=models.CharField(max_length=30, blank=True, null=True) country_id = models.ForeignKey(Country, on_delete=models.CASCADE) class Meta: managed = False db_table = 'city'``` [enter image description here][1] [1]: https://i.stack.imgur.com/Shj7x.png -
Django Rest Framework - Search Filter, How to use FilePathField with Serializer
I am using multiple fields for the search filter including a FilePathField as below : class Entity(models.Model): uuid = models.CharField(max_length=255, default="") description = models.CharField(max_length=255, default="") file = models.FilePathField(blank=False, max_length=1000, null=False) segment_start = models.PositiveIntegerField(default=0) class EntitySearchFilterSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ('uuid', 'description', 'file', 'segment_start', ) class StandardResultsSetPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'page_size' max_page_size = 1000 class EntitySearchList(generics.ListAPIView): model = Entity serializer_class = EntitySearchFilterSerializer queryset = Entity.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['description', ] pagination_class = StandardResultsSetPagination However, I see the following error when I introduce the FilePathField only. [19/Mar/2020 19:14:37] "GET /api/search/entity/?search=cat HTTP/1.1" 500 20295 Internal Server Error: /api/search/entity/ Traceback (most recent call last): res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py", line 363, in fields for key, value in self.get_fields().items(): File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py", line 1072, in get_fields fields[field_name] = field_class(**field_kwargs) File "/usr/local/lib/python3.6/dist-packages/rest_framework/fields.py", line 1535, in __init__ allow_folders=allow_folders, required=required File "/usr/local/lib/python3.6/dist-packages/django/forms/fields.py", line 1109, in __init__ for f in os.scandir(self.path): FileNotFoundError: [Errno 2] No such file or directory: '' What could be the reason for this ? -
Getting Started on Heroku with Python, Django - "Application Error"
I have been following this article https://devcenter.heroku.com/articles/getting-started-with-python I successfully did everything up until pushing local changes -> https://devcenter.heroku.com/articles/getting-started-with-python#push-local-changes I managed to run it on localhost and to display the teapot, I then did the following: git add . git commit -m "Demo" git push heroku master and finally when I run heroku open The website doesn't open anymore. It tried for 30 seconds and then comes with this message: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail I have no idea what I'm doing reading the logs, as I have no idea what any of it means. The errors that I can see are the following: 2020-03-19T19:13:32.915941+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/" and then x3 2020-03-19T19:13:53.251678+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" I don't know how to proceed from here. -
How to test uploading pdf file with APITestCase in Django Rest Framwork
from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse from rest_framework.test import APITestCase class BrokerTest(APITestCase): broker_url = reverse('user_registration', kwargs={'user_type': 'broker'}) @staticmethod def company_information(username, email, phone_number="+905380706512", file=None): company_valid_data = { "user": { "username": username, "first_name": "Tom", "last_name": "Jerry", "phone_number": phone_number, "password": "deneme123", "email": email }, "company": { "mc_number": 1234, "company_name": "Example Company", "file": file, } } return company_valid_data def setUp(self) -> None: file = SimpleUploadedFile('file.docx', b"file_content", content_type="documant/docx") self.broker_valid_data = self.create_broker_information(username='deneme', email='deneme12@gmail.com', file=file) def test_create_broker(self): responce = self.client.post(self.broker_url, self.broker_valid_data, format='json') //400 Bad Request !!!! self.assertEqual(200, responce.status_code) -
aiohttp network call is taking too much time within a django view
So, I wanted to build an api that takes a bunch of domains and used a third part api to fetch information regarding them and send the result to frontend. As i wanted the response time of api to be faster which constitutes of multiple network calls, sync way was not possible. So in my api i divide the domains in batch of certain size, call a celery task on each batch, celery task perform multiple network calls using asyncio and aiohttp. My code is : The api endpoint is : class BulkDomainCheckerView(APIView): def post(self, request): domains = request.data.get("domains") from math import ceil from itertools import islice num_domains = len(domains) Inputt = iter(domains) # slicing domains in 500 size batch domain_lists = [list(islice(Inputt, 500)) for e in range(ceil(num_domains / 500))] total_go_daddy_batch_size = len(domain_lists) Inputt = iter(domain_lists) # Make again a batch of size 5 of those batches in domain_lists domain_lists = [list(islice(Inputt, 5)) for e in range(ceil(total_go_daddy_batch_size / 5))] i = 1 for domain_batch in domain_lists: start = time() check_domain_avalaibality_async.apply_async([domain_batch, i, start], queue='celery_default_tools') i = i + 1 return success_response(status=HTTP_200_OK, msg="", data=[]) Celery Task: @app.task def check_domain_avalaibality_async(domain_batch, batch, start): asyncio.run(fetcher(domain_batch, batch)) Async code: async def fetch(session, domains, idx, batch): t … -
YearArchiveView.date_field is required. ImproperlyConfigured
I open up the documentation to Django. I try to use the (YearArchiveView) view. when I go through the URL index/2020/ I get this error( YearArchiveView.date_field is required. ) what I understand that I have to use the attribute that called date_field and I already use. so, how can I fix that error? also, I need to know how can I access on this URL by any link into another page?, like from index.html views.py from django.shortcuts import get_object_or_404, Http404, render_to_response from django.views.generic import ListView, DetailView from .models import Article, User from .forms import ContactForm from django.views.generic.edit import FormView from django.urls import reverse_lazy from django.views.generic.dates import ArchiveIndexView, YearArchiveView class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.all() template_name = 'index/article_archive_year.html' date_field = "date" allow_future = True urls.py from . import views from django.urls import path urlpatterns = [ path("<int:year>/", views.YearArchiveView.as_view(), name="article_archive_year") ] artcile_archive_year.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Archive year</title> </head> <body> {% for date in date_list %} <li>{{ date|date }}</li> {% endfor %} </body> </html> -
Is there some way to "lock" page in case another user is editing - DJANGO
I need some help. I got a page and I can switch it to another view where I got a form and I can change some texts on that page and save it. Is there any way how to lock/hide button if some user is editing, so another user can not access the editing form page and is only allowed to see the "view" of the page. I want to implement, so two users will not be able to edit page at the same time. I was trying to find something on the internet but I did not found anything useful for DJANGO. Thanks a lot for some recommendation how to do it. -
argparse library conflict between Django and Google Cloud SDK - how to resolve
I am trying to run my Django app in PyCharm and getting the following error: TypeError: __init__() got an unexpected keyword argument 'allow_abbrev' (This only occurs when I run it from the 'Run' menu in PyCharm, not from the terminal). The error comes from django.core.management.base.py. The CommandParser class in there inherits from ArgumentParser, but the interpreter is mixing up the standard from argparse import ArgumentParser, which does have the keyword argument allow_abbrev, with the ArgumentParser in the Google Cloud SDK, which doesn't have the argument allow_abbrev. I believe this only started when I upgraded the Google Cloud SDK tools. I am running a virtual environment with a recent version of Python but I am confused as to how it is picking up Google's ArgumentParser instead of the one Django is expecting. -
django gunicorn app spams the console with "Not Found: /api/templates/menu_main/" every second or so
I've built a simple django app and I'm working on dockerizing it. I'm able to create the image and start it. It even works fine locally via "docker run -it -p 8000:8000 project:0.1". However, the project logs this message to the console about every seconds or so: Not Found: /api/templates/menu_main/ I don't have a rest api or anything in the app, just a couple tables and several views. Here's requirements.txt: beautifulsoup4==4.8.2 certifi==2019.11.28 chardet==3.0.4 Django==2.0.7 django-auth-ldap==2.1.0 django-background-tasks==1.2.5 django-bootstrap4==1.1.1 django-compat==1.0.15 django-phone-field==1.8.0 gunicorn==20.0.4 idna==2.9 mysqlclient==1.4.6 psycopg2==2.8.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 PyJWT==1.7.1 python-ldap==3.2.0 pytz==2019.3 requests==2.23.0 six==1.14.0 soupsieve==2.0 twilio==6.36.0 urllib3==1.25.8 whitenoise==5.0.1 Googling for the error message didn't reveal anything that I could act on. Any idea what the message means? How do I stop it from filling up the logs? Thank you! -
filters inside django trans tag : first translates then applies filters; unlike other tags
I encountered a weird behavior from django trans tag. As you know whenever we use a filter inside a tag, the filter first applies and then gives the result as input to the tag. But this is in reverse order for trans tag. Example: Suppose I have this django.po file: msgid "msgid-world" msgstr "world" msgid "msgid-" msgstr "message" Now see the result of these tags: {% trans "msgid-"|add:"world" %} result: messageworld (first translate then concat) Expected result: "world" (first concat then translate the key) -
Can I use the field of a related model in a Django UniqueConstraint?
Is it possible to make a UniqueConstraint using the field of a foreignkey model? For example, how could I constrain all books written by authors of the same age to have a unique title? (A contrived example, but you get the idea.) models.py: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Book(models.Model): class Meta: contraints = [ models.UniqueConstraint( # THIS DOESN'T WORK fields=["author__age", "title"], name="my_constraint", ) ] title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name="books") This gives the following error: django.core.exceptions.FieldDoesNotExist: Book has no field named 'author__age ' -
NameError at /register/ name 'user' is not defined
I am currently developing a blogging webapp and I tried to extend my Django User Framework With a One To One Field, everything is working fine, but when I'm trying to register a new user, it's throwing a NameError. It is also worth noting that the user is being created and stored(I checked it from the admin page). It is saying that this statement profile.user = user in my views.py is creating the problem. Can anyone please help me with this? my views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() profile_form = ProfileForm return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form}) @login_required def profile(request): return render(request, 'users/profile.html') my models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') CHOICES = ( ('AB+', 'AB+'), ('AB-', 'AB-'), ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), … -
Pass query and html from views to modal popup
I have background page: views: @login_required def dashboard(request): return render(request, 'app/dashboard.html') and html: {% extends 'app/basenobar.html' %} {%load staticfiles %} <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> {% block content %} <body> <a href="#" id="winOpener2">Open PopUp</a> <div id="window2" title="Test Window"> {% for member in family %} {{ member.pk }} {% endfor %} </div> Now, if I click on the button it open popup and everything work but I need to pass a query from view to popup body For example, I have a query in a view: @login_required def myquery(request): family = Books.objects.all() return render(request, 'app/myquery.html', {family:'family'}) and I need to pass this values inside my popup when I click for open it. Any idea? -
UML association class and OOP languages
I am building a web application with Django, I did the design app with UML2. i read that association class concept does not exist in object oriented programming languages, is that true ?? thank you. class diagram -
Django autocomplete-light
I have used autocomplete-light in my django form to fetch the names from person table. Also I have to create the new person record, when ever the name I search for does not exist. This works fine for me. Now I want to add some more additional details(ideally with a new window to fill details) for the person as a input from the users when ever they select the option to create new users . enter image description here -
What is the meaning of "=" when specifying a superclass in Python?
I have a question about the class definition below. In case it's relevant, the full code can be found here, and the class I stubbed out can be found on line no. 98. class BaseModelAdmin(metaclass=forms.MediaDefiningClass): pass I understand that BaseModelAdmin is extending forms.MediaDefiningClass, but what is the significance of metacalass=? Specifically: What does the assignment operator do in this context? How is the l-value (i.e. metaclass) used? -
javascript , python online game comunication
I have one problem I am not able to find subtle model for the app so basically , I have a page where 2 people are looking for a game and then they have some challenge to do. I am using Django and Vue as stack. So my idea was when someone looking for the game put user username into redis queue and then take first two , but how I do return on the client side data back ,is there any smart way to make communication between two clients? -
Django/Postgres: Parameterized Queriy does not work
i have just started diving into raw queries in django. i am trying to change a schema name in my postgres, but my SQL query does not work here's the code that i run in django shell: >>> from django.db import connection >>> cursor = connection.cursor() >>> query = "ALTER SCHEMA %s RENAME TO %s;" >>> data = ('thor', 'thor1') >>> cursor.execute(query, data) Error: django.db.utils.ProgrammingError: syntax error at or near "'thor'" LINE 1: ALTER SCHEMA 'thor' RENAME TO 'thor1' i believe that those quotes are the root of my problem. any idea how can i make this work ? -
Django Admin Page on New/Chage display objects not values
I am create a simple model and admin in Django. Below is the model class Article(models.Model): title = models.CharField(max_length=30) tags = models.TextField(default="") text = models.TextField(default="") category = models.ForeignKey('cms.Category', default="") status = models.ForeignKey('cms.Status', default="") class Meta: verbose_name_plural = "Articles" And below the admin registration Class ArticleAdmin(admin.ModelAdmin): @staticmethod def get_status(obj): return obj.status.status @staticmethod def get_category(obj): return obj.category.category list_display = ('title', 'get_status', 'get_category') Although I am getting the below, i.e. objects not values. Snapshot from Django Admin I am trying to resolve this and I would like to know where to look for. Thanks a lot -
Django/Json: Can i easily change how django serializes objects?
I have Serialized and dumped my objects like this: data = serializers.serialize("python", MyObject.objects.all()) dic = { 'Studium' : data} return JsonResponse(dic, safe=False) The response I get: {"Studium": [{"model": "djangoApp.studium", "pk": 538, "fields": {"studiumkode": "ABIOK", "studium": "ABIOK (anestesi/barnevern/intensiv/operasjon/kreftsykepleie"}}]} The response I want: {"Studium": {"studiumkode": "ABIOK", "studium": "ABIOK (anestesi/barnevern/intensiv/operasjon/kreftsykepleie"}} -
What is the simplest way to get user input in Django?
I want to get some user input, process it a little and present the same to the user. I need not save the inout to the database. What is the simplest way to do that in Django -
Django - What are the cons of importing a library inside a view?
Currently in my app in certain views I want to get the ip, so I installed an external library. However, I have this doubt: The standard way of working in django is something like: from library import xyz from library2 import yzx def view1(request): #### def view2(request): #### but since I only want to get the ip in certain views, I thought of something like: def view1(request): from library impor xyz ### def view2(request): #### but I know that's not the standard way to do it. What inconveniences can this cause? Should I import the library of the standard way (at the beginning of all the views)? -
What's the main difference between using ./manag.py and python manage.py in a virtual environment
I couldn't execute ./manage.py makemigrations for a Django project. However, I could use python manage.py makemigrations and python3 manage.py makemigrations. I am using pipenv to manage my virtual environment, while doing the above operations, I already activated my virtual environment which installed all packages including Django. manage.py #!/usr/bin/python3 """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings.base') try: from django.core.management import execute_from_command_line # noqa except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Content after type python directly: Python 3.7.5 (default, Nov 20 2019, 09:21:52) [GCC 9.2.1 20191008] on linux Type "help", "copyright", "credits" or "license" for more information. >>> My question is what is the main difference bewteen using ./manage.py makemigrations and python manage.py makemigrations in an activated virtual environment? How to resolve this issue? Thanks for your help. -
Django all over sudden has refused to load static files
Django server was loading the static files successfully but all over sudden it has refused to load the files what might be the problem? i am using Django 2.2.1 and Python 3.6 -
How to handle multiple forms in one function in views in Django
I have to handle two forms in one function: HTML page <form name="selectgenderform" method = "POST"> <select name='gender'> <option>Male</option> <option>Female</option> </select> <input type = 'submit' name ='searchbtn' value= 'search' > </form> <form name="selectionform" method = "POST"> <input type = 'hidden' name = 'valueofnumber' > <input type = 'submit' name = 'searchbtn' value= 'search' > </form> Views.py def formselection(request): if selectgenderform in request.POST: gender = request.POST.get('gender') ... elif selectionform in request.POST: value = request.POST.get('valueofnumber') My query is to handle multiple forms in one function but this will not according to my demand