Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a timer in the Django admin model
I want to create a timer in such a way that when the time is set in the admin model, the timer will be activated. Thank you if anyone knows. enter image description here -
DJango admin base_site template extension not working
I am trying to override the basic structure of a Django admin page using the below code: {% extends "admin/base_site.html" %} But the problem is, using this I only get the branding of the site, everything else like the navbar or the logout buttons are all missing. I have also tried adding the below segment but it is not working: {% block nav-global %}{% endblock %} Please suggest some measures. -
Connecting to AWS RDS Postgres Instance from my Django Project (Settings.py)
settings.py import os import dj_database_url ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USERNAME'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': 5432 } DATABASES['default'] = dj_database_url.config(os.environ.get('DATABASE_URL'),conn_max_age=600) I have a environment variable in my machine postgres://<user>:<password>@<host>:5432/cust_manage this is to connect to my aws rds postgresql then when I start the server it returns this error django.db.utils.OperationalError: FATAL: password authentication failed for user "dieth" FATAL: password authentication failed for user "dieth" QUESTION: How to connect my app to my aws rds that uses environment variable? so that I don't have to pass my real host and password to my settings.py. Thanks guys. -
Hide algorithm, iterations, salt in django password field
In django user table password are encrypted automatically with a secure algorithm (pbkdf2_sha256) with salt and iterations. But what I don't understand is why the django password field shows the algorithm, iterations and salt in this format: <algorithm>$<iterations>$<salt>$<hash> I thought those information are secret and I want to show only the hash. -
Login form not initializing not authenticating
When I was adding a template from the internet to my login.html code I encountered a problem. When I try to login it did not work. Even after I added CSRF tokens and login form control code. It has a clickable button that does not thing. I hope someone can help me. If any pictures or other codes needed please feel free to ask. login.html: {% extends 'base.html' %} {% load static %} {% block content %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Style --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <div class="content"> <div class="container"> <div class="row"> <div class="col-md-6 order-md-2"> <img src="{% static 'images/undraw_file_sync_ot38.svg' %}" alt="Image" class="img-fluid"> </div> <div class="col-md-6 contents"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="mb-4"> <h3>Sign In to <strong>C</strong></h3> <p class="mb-4">Lorem.</p> </div> <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="username" placeholder="Username"> </div> <div class="form-group"> <input type="password" class="form-control" id="password" for="password" placeholder="Password"> </div> </form> <input type="submit" value="Log In" class="btn text-white btn-block btn-primary"> </form> </div> </div> </div> </div> … -
Django | Queryset ManyToMany Relation through Instance
I would like to display the different dates for each course. A course can also have several dates. Unfortunately I can't find a solution. Models: class Course(models.Model): course_number = models.CharField(max_length=24, blank=True) course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE) course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates") def __str__(self): return self.course_number class Course_Course_dates(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE) def __str__(self): return self.id class Course_dates(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() trainer = models.ManyToManyField('Trainer', through="Course_dates_trainer") def __str__(self): return self.date.strftime("%d.%m.%Y") View: def course_list(request): courses = Course.objects.all() course_list = [] for course in courses: course_location = course.course_location.description dates = course.course_dates.all() course_list.append({'course': course, 'course_location': course_location, 'dates': dates,}) context = { 'course_list': course_list, } return render(request, 'kursverwaltung_tenant/course.html', context) Thanks for help!!! -
Request data empty with formData - Django Rest Framework
I am trying to save strings, floats and an image via a POST request made to a Django Rest Framework backend: # My view: class CreatePost(APIView): # tried with and without parser: # parser_classes = [FormParser, MultiPartParser] def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user_id=request.user.pk) return Response(serializer.data, status=201) return Response(serializer.errors, status=400) # My serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ("x", "y") And my JS frontend: const postBody = new FormData(); postBody.append('x', 'someValue'); postBody.append('y', 'someValue'); fetch('/api/v1/post', { method: 'post', body: postBody, credentials: 'same-origin', headers: { 'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'multipart/form-data' } } However, sending as 'Content-Type': 'multipart/form-data' does not show any values in request.data in my backend. Sending as application/json works, but does not when one of the fields is an image. How can I process both text and image using form-data? I tried using parsers (FormParser and MultiPartParser) without success. -
Django, all views require login except `@login_not_required` decoratored views
Django is centered towards allow access to all the majority of the time, and restricting acces on the exception. I am making a site whereby I would like access restricted the most of the time, and the rare case is open to all. Ensuring that one has added a @login_required decorate to all views is error prone. I acheived this by creating a custom middleware like this. To keep track of open URLs, I defined a list, and then whenever I wished to open up a URL, I added it to the list, and the middleware checked the request path against this list, and allowed exceptions accordingly. This method above works, but I often mess it up with changing urls, and other issues to do with code reuse on different sites. Ideally I would like to create my own @login_not_requied decorator. How to get the class based view or function the request is going to call within the middleware, so I can check whether the view does not require login? -
Using Django's GenericForeignKey with Async Graphene Subscription
I've implemented graphql_ws to subscribe to updates from a Notification model that uses multiple GenericForeignKeys. My setup works well, except when I try to query information from those foreign objects. I then get the following error: graphql.error.located_error.GraphQLLocatedError: You cannot call this from an async context - use a thread or sync_to_async. From what I seem to understand, that's because some database query operations are being done outside the async context of get_notifications (that is, in the resolve_actor function). But I'm really not clear on how I can pull the operations of resolve_actor into the async context. I've unsuccessfully tried using prefetch_related (plus I'm not sure it'll work with multiple content types per Django's docs). Here's the code models.py class Notification(TimeStampedModel): # ... actor_content_type = models.ForeignKey(ContentType, related_name='notify_actor', on_delete=models.CASCADE) actor_object_id = models.CharField(max_length=255) actor = GenericForeignKey('actor_content_type', 'actor_object_id') # ... schema.py class ActorTypeUnion(graphene.Union): """ All possible types for Actors (The object that performed the activity.) """ class Meta: types = (UserType,) # here's there's only one type, but other fields have multiple class NotificationType(DjangoObjectType): actor = graphene.Field(ActorTypeUnion) def resolve_actor(self, args): if self.actor is not None: model_name = self.actor._meta.model_name app_label = self.actor._meta.app_label model = ContentType.objects.get(app_label=app_label, model=model_name) return model.get_object_for_this_type(pk=self.actor_object_id) return None # ... class Meta: model … -
"Incorrect type. Expected pk value, received User."
I have this two models: order and route. Route has a oneToMany relation with Order as you can see: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField(default=datetime.date.today) date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) description = models.CharField(max_length=500, null=True) route = models.ForeignKey(Route, related_name='orders', null=True, on_delete=models.CASCADE) class Route(models.Model): day = models.DateField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) start_time = models.TimeField() When a route is created I want to associate orders with that route, so I've done the following serializer: class routeSerializer(serializers.ModelSerializer): orders = OrderSerializer(many=True) class Meta: model = Route fields = ['day', 'warehouse', 'start_time', 'orders'] def create(self, validated_data): orders_data = validated_data.pop('orders') route = Route.objects.create(**validated_data) for order_data in orders_data: order_serializer = OrderSerializer(data=order_data) order_serializer.is_valid(raise_exception=True) orders = order_serializer.save() orders.route = route orders.save() return route I am sending a request like this: { "day" : "2021-12-12", "warehouse": "1", "start_time": "7:00", "orders": [ { "id": 15, "customer": 1, "retailer": 2, "date_available": "2020-12-12", "weight": "1.20", "description": null, "ordertimelocation": [ { "longitude": "12.1223000000000000", "latitude": "12.1223000000000000", "time_interval": [ { "start": "2021-07-21T10:10:00Z", "end": "2021-07-21T10:10:00Z" } ] } ] } ] } But the server returns a bad request: { "customer": [ "Incorrect type. Expected pk value, received User." ], "retailer": [ "Incorrect type. Expected pk value, … -
Django Ajax Post - works sometimes
I have a Django application where I am using AJAX to do a post when submitting a form. My issue is what do I set the URL to in my JavaScript? JavaScript snippet: $.ajax({ url: "search/do_post/", // the endpoint type: "POST", // http method data : { relevancy: relevancy, report_id: report_id, query: query_text, //csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, urls.py snippet: path("search/do_post/", do_post_view, name="do_post"), My issue is that sometimes the above works and sometimes it does not. When it doesn't I get: POST http://localhost:1227/search/search/do_post/ 404 (Not Found) When I see that I then remove the search part from the url in my JavaScript. Sometimes that works and sometimes not. Any suggestions? -
How to upload a saved file in django
in my case, the user gives a word in the front-end and in the back-end, i will call some function that i wrote and at the end i will build a .PDF file in the /media/reports directory. how i can make this files user-specefic and save them in the database? before that, i implemented my code without models and forms and just save file in the /media/reports/ directory. and user just could download that file at the moment after redirected to the download page. but now, i want to save these files to the database that each user will be access new files in his profile. how i can do that ? here is my code: views.py: @login_required(login_url='/login/') def dothat(request): if request.method == 'GET': return render(request, 'app/dothat.html') else: try: global word, user_name, function_name function_name = dothat.__name__ word = request.POST.get("word") user_name = request.user full_name = request.user.get_full_name() myscript.script_one(word, user_name,full_name, function_name) # And in the called myscript, after doing some things, # the PDF file will be saved in /media/reports/ directory except ValueError: return render(request, 'app/dashboard.html', {'error':'Bad data passed in. Try again.'}) # And then, the user will be redirect to the download page to download that single file return render(request, 'app/download.html') and … -
django_elasticsearch_dsl -RequestError(400, 'search_phase_execution_exception', 'failed to create query: For input string: )
I am trying to search with Elasticsearch using django_elasticsearch_dsl and 'django_elasticsearch_dsl_drf',, but I get RequestError(400, 'search_phase_execution_exception', 'failed to create query: For input string: "MM"'). I am able to search if my input is an integer or a float , but I am not able to search for string. Here is my document.py file:- from django_elasticsearch_dsl import ( Document , fields, Index, ) #from .models import ElasticDemo from .models import Course #PUBLISHER_INDEX = Index('elastic_demo') PUBLISHER_INDEX = Index('courses') #Name of the database that we are making PUBLISHER_INDEX.settings( number_of_shards=1, number_of_replicas=1 ) @PUBLISHER_INDEX.doc_type class CourseDocument(Document): id = fields.IntegerField(attr='id') #fielddata=True course_index = fields.IntegerField( fields={ 'raw': fields.IntegerField(analyzer='keyword'), } ) Code = fields.TextField( fields={ 'raw': fields.TextField(analyzer='keyword'), } ) Title = fields.TextField( fields={ 'raw': fields.TextField(analyzer='keyword'), } ) TotalCredits = fields.FloatField( fields={ 'raw': fields.TextField(analyzer='keyword'), } ) Description = fields.TextField( fields={ 'raw': fields.TextField(analyzer='keyword'), } ) department = fields.TextField( fields={ 'raw': fields.TextField(analyzer='keyword'), } ) class Django(object): model = Course Here is my views.py class CourseDocumentView(DocumentViewSet): document = CourseDocument serializer_class = CourseSerializer lookup_field = 'id' filter_backends = [ FilteringFilterBackend, OrderingFilterBackend, CompoundSearchFilterBackend, #DefaultOrderingFilterBackend, SearchFilterBackend, ] search_fields = ( 'Code', 'Title', 'TotalCredits', 'Description', 'department', ) multi_match_search_fields = ( 'Code', 'Title', 'TotalCredits', 'Description', 'department', ) filter_fields = { 'Code' : 'Code', 'Title' : 'Title', 'TotalCredits' … -
How to sync django calendar project with mobile app calendar?
I have created a calendar with drf and react js which has all calendar features including events. Now, I'm trying to see my calendars and events on mobile calendar apps like Samsung or iphone calendar. I use google to authenticate users. Is there any ways to do it? What if I use my own email service (something other than google account)? Thanks for your help. -
Intergrating shopify payment with django app
Is it possible to integrate Shopify payment with Django!? Currently I developed an eCommerce site with django using Stripe payment-gateways,but in latest requirements I'm supposed to integrate Shopify Payments with the project. So now here comes two questions Is it possible to integrate shopify payment with django ? If possible, what's the starting point? -
Python/Django 'WindowsPath' Type Error in Django Rest Framework (DRF)
I keep getting the 'TypeError' below when running a Django project in the virtual environment. What could be the problem? Thanks in advance! File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 190, in close if not self.is_in_memory_db(): File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 287, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 13, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable Here's the settings code for the Databases: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } -
get input to translate a web page django
i'm trying to use multi language for my website by default its language is english , but i 've to add arabic and kurdish(arabic character) to the website ,i want to get input from the user to translate the website to its language for example , in the website we have home - pages - contact map and also some success messages from views.py messages.success(request,_('added')) i need to give privileges' to users who wants translate the website to his/her language , i dont want to use gettext and {% trans %} ! is it possible please ?or isnt there any library for doing that ?!thank you in advance -
Have a constant parameter in all my django URLs
I have a django website that shows data which is seperated in 3 differents databases corresponding to different servers. I have a dropdown list on my website that allow to choose the desired server. What i would like is when a server is chosen, that this choice is keeped all around the website until an other server choice is done. With this choice beeing constant in the URLs like that : website.com/server1/home -> website.com/server1/page-1 -> new server choice -> website.com/server2/page-1 I don't know how to keep this parameter constant without having to pass a variable 'server_name' to every view and every URL of my website. Is there an easier way to do this ? Thank you for your help ! -
Create serializer fields according to the data in Django Rest
I am writing an api for Auth. and I have 2 user types ( Donors , Charity ) when they did registration my data is changing. So that I need to update my fields according to the data. Here is what I did so far. views.py class RegisterView(APIView): def post(self, request): js_data = request.data if 'last_name' in js_data: #fields = ['id', 'email', 'first_name', 'last_name', 'password'] serializer = UserSerializer(data=js_data) serializer.is_valid(raise_exception=True) serializer.save() else: #fields = ['id', 'email', 'first_name', 'postcode', 'password'] serializer = UserSerializer(data=js_data) serializer.is_valid(raise_exception=True) serializer.save() in views.py I tried to define fields from outside serializers.py but I can't send fields as a parameter. serializer = UserSerializer(data=js_data, fields = fields) # gives error. also I tried this one; serializer = UserSerializer(data=js_data, many= True, fields = fields) # gives error So I am trying to create fields dynamically. serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = [] extra_kwargs = {'password': {'write_only': True} } def create(self, validated_data): if 'last_name' in validated_data: self.Meta.fields = ['id', 'email', 'first_name', 'last_name', 'password'] else: self.Meta.fields = ['id', 'email', 'first_name', 'postcode', 'password'] password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance So in here I tried to change fields in create function. … -
Unable to deploy django project on heroku
I am trying to deploy django project on heroku but I am getting following error. 2021-08-07T10:05:35.789899+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=betabrains.herokuapp.com request_id=2e0f8a7e-ce6f-492b-88d9-81b89a3d7ec0 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:05:36.294818+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=betabrains.herokuapp.com request_id=0bcb0efe-ef5a-4040-9a5e-a5ca56ea9867 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:05:45.842915+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=betabrains.herokuapp.com request_id=fb1e34e7-cc89-4e2f-b7a9-6086b8b8846e fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:05:46.803562+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=betabrains.herokuapp.com request_id=bcd75f14-d98a-42c6-9a6f-e43478360d11 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:08:04.166212+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=betabrains.herokuapp.com request_id=93ab6bfb-f8c5-4b5f-9a7a-2eca36b467ed fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https 2021-08-07T10:08:04.627050+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=betabrains.herokuapp.com request_id=73582b96-2327-4c95-8962-a239c1270075 fwd="223.187.110.102" dyno= connect= service= status=503 bytes= protocol=https my file system is. . ├── Procfile ├── aboutus │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── admin.cpython-39.pyc │ │ ├── apps.cpython-39.pyc │ │ ├── models.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── views.cpython-39.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-39.pyc │ ├── models.py │ ├── templates │ │ └── aboutus │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py … -
How to return articles from followed users only?
Right now i am successfully able to return every article without issue. But what i want to do is this: I want to return the articles,only followed by the current authenticated user. How can i do it? models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='undefinedusername') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class UserFollow(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') serializers.py class UserSerializer(DynamicFieldsMixin,serializers.ModelSerializer): userfollowers_set = UserFollowSerializer(source='followers',required=False,many=True) userfollowing_set = UserFollowSerializer(source='following',required=False,many=True) class Meta: model = User fields = ('id','email','username','userfollowing_set','userfollowers_set') views.py class ArticleViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-timestamp') serializer_class = ArticleSerializer -
django create views use more models
hi everyone I have a doubt with the use of forms and models. I have to create a code that creates records in multiple tables and I don't know how to do it. my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user. forms.py from django import forms from .models import Schede, DatiGruppi, Gruppi class CreaSchedaForm(forms.ModelForm): nome_scheda = forms.CharField( required = True, label ='Nome scheda', widget = forms.TextInput( attrs = { 'class': 'form-control', 'placeholder' : 'nome scheda', 'autocomplete' : 'off' } ) ) data_inizio = forms.DateField( label='Data inizio', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data inizio' } ) ) data_fine = forms.DateField( label='Data fine', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data fine' } ) ) class Meta: model = Schede fields = ['nome_scheda','data_inizio','data_fine'] class CreaDtGruppoForm(forms.ModelForm): giorni_settimana = forms.ChoiceField( choices = DatiGruppi.giorni_settimana_scelta ) dati_gruppo = forms.ModelChoiceField( queryset = Gruppi.objects.all(), empty_label = "-", required = True ) class Meta: model = DatiGruppi fields = ['giorni_settimana', 'dati_gruppo'] views.py @login_required def creaScheda(request): if request.method == "POST": form = CreaSchedaForm(request.POST) if form.is_valid(): scheda … -
Python/Django 'DEFAULT_PERMISSION_CLASSES' Syntax Error
I'm trying to get my Django project up and running but keep getting the error below when I run the code in the virtual environment. What could be the problem? Thanks! Traceback (most recent call last): File "D:\Studio\Python\REST\elections\manage.py", line 22, in <module> main() File "D:\Studio\Python\REST\elections\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ....... ....... File "D:\Studio\Python\REST\elections\elections\settings.py", line 50 'DEFAULT_PERMISSION_CLASSES': ( ^ SyntaxError: invalid syntax -
How can I display the image to the desired product category? (if there are two separate models (Product and Image))
I can't figure out how to connect two models (product and images) in views and output images in html. At the moment, several images are loaded for a specific project (for example, photos of a 3D model) all this through the admin panel. There are several projects, that is, 3D models, engineering and so on. And now I can't display 1 of those uploaded images on my site for each product (project). That is, either all the images that were uploaded are displayed (both 3d models and books and engineering). Or if you use model.objects.first () displays the very first uploaded image( that is, the same for all projects). My models: class Portfolio (models.Model): modeling='Modeling' books ='Books' engineering='Engineering' category_ch = [ (modeling, 'Modeling'), (books, 'Books'), (engineering, 'Engineering'), ] category = models.CharField('Category',max_length=100,choices=category_ch, default=modeling) name = models.ForeignKey (Teams, related_name='maked', on_delete=models.PROTECT,blank=True) short_discription = models.CharField("Name of the work", max_length=200, blank=True) discription = models.TextField('Discription', blank=True) сustomer = models.CharField('Customer', max_length=100, default='Заказчик') created = models.DateTimeField('Date',auto_now_add=True) class Meta: verbose_name= 'Portfolio' verbose_name_plural = 'Portfolios' def __str__(self): return self.short_discription #def get_absolute_url(self): #return reversed ('shop:product_detail', args=[self.category.slug, self.slug]') class Image(models.Model): image = models.ImageField('Picture of work', upload_to='products/%Y/%m/%d', blank=True) product = models.ForeignKey(Portfolio, default=None, related_name='image', on_delete=models.PROTECT) Views: def portfolio_page(request): portfolio = Portfolio.objects.all() image_work= Image.objects.all() ctx … -
Django Rest Framework: Register pure function-based views with router so it appears under API root
This is my views.py: class ChoicesViewSet(viewsets.ModelViewSet): queryset = SingleChoice.objects.all() serializer_class = SingleChoiceSerializer ... class AssessmentTakersViewSet(viewsets.ModelViewSet): queryset = AssessmentTaker.objects.all() serializer_class = AssessmentTakersSerializer ... @api_view(['POST']) @parser_classes((JSONParser,)) def studio_create_view(request, format=None): """" A view that accept POST request with JSON content and in turn build out the questions and choices. Post with application/json type. """ ... This is my urls.py: urlpatterns = [ # http://localhost:8000/survey/api/studio-create path('api/studio-create', views.studio_create_view, name='studio-create-api'), ] # drf config router = routers.DefaultRouter() router.register('api/choices', views.ChoicesViewSet) router.register('api/assessment-takers', views.AssessmentTakersViewSet) urlpatterns += router.urls This works functionally, and is considered feature-complete, but but because studio-create_view is not registered with the router, the path doesn't show up under the API Root which isn't great documentation wise. In other words, the API root from Django Rest Framework isn't aware of the path, and a GET request to the root would list only: http://localhost:8000/survey/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "api/choices": "http://localhost:8000/survey/api/choices/", "api/assessment-takers": "http://localhost:8000/survey/api/assessment-takers/", ... } My question is, outside of viewsets that inherit from ModelViewSet, how do we get the custom views like studio_create_view to be registered with the router that Django Rest Framework provide so it's listed under the API root? One would be inclined to try something like: router.register('api/studio-create', views.studio_create_view, …