Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create views and extend basic Django admin templates?
SyntaxError: closing parenthesis ']' does not match opening parenthesis '{' on line 56 PS D:\djangoProjetcs\usercase> -
Import "channels.auth" could not be resolved
i m trying to create a real time chat app i m following this tutorial https://www.youtube.com/watch?v=cw8-KFVXpTE&list=LL&index=4&t=293s i can't import channels to my project i used these: 'python -m pip install -U channels' i added channels to my apps settings file enter image description here i installed channels and reinstall it i followed another tutorials -
Django admin search function in GenerifForeignkey field with Content_object relation
I am trying to build an admin page that lets admins search through 2 fields of the model "SeasonalitiesCalculated". The fields for my search are called "fruit" and "object_id". "fruit" is a Foreignkey field and returns the "name" field of the corresponding fruit. "object_id" is Genericforeignkey field that sometimes points at a UUID in a model called "Countries" (with a "country_name" field: Germany) and sometimes points at a UUID in a model called "AdminZones" (with an "admin_zone_name" field: California) The problem now is that django seems to not have any standard way of searching through GenericForeignkeys. So I tried defining a search function like this: class SeasonalitiesCalculatedAdmin(admin.ModelAdmin): list_per_page = 20 def country_or_admin_zone_name(self, obj): return obj.country_or_admin_zone_name() country_or_admin_zone_name.short_description = 'Country or Admin Zone' def search_field(self, obj): return obj.search_field() list_display = ('fruit', 'country_or_admin_zone_name', 'content_type', ...) search_fields = ('fruit__fruit_name', 'search_fields') the admin page itself works and it also shows the country or admin zone names and other foreignkey related fields properly since I specified this in the SeasonalitiesCalculated model like this class SeasonalitiesCalculated(LoggingMixinSeasons, Basemodel): fruit = models.ForeignKey('IngredientOriginals', on_delete=models.PROTECT, related_name='%(class)s_related_ingredient_original') content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.UUIDField(default=uuid.uuid4, editable=False) content_object = GenericForeignKey('content_type', 'object_id') ... class Meta: managed = True db_table = 'seasonalities_calculated' verbose_name_plural = 'Seasonalities Calculated' … -
How to save tem file in my system with python
i try to add geometry layer to my gis app from shb layer i use Django for doing that and for uploading file i use serializer FileField now my main question is How can i save temporary file to my system in python is there any way to do that? if there is please help me about that -
Job Portal in Django
Recently, I started working on a job portal project on Django. In the project, I need to create a registration form for multiple types of users. So, please someone suggest if should I create a stored procedure for executing repeated tasks and use that stored procedure in Django? Or is there any way I can reduce code repetition in Django? It will be better if someone can give example as well... -
Multivaluedict key error wventhough i have set name to input field
I have made a form and set method=post and while taking request.post['name'] to a variable MultiValueDictKeyError is Coming why is that ? <form action="verify_user" method="post"> {% csrf_token %} <input required type="text" placeholder="Name" name="name"><br><br> <input required type="password" placeholder="Password" name="password"><br><br> <input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br> <br><br><h1>{{ messages }}</h1> <button type="submit">Create</button> </form> this is my form ------ def verify_user(request): inputname = request.POST['name'] inputpass = request.POST['password'] inputconfirmpass = request.POST['confirm_password'] if not inputpass == inputconfirmpass: messages.info(request,"Passwords don't match") else: messages.info(request,"Passwords match") return redirect('/verify_user') this is my function in views.py ------------- MultiValueDictKeyError at /verify_user 'name' Request Method: GET Request URL: http://127.0.0.1:8000/verify_user Django Version: 4.1.2 Exception Type: MultiValueDictKeyError Exception Value: 'name' this is the error -------- -
TemplateDoesNotExist at /blog/create/
Not sure if its a typo or not... I don't understand why I am getting this error: enter image description here getting TemplateDoesNotExist error? weird because when I click on create post it takes me to ".../blog/create/" can someone help please! " base.hmtl ''' This is the Title {% include 'snippets/header.html' %} <style type="text/css"> .main{ min-height: 100vh; height: 100%; } </style> <div class="main"> {% block content %} {% endblock content %} </div> {% include 'snippets/footer.html' %} **create.html (inside blog/Template/blog) ** {% extends 'base.html' %} {% block content %} <p>Create a new blog...</p> {% endblock content %} ** urls.py (inside blog folder)** from django.urls import path from blog.views import( create_blog_view, ) app_name = 'blog' urlpatterns = [ path('create/', create_blog_view, name="create"), ] urls.py (in mysite folder) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from personal.views import ( home_screen_view, ) from account.views import ( registration_view, logout_view, login_view, account_view, ) urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"), path('blog/', include('blog.urls', 'blog')), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('account/', account_view, name="account"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py (inside blog) from django.shortcuts import render from blog.models import … -
Django nested query in From clause
Is there any way to construct a query like the following using Django ORM? SELECT * from ( SELECT r1 from table_name ) temp; -
Django Rest allauth Keycloak dj-rest-auth authentication PKCE code verifier not specified
I'm trying to retrieve access and refresh token from django rest framework(simple jwt) through keycloak authentication. I extended dj-rest_auth.registration.views SocialLoginView for retrieving the token, but I'm getting an error like allauth.socialaccount.providers.oauth2.client.OAuth2Error: Error retrieving access token: b'{"error":"invalid_grant","error_description":"PKCE code verifier not specified"}' please forgive me if there is any misunderstanding in my code and please help. -
My Html Table footer doesn't render correctly
I'm trying to create a simple table. I would like a footer with only one cell but I don't know why it's divided in two. Any idea? <table class="table-cart-view-producer"> <thead> <tr> <th>Produit</th> <th>Quantité</th> <th>Prix</th> </tr> </thead> <tfoot> <tr> <th> Prix Total du Panier : <strong>{{cart_price}}€</strong></th> </tr> </tfoot> <tbody> {% for item in cartitems %} <tr> <td>{{item.stock_item.product_stockitem.name}}</td> <td>{{item.quantity}} {{item.stock_item.product_stockitem.unit}}</td> <td>{{item.get_total_price}}€</td> </tr> {% endfor %} </tbody> </table> It renders this way: -
Celery Django: Resource temporarily unavailable: 'celerybeat-schedule'
Have some problems with setting celery a schedule Trying to create celerybeat-schedule with command: "celery -A my_app beat -l info" It has infinity starting msg: LocalTime -> 2023-01-30 14:36:49 Configuration -> . broker -> amqp://guest:**@192.168.101.36:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2023-01-30 14:36:49,493: INFO/MainProcess] beat: Starting... When im trying to call command: "celery -A my_app beat" I got an error: [2023-01-30 14:36:37,316: ERROR/MainProcess] Removing corrupted schedule file 'celerybeat-schedule': error(11, 'Resource temporarily unavailable') Traceback (most recent call last): File "/home/knefedov/PycharmProjects/unica_b2b_1/venv/lib/python3.10/site-packages/celery/beat.py", line 533, in setup_schedule self._store = self._open_schedule() File "/home/knefedov/PycharmProjects/unica_b2b_1/venv/lib/python3.10/site-packages/celery/beat.py", line 523, in _open_schedule return self.persistence.open(self.schedule_filename, writeback=True) File "/usr/lib/python3.10/shelve.py", line 243, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/lib/python3.10/shelve.py", line 227, in __init__ Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) File "/usr/lib/python3.10/dbm/__init__.py", line 95, in open return mod.open(file, flag, mode) _gdbm.error: [Errno 11] Resource temporarily unavailable: 'celerybeat-schedule' celery.py import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') app = Celery('unica_b2b', broker_url='some_ip') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_schedule = { 'add-update-every-5-minutes': { 'task': 'authentication.tasks.create_counter_party', 'schedule': 300.0, 'args': (16, 16) }, } app.conf.timezone = 'UTC' -
Django - Problem with Model Manager - Query
I'm still a beginner and I'm stuck in a challenging spot for me. I can't get data from a foreign key table to be inserted "correctly" into a column of a ListView. I basically want to create a list view of a table (FeatureFilm). This also works. But in one column I get information from another table and here I get data, but not the one that belongs to the particular table row. Here are my models. The table I want to show is "FeatureFilm" model. This model is inherited from my base Project class "ProjectBaseModel". Then there is another table "CompanyInvolved Model". This is attached to the FeatureFilm table with a foreign key (feature_id). So movies are stored (FeatureFilm) and different companies are involved in the creation process of the movies. (CompanyInvolved) class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) leading_postproduction_id = models.ForeignKey( Company, verbose_name="Federführende Postproduktion", on_delete=models.SET_NULL, blank=True, null=True, ) phase = models.CharField(choices=post_phase, max_length=30, blank=True, null=True) former_title = models.CharField("Titel, ehemalig", max_length=100, blank=True) title_international = models.CharField( "Titel, international", max_length=100, blank=True, null=True, unique=True ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" ordering = ["title"] class ProductionManager(models.Manager): def get_production(self): return ( super() .get_queryset() .filter(company_role="Produktion", is_production_list=True) .values_list("company_involved__name") ) class CompanyInvolved(models.Model): … -
make mutualTLS between microservices (Django, Fastapi)
I have microservices on Django and FastAPI. I want to make mutualTLS between these services. When I send request from Django project to FastApi project for payment (need to check certificate in FastApi project from Django project) and then FastApi project send request for notify about success or not payment to Django project (need to check certificate in Django project from FastApi project). Like this :) I've tried a lot to implement MutualTLS between Django and FastAPI. -
Bundle django postgres nginx gunicorn docker in real projects [closed]
подскажите пж-ста как в реальных проектах используют связку django postgres nginx gunicorn docker? Т.е, к примеру, БД устанавливают на один сервер и к ней подключаются (мб тоже в докер контейнер устанавливают), nginx в докер, gunicorn тоже в докер, все отдельно, в потом как то связывают или как то иначе... -
Django Model Formset from ManyToMany not accepting queryset
I have my model called Game that has a ManyToMany field consoles = models.ManyToManyField('Console', through='GameConsole') That ManyToMany has some additional attributes class GameConsole(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) console = models.ForeignKey(Console, on_delete=models.CASCADE) released = models.DateTimeField exclusive = models.BooleanField(default=False) I have a page where I want to create/edit those relations. #forms.py class GameConsoleForm(ModelForm): class Meta: model = GameConsole fields = ['console', 'released', 'exclusive'] #to prevent the submission of consoles with the same id (taken from django topics forms formsets) class BaseGameConsoleFormSet(BaseFormSet): def clean(self): """Checks that no two alias have the same name.""" if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return console_ids = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue console= form.cleaned_data.get('console') if console in console_ids: raise ValidationError("Consoles in a set must be different.") console_ids.append(console) NewGameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=1, can_delete=True) GameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=0, can_delete=True) The creation of multiple GameConsole's works fine. The problem is on the edition. On the views, when I do the following: formset = GameConsoleFormSet(queryset = game_consoles) I get the following error __init__() got an unexpected keyword argument 'queryset' which is strange, since I already used this logic with another model (normal table, … -
Django Rest Framework - Why is serializer.data giving me an empty result set but printing the serializer shows me the data
I have created a view to search posts based on their body text. I added a breakpoint to the view and I tested it with mutliple search terms and it works. The problem I have is when I do a print(serializer) in the console then I see the data of all the posts it found. But doing a print(serializer.data) gives me body:null in the data object in the front end console and an empty dictionary in the back end console. Why am I getting body: null? Here is the response in the console for print(serializer): SearchSerializer(<QuerySet [<Post: This is a post>, <Post: This is another post>, <Post: Post THREE>, <Post: Post ONE>, <Post: Post ONE by the user>, <Post: Post TWO by the user>]>): body = CharField(allow_blank=True, allow_null=True, label='Content', max_length=5000, required=False, style={'base_template': 'textarea.html'}) Here is the view: class SearchPosts(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): term = request.data.get("term") posts = Post.objects.filter(body__search=term) serializer = SearchSerializer(posts) breakpoint() return Response(serializer.data, status=HTTP_200_OK) Here is the serializer: class SearchSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'body' ] Here is the post model: class Post(models.Model): body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts") published … -
Django URL dispatcher - Try next view
Alright, let me give you guys an example; We have the following url configuration in Django. Django will try to match the url with the rules down below. Once it finds a match, it will use the appropriate view and lookup the object in the model. The thing is, once it finds a match in the URL pattern, it will match the view. But once the object in the view can't be found, it will return a page not found (404) error. #urls.py from django.urls import path from . import views urlpatterns = [ path('articles/<slug:category>/<slug:editor>/', views.articles_by_editor), path('articles/<slug:category>/<slug:theme>/', views.articles_by_theme) ] We have the following url patterns, we can sort articles either by the editor or by theme. We do this to create a logical url structure for SEO purposes. Is their any way we can redirect to another view once the object isn't found? Can we modify the dispatch method to return to the url patterns and find the following matching rule? Your help will be much appriciated. Kevin -
Django, Choices to Serilize
I have choices like this in my choices.py MATH_CHOICES_TYPE = ( ('1', 'test1'), ('2', 'teste2'), ('3', 'test3'), ('4','test4') ) I want to get result like this as json from APIVIEW using get method Is there any solution? Thanks { "MATH_CHOICES_TYPE": [ { "value": "1", "display_name": "test1" }, { "value": "2", "display_name": "test2" }, { "value": "3", "display_name": "test3" }, { "value": "4", "display_name": "test4" } ] } -
how to convert a range of dates to fill in for a drop down list in django
Trade(models.Model): user_id = models.CharField(max_length=5, null=True, blank=True) nse_index = models.ForeignKey('NseIndex', on_delete=models.CASCADE) trade_expiry = models.DateField(default=THURSDAYS[0], choices=THURSDAYS) trade_type = models.CharField(max_length=25, choices=TRADE_TYPE, default="paper") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I need to display the trade_expiry(all thursdays in a year) as a tuple to be displayed as a dropdown list on a form using django pls help -
How can I get return value from A class to class B in python?
class InputForm(forms.Form):ㅤ attachment = forms.FileField() class View1(FormView): template_name = 'main.html' form_class = InputForm def post(self, request) : I_want_this_file = request.FILES.get('attachment') return I_want_this_file class View2: blar blar ..... When there's this structure, Is there any way to get the value of I_want_this_file from a class called View2? I understand that I have to hand over the parameters to get the return value. But I couldn't bring it because of the "request". When a user uploads a file from a template called main.html, I want to take the file itself, put it in the return value I_want_this_file, and bring the file itself to View2. I have to bring that, but it's not my personal project, so there's no other way to add a file field than this. I'd appreciate it if you could help me. -
missing "Meta.model" attribute i can't find the solution
i'am statring create my rest Api with django restapi but my problem is when i create my meta class he show me this error i don't know why Class SoundSerializer missing "Meta.model" attribute and this is my code ` from rest_framework import serializers from sounds.models import Sound class SoundSerializer(serializers.ModelSerializer): class Meta: Model = Sound fields = '__all__'` from django.urls import path from sounds.api.views import SoundList urlpatterns = [ path('list/',SoundList.as_view() , name ='list'), #path('<int:pk>',sounds_names, name='name1'), ] from rest_framework.response import Response from sounds.api.serializers import SoundSerializer from sounds.models import Sound from rest_framework.views import APIView from rest_framework.decorators import api_view # Create your views here. class SoundList(APIView): def get(self,request): sounds =Sound.objects.all() serializer= SoundSerializer(sounds,many=True) return Response(serializer.data) def post(self, request): serializer=SoundSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) please help me i don't know the problem where is it -
How to detect the Android foldable/flip phone in Djagno
My project displays templates separately from PC/tablet and mobile. views.py ... from django_user_agents.utils import get_user_agent ... class indexView(View): def get(self, request, *args, **kwargs): ... user = get_user_agent(request) if user.is_pc or user.is_tablet: template_name = 'web/index.html' # for PC and Tablet else : template_name = 'mobile/index.html' # for Mobile ... However, Galaxy z fold 4 is recognized as tablet when folded and opened in the Chrome browser. In Samsung's basic browser, when folded, it is displayed as a mobile template. When I checked the userAgent, it included "Safari" instead of "Mobile Safari" in the Chrome browser. Mozilla/5.0 (Linux; Android 13; SM-F936N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 When the foldable phone is folded, I want to display it as a mobile template on the cover screen in the Chrome browser. Is there a way to detect a foldable phone in Django? Or if you have another good idea, please recommend it :) -
useing logging.getLogger(__name__) in django where can i define logger path
I'm using logger = logging.getLogger(name) where can I define logger path in django. logger.warning("Batch files not found.") logger.error('error1') I want to know the log file path and how will create that path? -
expected str, bytes or os.PathLike object, not BoundField in instaapi
I was trying to post a picture in instagram, I have picture url, caption, instagram username and password in 3 different model, I'm sending primary key of the models in response. class InstagramPost(APIView): @staticmethod def post(request, user_id, pk, attachment_id, *args, **kwargs): user_name = get_user_name(user_id) caption = get_post(pk) url = get_attachment(attachment_id) bot = Bot() bot.login(username=user_name['name'], password=user_name['password'], is_threaded=True) print(user_name['name']) print(user_name['password']) bot.upload_photo(url[r'url'], caption=caption['caption']) print(url['url']) print(caption['caption']) return HttpResponse("posted") -
ReactJs Url is changing on its own on api call
I am hitting an api using my ReactJs application. My code is as follows export const getCustomers = (filters) => { return createAction({ type: GET__CUSTOMERS, action: async () => await axios.get(`${BASE_URL}/customers${filters}`, { data: {}, headers: HEADERS.AUTHENTIC(), }), }); }; In the above code, we can see that in the url -> '${BASE_URL}/customers$' , 'customers' is hard coded, but whenever I am running it actually, it hits the as 'Customers'. The case of c changes on its own. It is nowhere in my application. The same problem is with other routes as well. What can be the possible issue and solutions? I hard coded the api to find the issue but it persists.