Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making a search field without using a Django model
I want to search by id in the search field in the django project I created using mongodb. But I want to do this without using a model. I want it to search from mongo. can you help me. Here my code views.py search_query=request.GET.get(’search’ ‘ ’) if search_query: app=app.objects.filter(owner_id__icontains=search_query) else: app=app.objects.all() base.html <form type="get" action="." style="margin: 0"> <input id="search_box" type="text" name="q" placeholder="Search..." > <button id="search_submit" type="submit" >Submit</button> </form> -
How to controll versioning in Django Rest Framework (DRF)
I want to know what is the best practices for controlling the Version for Mobile App APIs. Requirement If I change something in my database previous version of the app should not be affected. Currently I'm doing like... path('v1/auth/', include('authentication.urls')), path('v2/auth/', include('authentication.urls2')), # Example path('v1/api/', include('contentstudio.urls')), -
Accessing fields in a sqlalchemy query by field name
I have a script that is suddenly not working anymore. I upgraded sqlalchemy and pg8000 with just minor upgrades at the same time so I'm not entirely sure which one is the culprit exactly. I have a query to an external Postgres database and upserting the result set back into a Heroku database which is also Postgres. I can connect to the external database and query it, but Python is returning an error when it tries to access a specific field by field name. However, I can access the fields by location: for row in db.query(DATABASE_QUERY): print(type(row)) # <class 'records.Record'> print(row) # <Record {"item_id": 12345, "item_name": "7.Subject.Class", "active": true, "is_deleted": false} print(row[0]) # 12345 print(row.item_name) # print(row['item_name']) # Error thrown Error is thrown on the last line, using either syntax. The full stack trace is: Traceback (most recent call last): File "app_dir/manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\Documents\Github\django-app\venv-dev\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\Documents\Github\django-app\venv-dev\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Documents\Github\django-app\venv-dev\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Documents\Github\django-app\venv-dev\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\user\Documents\Github\django-app\app_dir\apps\etl\management\commands\load.py", line 118, in handle step.load(period=period) File "C:\Users\user\Documents\Github\django-app\app_dir\apps\etl\models\job.py", line 89, in load match_status = self.domain_source.load(*args, **kwargs) File "C:\Users\user\Documents\Github\django-app\app_dir\apps\etl\models\domain.py", line 90, … -
Django project docker after unexpected shutdown: Is the server running on host "db" (172.19.0.3) and accepting TCP/IP connections on port 5432?
I am using popOs20 Battery was running low and unexpected shutdown occurred. The same project with docker successfully gets built on other device. I have tried: docker system prune docker volume prune killing all processes of swap and ram and then restarting changing docker network and some other things I do not even remember anymore. Any ideas what can I do ? Project is using postgresql13 full error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection timed out Is the server running on host "db" (172.19.0.3) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run … -
How to use UserCreationForm in Django?
I have followed this tutorial to test out the User authentication and Signals in Django. I don't know what I should do with this part (found from the first post of this tutorial): from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): birthdate = forms.DateField() discord_id = forms.CharField(max_length=100, help_text='Discord ID') zoom_id = forms.CharField(max_length=100, help_text='Zoom ID') text = forms.TextField(null=True, blank=True) class Meta: model = User fields = ["username", "password1", "password2", "birthdate", "email", "discord_id", "zoom_id"] With those imports I get an error NameError: name 'forms' is not defined and if I add an import from django import forms I get errors like AttributeError: module 'django.forms' has no attribute 'TextField'. Sohuld I add all the fields from my Model into this RegisterForm -class I want to include to the registration process? What do I do to the fields that are textFields in my Model? -
How can I create a Saleor plugin that is a Django app?
I'm trying to add a Saleor plugin that is also a Django app. The reason is that I want to be able to use Django migrations for it. I've created regular Saleor plugins before, which work fine. I'm not very familiar with Django apps yet, but the documentation makes sense to me. What I'm utterly confused about is the combination of the two concepts. Which directory does it go into? Does it go into the saleor/plugins directory like all other regular Saleor plugins? Or directly into the saleor directory, like all other Django apps? The only somewhat related answer I could find suggests using manage.py startapp, which creates the plugin in the root directory, next to the saleor directory, adding to my confusion. How to install the Django app as a Saleor plugin? The official documentation instructs to use a setup.py and suggests that: If your plugin is a Django app, the package name (the part before the equal sign) will be added to Django's INSTALLED_APPS so you can take advantage of Django's features such as ORM integration and database migrations. However, none of the built-in Saleor plugins or Django apps are using this setup.py mechanism, and I cannot find … -
ModuleNotFoundError: No module named 'ffi'
After building success heroku git push heroku main.when I executed that gunicorn --bind 0.0.0.0:8000 app:app i get this error.I searched in google but didnot found answer.With procfile data as web: gunicorn tictactoe.wsgi .tictactoe my project name. Traceback (most recent call last): File "c:\users\anves\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\anves\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\anves\AppData\Local\Programs\Python\Python39\Scripts\gunicorn.exe\__main__.py", line 4, in <module> File "c:\users\anves\appdata\local\programs\python\python39\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in <module> from gunicorn.app.base import Application File "c:\users\anves\appdata\local\programs\python\python39\lib\site-packages\gunicorn\app\base.py", line 11, in <module> from gunicorn import util File "c:\users\anves\appdata\local\programs\python\python39\lib\site-packages\gunicorn\util.py", line 8, in <module> import fcntl File "c:\users\anves\appdata\local\programs\python\python39\lib\site-packages\fcntl.py", line 1, in <module> import ffi ModuleNotFoundError: No module named 'ffi' -
TypeError: get_object() takes 1 positional argument but 2 were given [18/May/2021 18:27:12] "GET /api/Oxyegn/ HTTP/1.1" 500 94676
What i am trying to do is i am giving Choice Field and i am trying to get all post when i pass that choice field to url as parameter for eg: Oxygen, Plasma etc They are in my choice field which user has to choose during posting post. I want to get json format which we get whenever we do request to api and i want that information based to choice filed i have given but getting error. Rest Api View class PostRestApi(APIView): def get_object(self, **kwargs): try: return Post.objects.get(help_type=kwargs.get('help_type')) except Post.DoesNotExist: raise Http404 def get(self, request, **kwargs): posts = self.get_object(kwargs.get('help_type')) serializer = PostSerializer(posts) return Response(serializer.data) > SERIALIZERS CLASS class PostSerializer(serializers.Serializer): title = serializers.CharField(max_length = 100) content = serializers.CharField() date = serializers.DateTimeField(default=timezone.now) help_type = serializers.CharField() My Post Model CHOICES = ( ("1", "Plasma"), ("2", "Oxygen"), ("3", "Bed"), ("4", "Emergency") ) class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) help_type = models.CharField(max_length=300, choices = CHOICES, null=True) url path('api/<str:help_type>/', PostRestApi.as_view(), name='post-api') -
DRF Viewset test method
I have added a method to my viewset as follows: class CustomImageViewSet(viewsets.ModelViewSet): queryset = CustomImage.objects.all() serializer_class = CustomImageSerializer lookup_field = 'id' @action(detail=True, methods=['get'], url_path='sepia/') def sepia(self, request, id): # do something data = image_to_string(image) return HttpResponse(data, content_type="image/png", status=status.HTTP_200_OK) Since it is not a default or overridden request method, I am not sure how can I proceed writing a test for it. Any suggestions? -
JSONField Django
how can i store a dictionary in JSONField of django model ? class order(models.Model): payment_collection_webhook_request_parameters = models.JSONField() dictionary to be stored in payment_collection_webhook_request_parameters is: postData = { "orderId" : payment_gateway_order_identifier, "orderAmount" : amount, "referenceId" : reference_identifier, "txStatus" : settlement_status, "paymentMode" : payment_mode_code, "txMsg" : transaction_message, "signature" : signature, "txTime" : datetime } -
comment not being submitted by my django form
I want my users to be able to add comments under a transfernews [I am creating a sports related website], I tried this code, but for some reason, it is not working, I can add comments manually from the admin page but can't from the comment form. Can anyone please tell me how to fix my code? My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.transfernews_id = transfernews.id new_comment.save() return redirect(request.path_info) return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My html file: {% for transfer in transfernews %} <h2>Comments...</h2> {% if not transfer.comments.all %} No comments Yet... {% else %} {% for comment in transfer.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} <br/><br/> {% endfor %} {% endif %} <hr> <div>Comment and let us know your thoughts</div> <form … -
Populating parent model from child model form in django
I have a web interface in which I can add entries to a child model, which I created in Django. I can populate the child model by using dropdown menus which will display the items currently stored in the parent models. I would like to be able to actually insert a new item in the parent model from within the same form. I have the following model, which works fine if I want to populate the child model (results class) using already existing parent model (project table and objects_table) entries. models.py class project_table(models.Model): project = models.CharField(max_length = 100, unique = True) def __str__(self): return u'{0}'.format(self.project) class objects_table(models.Model): object = models.CharField(max_length = 50) def __str__(self): return u'{0}'.format(self.object) class results_table(models.Model): object_id = models.ForeignKey(objects_table, on_delete = models.PROTECT) project_id = models.ForeignKey(project_table, on_delete = models.PROTECT) date = models.DateTimeField(default = timezone.now) path = models.CharField(max_length = 500) def get_absolute_url(self): return reverse('result-detail', kwargs = {'pk': self.pk}) My view is: views.py class ResultCreateView(LoginRequiredMixin, CreateView): model = results_table fields = ['object_id','project_id', 'date', 'path'] def form_valid(self, form): form.instance.operator = self.request.user return super().form_valid(form) and the HTML: {% extends "queryd/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Result</legend> {{ form|crispy … -
Only get Cors Header error when accessing media files, rest of the app works fine (DRF, pythonanywhere, React)
This is happening on both chrome and firefox. I have a react app that communicates fine with my django rest framework backend until I try to access an uploaded mp3 media file. I then get: " has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." If I click on the error media link within chrome console it will take me to the uploaded mp3 and it will play fine. My app is deployed on Pythonanywhere. My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tagging', 'rest_framework', 'corsheaders', 'rest_framework.authtoken', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'STATIC') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'MEDIA') CORS_ALLOW_ALL_ORIGINS = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('tagging.urls')), path('api/api-token-auth/', views.obtain_auth_token) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have static & media files setup within the pythonanywhere web app: URL:/STATIC/ Directory: /home/username/project/STATIC URL:/MEDIA/ Directory: /home/username/project/MEDIA not sure why this is occurring, any help would be much appreciated. -
can set string data to state with axios in reactjs
I want to save the string received from API in the state, but it can't. First I wrote a Python code as follows that returns the first 3 letters of the username (each username is entered so that the first three letters specify its type). this is Django(python) code: from django.shortcuts import redirect, render from rest_framework.views import APIView from rest_framework.response import Respons class usertype(APIView): def get(self,request,format=None): try: user=request.user except: raise ValueError('error') return Response({ 'username':user.username[:3], }) then i write this code in react for separate dashboards: import React, { Component } from 'react' import { render } from 'react-dom'; import DashboardS from './Students/DashboardS'; import DashboardT from './Teachers/DashboardT'; import axios from 'axios'; const api=axios.create({ baseURL:'http://127.0.0.1:8000/accounts/usertype/' }) export default class App extends Component { constructor(props){ super(props); this.state={ usertype:'', showS:false, showT:false, } this.showDash=this.showDash.bind(this); this.getusertype=this.getusertype.bind(this); } componentDidMount(){ this.getusertype(); this.showDash(); } getusertype(){ api.get('/').then(res=>{ this.setState({ usertype:res.data.username, }); console.log(res.data.username); // out is std for stduent user }); } showDash(){ switch(this.state.usertype){ case "std": this.setState({ showS:true,showT:false, }) break; case "tcr": this.setState({ showS:false,showT:true, }) break; } } render() { return ( <div> {this.state.showD && <DashboardS/>} {this.state.showP && <DashboardT/>} </div> ) } } how can i solve this problem. help me. -
Gunicorn process never die
I have a nginx + gunicorn django application, those process never dies for some reason until no-response: Once it run on local windows 10 env - It works really good no memory leak hangs. I think local only "fork" (win dont fork IO know) one main, but Y gunicorn process never die ? -
How to resolve 'Import "django.contrib" could not be resolved from sourcePylancereportMissingModuleSource'?
This error suddenly came up when I created a new django project. I used pip to install all the packages in the virtual environment.enter image description here -
'Contact.Contact' has no ForeignKey to 'Order.Order' error using django extra views
I'm trying to use django extra views to create an Order with a Contact inline formset but i'm getting the following error : 'Contact.Contact' has no ForeignKey to 'Order.Order'. models.py class Contact(models.Model): ... class Order(models.Model): contact = models.OneToOneField(Contact, on_delete=models.CASCADE, default="") views.py class ContactInline(InlineFormSetFactory): model = Contact fields = ['name', 'email'] class CreateOrderView(CreateWithInlinesView): model = Order inlines = [ContactInline] fields = ['customer', 'name'] template_name = 'order_and_items.html' I am wordering if the problem is due to the OneToOne relationship between Contact and Order. -
Filter on custom field across multiple models that import from Wagtail core Page
I have two custom Page models that share a field in common, for example: class CustomPageModelOne(Page): custom_field = models.IntegerField() ... class CustomPageModelTwo(Page): custom_field = models.IntegerField() ... I need to run, ideally, a single filter across the two types of custom Page models. The Wagtail docs say I can use an exact_type method to specify multiple models inheriting from core Page, so I am trying some variations of the following: Page.objects.exact_type(CustomPageModelOne, CustomPageModelTwo).filter(custom_field=123) However, when I try to filter any QuerySet that uses both models, I get an error: django.core.exceptions.FieldError: Cannot resolve keyword 'custom_field' into field. How can I query across multiple Wagtail custom Page models that share a field in common? Note: I have considered creating an abstract class inheriting from Page, but cannot import that abstract model in the file where it is needed. Abstract class example: class CustomFieldModel(Page): custom_field = models.IntegerField() class Meta: abstract = True class CustomPageModelOne(CustomFieldModel): pass class CustomPageModelTwo(CustomFieldModel): pass -
python filter returns none if any one input is not present in combination django
i am creating a model in for a literature in which we can type english,german,french etc.. , my model may be containing english,german,french. if i put these 3 values in it , it shows me correct output but if type english,german it returns none because one condition failed, but in fact i want it in such a way that it return that perticular object if that condition met, if i write english,german,french and model contains only english,german it should return english,german instead of none def resolve_codepool_advanced_lang5(root,info,lang1,lang2,lang3,lang4,lang5): return Codepool_Advanced.objects.filter(codepool_advanced_language1=lang1,codepool_advanced_language2=lang2,codepool_advanced_language3=lang3,codepool_advanced_language4=lang4,codepool_advanced_language5=lang5) -
Uncaught TypeError: Cannot read property 'fields' of undefined at Object.success
I wanted to use ajax for showing all comments that are responding to a song. The song model contain a many to many field for the comments model. Im having trouble with the serializer for django or im having trouble with receiving the data from my view. Im not quite sure which it is. View.py: def commentview(request): if request.is_ajax and request.method =="GET": song_id = request.GET.get("song_id",None) song = get_object_or_404(Song,pk=song_id) comments = song.comments.all() ser_comments = serializers.serialize('json', comments) return JsonResponse({"instance": ser_comments}, status=200) playlist.html: {% block javascript %} <script> function comments( id) { $.ajax({ type: 'GET', url: "{% url 'app:commentview' %}", data: { "song_id": id }, success: function (response) { var comments = JSON.parse(response["instance"]); for (var i = 0; i <= comments.length; i++) { var field = comments[i]["fields"]; $("popup" + id).prepend( '< h5 > ${ field["member"]|| "" }</h5 >' + '< p > ${ field["text"]|| "" }</p >' + '<br>', ) } $("popup" + id).prepend( '<textfield id="comment' + id + '"></textfield>' + '<button onclick="postComment(' + id + ')">Comment</button>', ) }, error: function (response) { } }) } </script> {% endblock javascript %} the error code i get: 1:520 Uncaught TypeError: Cannot read property 'fields' of undefined at Object.success (1:520) at i (jquery-3.2.1.min.js:2) at Object.fireWith … -
django admin css broken - vertical scroll runs over all parts of page
I am running django 3.1.4 and my admin css broke somehow: when scrolling, the list of the products is appearing "behind" other menu points. so instead of just the products being scrolled below the last point of the admin, all of them scroll. which css setting might be the key here (the admin css is too long to post here I guess, but I am happy to share what helps). -
Why is Django retrieving all the reverse foreign objects
I have the following models created in django: class A(models.Model): route = models.ForeignKey('B', related_name='b') class B(models.Model): name = models.CharField(max_length=100) And I want to filter the elements of 'B' without accessing the elements of A. The problem is that when I run the following query (supposing there are 4 objects of A related to one object of B with id equal to 1): B.objects.filter(id='1') I get printed 4 different sql queries, fetching all related objects of A. I do not know why that's happening. I have tried B.objects.filter(id='1').select_related('b') But it does not work for some reason. I do not want to do those hits to the database, ideally, I would want to ignore/exclude those objects because I only want the objects of B. Additional info: django version: 1.11 python version: 2.7 -
Why am i getting a ModuleNotFoundError when i add rest_framework to my django app
I created a new django app and installed djangorestframework using pipenv version 2020.11.15 and regestered it in the settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', 'rest_framework' ] i got this error on running python manage.py makemigrations C:\Users\eliHeist\Python Workspace\lead_manager_react_django\leadmanager>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' What is going on? -
How to add searchable choice field in django form
I am looking for implementing searchable choice field (searchable dropdown) in django using django forms and models. This choice field will be populated from database. -
Single page application using django-Nav Bar for django app
In Angular,we can use routing to create SPAs . So I can have a navigation bar that's common for all templates(or written only once). Basically only required part of the page loads everytime . But in django,so far I haven't seen anything like it. Do i have to include the code for the Nav bar in each template file?