Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forwading ManyToMany model field in django-autocomplete-light
models.py class InvestmentGroup(models.Model): name = models.CharField(max_length=200, blank=True, null=True) persons = models.ManyToManyField('Person', blank=True, related_name='investment_groups') lead_investor = models.ForeignKey( 'Person', blank=True, null=True, on_delete=models.CASCADE, related_name='lead_investment_groups' ) forms.py class InvestmentGroupModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(InvestmentGroupModelForm, self).__init__(*args, **kwargs) class Meta: model = models.InvestmentGroup fields = '__all__' widgets = { "lead_investor": autocomplete.ModelSelect2( url="lead-investor-autocomplete", forward=["name"] ) } AutoCompleteview class LeadInvestorAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: return models.Person.objects.none() qs = models.Person.objects.all() persons = self.forwarded.get('persons', None) print(persons) # Output: [] if persons: qs = qs.filter(person__in=persons) return qs I am getting empty values if I forward many to many field like this but works for other fields like name or foreign keys. Is it possible to forward ManyToMany field? -
Pass searched query to another view
I am building a small and simple Question and Answer Web App and I am trying to implement a search page. I have successfully created a search page. When i search question title than results are showing fine below the search field. BUT I am trying to show the answers of the searched tag on another page. I am trying to put a link below all the results to show the answers of the searched query, but still unable to make it. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() class Answer(models.Model): answer_user = models.ForeignKey(User,on_delete=models.CASCADE) quest = models.ForeignKey(Question,on_delete=models.CASCADE) body = models.CharField(max_length=30) views.py def search(request): query = request.GET.get('q') answer = '' objs = '' if query: objs = Question.objects.filter(tags__name__icontains=query) answer = Answer.objects.filter(quest__tags__name__icontains=query) context = {'objs': objs,'answer':answer} return render(request, 'search.html', context) search.html <form action="{% url 'search' %}" method="get"> <input name="q" type="text"> {% for qas in objs %} {{ qas.title }} {% endfor %} {% for ans in answer %} {{ ans.ans }} {% endfor %} This view is showing answers in single page ( In searched pages ). I was thinking about creating a new view which will associate with the search view and will pass the … -
I need to override the save method for a specific model in django model(admin section)
I need to override the save method in the admin section. its related to documents. I need the save button to update some fields in database for me and beside that to send an email to the user that I have choosed .the model section is like this: class Documents (models.Model): applicant_email = models.EmailField(max_length=254) user_email = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) request_title = models.CharField(max_length=500) DOC_STATUS = ((0, 'Sent'), (1, 'Uploaded'), (2, 'Done')) request_status = models.SmallIntegerField(choices=DOC_STATUS) class Meta: verbose_name_plural = "Document Request" and here is the admin section: @admin.register(Documents) class DocumentsAdmin(admin.ModelAdmin): list_display = ('applicant_email','request_title', 'user_email','request_status') Where should I override the save method? in model section or in the admin part? and what's the code that do this? A complete and accurate answer would be appreciated. thanks -
Get all the data from model of searched tag on another page
I am building a Simple Question and Answer Web App and I implement a feature of search tags and it will show all the questions associated with it. And Now I am trying to show all the data of models in other page which is attached with that searched tag. Then I make a query of another model with searched tag but it is showing. Field 'id' expected a number but got 'first_post'. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() class Answer(models.Model): answer_user = models.ForeignKey(User,on_delete=models.CASCADE) quest = models.ForeignKey(Question,on_delete=models.CASCADE) body = models.CharField(max_length=30) views.py def search(request): query = request.GET.get('q') answer = '' objs = '' if query: objs = Question.objects.filter(tags__name__icontains=query) answer = Answer.objects.filter(quest=query) context = {'objs': objs,'answer':answer} return render(request, 'search.html', context) When i run this then it is showing Field 'id' expected a number but got 'first_post'. What i am trying to do :- I am trying to make a page of search and if i search a tag then a link of another page of all the answers of the searched tags, But i have no idea how can i attach two views so one page can show results and another can show answers. Any … -
Django ORM filter by singular field name
Is it possible to filter a model by some additional/singular version of field name? For example, using model like (where authors is CharField which contains python-list, e.g. ['Johnny']): class Movie(models.Model): title = models.CharField(max_length=100, null=False, blank=False) actors = models.CharField(max_length=250, null=True, blank=True) And query something like Movie.objects.filter(input), where input is <QueryDict: {'actor': ["['Johnny']", "['Pablo']"]}> Anyone has idea how to solve it? Thanks in advance. -
I'm working on a website similar to flat.io, what do these characters signify? [closed]
I'm working on a website similar to flat.io, I wanted to know, what do these string of characters signify and why are they displayed when a user creates a new document? -
How to use multiple toggle switches created dynamically?
I am a beginner in Frontend. I am implementing toggle switches in HTML,CSS and Vanilla Javascript. Structure: I create an HTML with "n" number of rows depending on the data in my django database. Each row has some data like name, id, status. Status column has toggle switches for each row. I have implemented the toggle switch which works fine for one single toggle switch. Problem: When there are multiple rows, and hence, multiple toggle switches, only the first toggle switch is getting toggled not the others. When I click on other toggle switches then also the first one gets triggered. I want all toggle switches to work separately and to detect it in my vanilla javascript. What I know: I know that we need unique id for each toggle switches but I don't know how to do that when I don't know how many rows I will have and how to detect all of them in JS code. Code: Here is the link to my codepen for this problem: ToggleSwitch Any help will be appreciated. Thank you in advance!. -
I can`t reorder apps in Djnago-admin
I can`t admin apps reorder my apps. In django admin home I have the message "Site administration You don’t have permission to view or edit anything." DEFAULT_APPS = ( 'admin_reorder', ) MIDDLEWARE = [ 'admin_reorder.middleware.ModelAdminReorder', ] ADMIN_REORDER = ( "apps.accounts", "apps.questions", "apps.exams", "apps.settings" ) -
How to serialize the aggregated record in Django rest framework?
model class Metric(models.Model): date = models.DateField() channel = models.CharField(max_length=50) country = models.CharField(max_length=10) os = models.CharField(max_length=10) impressions = models.IntegerField() clicks = models.IntegerField() def __str__(self): return "{} - {}".format(self.date, self.channel) My view class MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = MetricFilter My serializer class MetricSerializer(serializers.ModelSerializer): class Meta: model = Metric fields = '__all__' I need to group by one or more columns: date, channel, country, operating system and serialize it. Can someone help me with how I can do it? -
Override url.html in Django Admin
I have overridden the template url.html(template path: /admin/widgets/url.html) file of Django Admin. Now I need to keep that overridden file in my project folder so that whenever the functionality of url.html file is needed, the admin app should look into the overridden template(present inside the project folder) but not the template from Django Admin templates present inside the site-packages folder. Here is my settings.py file settings for templates: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, "company", "app2"), os.path.join(BASE_DIR, "company", "app2", "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] I have placed the overridden file in the following path in my project: compnay -> app2 -> templates -> admin -> widgets -> url.html url.html is present in the widgets folder. The changes made in the overridden template aren't being reflected in the Django Admin UI(For example, in the url.html file, I kept target="_blank" attribute inside the anchor tag to open the corresponding link in a new tab. These changes aren't being reflected.). So, I think it's not taking overridden template present inside my project. What should I do to take the overridden url.html file present in my project folder? -
Django money and ordering by min-max price
Hello i am making Django e-commerce app and i have a problem i wanted to make sorting thing. The problem is i do not know how to get prices between min-price - max-price and filter items. HTML: <div class="sort__prices"> <input class="sort__min-price" type="number" name="min-price" placeholder="minimum price"> <input class="sort__max-price" type="number" name="max-price" placeholder="maximum price"> </div> <button class="submit">sort</button> views: def sortView(request): if request.method == "GET": min_price = request.GET.get('min-price') max_price = request.GET.get('max-price') items = Item.objects.all().filter(price=min_price) return render(request, 'shop/sort.html', {'items': items}) -
djanog-machina search returns no result
I have followed all the steps given in this Tutorial but the search feature for my project is not working. Whereas the example project given by django-machina is working fine with search. So can someone tell me what is the missing thing. I have also rebuild and updated the index. But still my search is not giving any results. It is always 0 results with no error. -
How do django ORM functions interact with db and parse sql code?
I'm somewhat new at programming and just for fun, tried to figure out how the django library works. I went to see how to ORM functions are implemented. I followed the functions to BaseManger, which inherits from Generic[_T]. But then I got stuck. Here's what is in BaseManager for something like get() def get(self, *args: Any, **kwargs: Any) -> _T: ... I assumed something is happening in the parent class Generic, but this is what I got: class Generic: """Abstract base class for generic types. A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default """ __slots__ = () _is_protocol = False @_tp_cache def __class_getitem__(cls, params): if not isinstance(params, tuple): params = (params,) if not params and cls is not Tuple: raise TypeError( f"Parameter list to {cls.__qualname__}[...] cannot be empty") msg = "Parameters to generic types must be types." params = tuple(_type_check(p, msg) for p … -
Fake data for django channels unit tests
I previously asked a question regarding this topic but finally I gave up on that because there seemed to be no way ... But now I really really really need to write unit tests for my django channel consumers because the application is growing larger in size and manual testing isn't efficient anymore. So I decided to ask another question and this time I'm going to do my best to explain the situation. The main problem is "Generating Fake Data". I'm using factory_boy and faker together in order to generate fake data for my tests. When I generate fake data, it is accessible from inside the TestCase itself but is not accessible inside the consumer. Let me show you by an example, consider the code below: test_consumers.py from chat.models import PersonalChatRoom from users.models import User from django.test import TestCase from channels.testing import WebsocketCommunicator from asgiref.sync import sync_to_async from users.tests.test_setup import TestUtilsMixin from astra_backend.asgi import application from chat.tests.model_factory import PersonalChatRoomFactory class TestPersonalChatRoomConsumer(TestCase, TestUtilsMixin): def setUp(self) -> None: super().setUp() self.chat_room = PersonalChatRoomFactory() self.u1 = self.chat_room.user_1 self.u2 = self.chat_room.user_2 -> print("setup: (user): ", User.objects.all()) -> print("setup: (personal chat room): ", PersonalChatRoom.objects.all()) async def test_personal_chat_room_connection(self): -> await sync_to_async(print)("test (user): ", User.objects.all()) -> await sync_to_async(print)("test … -
How to filter by Date fields in Django-filter package?
My model class Metric(models.Model): date = models.DateField() channel = models.CharField(max_length=50) country = models.CharField(max_length=10) os = models.CharField(max_length=10) I am using the django-filter to filter the records. Can someone help how I can filter by time range (date_from+date_to is enough). Like in query parameter user will provide /metrics?date-gte='2021-08-17'&date-lte='2021-08-19' my view class MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_fields = ['country', 'channel','os'] -
Is there any way to allow some API methods avoid Django MAX_MEMORY restrictions?
Is there any way to allow some API methods avoid Django 2.1 DATA_UPLOAD_MAX_MEMORY_SIZE? e.g. in my project DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 JSON: { "data": "some encoded to base64 file with DATA_UPLOAD_MAX_MEMORY_SIZE x2 size" } Now I get Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. I dont want to raise up global Django limit because of security reasons. Thank you in advance, sorry for poor english :( -
Djnago FileField: Prevent saving file onto file system when uploading
I have a simple app in this github repo. There is ready database. There are two models: from django.db import models from django.db.models import FileField class Task(models.Model): name = models.CharField(max_length=20) class TaskAttachment(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) file = FileField() binaries = models.BinaryField() content_type = models.TextField() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.binaries = self.file.file.read() self.content_type = self.file.file.content_type super().save(force_insert, force_update, using, update_fields) Note: please do not ask why I'm saving files in database and not in file system or s3. Registered TaskAttachment model in admin: from django.contrib import admin from tasks.models import TaskAttachment class TaskAttachmentAdmin(admin.ModelAdmin): exclude = ['content_type'] admin.site.register(TaskAttachment, TaskAttachmentAdmin) The problems I faced with that is that uploaded files are being saved to file system: As far as I save binaries in database I do not want files being saved on file system. How could I prevent saving files to file system when uploading files and get file content from database binaries field when fetching TaskAttachment model instance? -
What is the main purpose of the admin site?
Well I been working on Django for a short time as a backend developer (maintainant). And most of the Django sources that I work on, do not have the Django Admin Site. However, when I look up any document of Django. There will be a big section relating about the Django Admin site. So I wonder, what is the main purpose of the Django Admin Site, and in which scenario we gonna use it and in your case, how often you interact with Django Admin Site. -
Notification-like system for django
I'm developing an app for builders. I want to have a button on one page, that will be "I need material" and when that button is pushed, I need to notify, let's say John, on another tablet, that the user, who's working on X, needs material. I need to have it sent without reloading either page, so John can just sit back and when the page that John's tablet will be on starts flashing and information appear, John will know where he needs to go. Any ideas on what to use? I don't want to use extensions if possible. Thanks -
Dynamically populate one Django Form field based on selection in another
I have a model with a list of choices as follows: models.py class Choice_class(models.Model): options = ( ('None', 'none'), ('one', 'one'), ('two', 'two'), ('three', 'three'), ) option_values = ( ('None', 0), ('one', 1), ('two', 2), ('three', 3), ) user_choice = models.CharField(max_length = 5, choices = options, default = 'None') choice_value = models.IntegerField() and a form as follows: forms.py class Choice_class(models.Model): options = ( ('None', 'none'), ('one', 'one'), ('two', 'two'), ('three', 'three'), ) option_values = ( ('None', 0), ('one', 1), ('two', 2), ('three', 3), ) user_choice = models.CharField(max_length = 5, choices = options, default = 'None') choice_value = models.IntegerField(default = option_values[#BASED ON USER CHOICE IN FIELD ABOVE] ) I'd like to populate the choice_value field with a default value from option_values based on what user selects for the user_choice field. I'd rather not do this through js (although it's an option) because I feel like there should be a way to do this through the framework in the same form. I realise that I also have the option of doing the logic for this in views.py: if choice_value == 'None': '''populate with default value based on user_choice as defined by dict in views file etc''' but I'd rather do this within … -
Getting AttributeError: 'ASGIRequest' object has no attribute 'get' in daphne django
I'm trying to run my fastapi code on daphne webserver instead of uvicorn, because my end goal is to run it on Android, where uvicorn is not available. I've been debugging my app for hours at this point. Setting it all up. Here is my code: settings.py """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_n5hy*-sk6y0&mcgu6&_s*+ql5fvujw+ndccjobc0g8lryx!^z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': … -
Django google picker API key
I'm setting up google picker API within a Django app and am trying to figure out how to handle the API key and other settings properly. I am wondering if the way I am doing it is a security risk. I set the values using environment variables like so: # views.py @staff_member_required def upload(request): context = { 'GOOGLE_DEVELOPER_KEY': os.environ.get('GOOGLE_DEVELOPER_KEY'), 'GOOGLE_CLIENT_ID': os.environ.get('GOOGLE_CLIENT_ID'), 'GOOGLE_APP_ID': os.environ.get('GOOGLE_APP_ID') } return render(request, 'upload.html', context) # upload.html <script type="text/javascript"> var developerKey = "{{ GOOGLE_DEVELOPER_KEY }}"; var clientId = "{{ GOOGLE_CLIENT_ID }}" var appId = "{{ GOOGLE_APP_ID }}"; function createPicker() { if (pickerApiLoaded && oauthToken) { var view = new google.picker.View(google.picker.ViewId.DOCS); //view.setMimeTypes("image/png,image/jpeg,image/jpg"); var picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.NAV_HIDDEN) .enableFeature(google.picker.Feature.MULTISELECT_ENABLED) .setAppId(appId) .setOAuthToken(oauthToken) .addView(view) .addView(new google.picker.DocsUploadView()) .setDeveloperKey(developerKey) .setCallback(pickerCallback) .build(); picker.setVisible(true); } } </script> You have to be logged in securely to see the page. But the way I am setting the values, once you are logged in you can simply view the HTML and see the developer key, client id, etc. Is this a problem? Should I be doing this a different way? -
Error loading psycopg2 module: Library not loaded: libpq.5.dylib
I am trying to run a Django project with Postgres database by PyCharm professional. I use Postgres 13.4 installed via postgressapp (UNIVERSAL with all currently supported versions) and python 3.9 (in venv). I work on Mac with Apple M1 chip, macOS Big Sur. I faced the following well-known problem: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/mymac/PyCharmProjects/projectname/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Library not loaded: /opt/homebrew/opt/postgresql/lib/libpq.5.dylib Referenced from: /Users/mymac/PyCharmProjects/projectname/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so Reason: image not found With searching, I found some discussions like this: https://github.com/psycopg/psycopg2/issues/1216. It seems that the most relevant solution is "RyanDurk commented on Jan 27": $ brew install libpq --build-from-source $ export LDFLAGS="-L/opt/homebrew/opt/libpq/lib" $ pip install psycopg2 Unfortunately, in my case it does not help. Then, I found some recommendations here: Library not loaded: /usr/local/lib/libpq.5.4.dylib and tried them. In particular, I tried to reach libpq.5.dylib via symlink like: ln -s /Library/PostgreSQL/13/lib/libpq.5.dylib /opt/homebrew/opt/postgresql/lib/libpq.5.dylib (the solution marked as accepted by topic starter), but also unsuccessfully. I tried to install postgres from postgresql.org, then uninstall/reinstall postgres with homebrew, then gem uninstall pg -> bundle install with the same result. I have run the same project successfully before, on the mac with Intel chip and PyCharm community edition. Also the same project runs normally on Linux. If you have any … -
How to connect a database to two Django projects and access models?
I have a local Django server running and it stores data to a PostgreSQL cluster and I'm trying to access same database in my different Django project how can I achieve this I've tried by creating same models and copying migrations folder in my local server but it din't worked for me, and how can I access the data from PostgreSQL in my second project. -
Not able to use static image after getting the value of dictionary key and using it in HTML template. Unable to use value in HTML
Blockquote I have loaded the static <div class="row"> <img src="{% static 'wea_app/icons/{{ mainresult.icons }}.png' %}"> <div> Blockquote If I print the 'icons', I get the value in terminal. The value name also matches the name of the static file. How can I pass it to the static path which contains the image of my weather. I just want the value to pass to path so I can get the image according to the weather from my static folder. **<!-- myviews.py file -->** mainresult = { "city":city, "temprature": a['current']['temp'], "description": a['current']['weather'][0]['description'], "icons": a['current']['weather'][0]['icon'], "feels": a['current']['feels_like'], "windspeed" : a['current']['wind_speed'], "timezone" : a['timezone'], "pressure" : a['current']['pressure'], "humidity" : a['current']['humidity'], "dt" : a['current']['dt'], } context = {"mainresult":mainresult} return render(request,'wea_app/index.html',context)