Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to duplicate a <details> tag containing a Django Form in HTML5?
I am making an application that accepts a list of family members wherein the head of the family can register every single member. For every member entry, there is a form that accepts their name, age, etc. Then, there is an Add Member option that would just duplicate the form. I figured out a way to duplicate the forms, but the app looks too messy when there are many form duplicates, so I used the details tag to give the user the option to hide other form duplicates to make it look cleaner. Here's a part of my html code: {% extends "registrationForm.html" %} {% load static %} {% block content %} {{ formset.management_form }} <details open> <summary>Member 1</summary> <div id="form_set"> {% for form in formset.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> </details> <input type="button" value="Add Member" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> <details open> {{ formset.empty_form }} </details> </table> </div> {% endblock %} What happens in my approach is, every time I click Add Member, it duplicates the form but it is not inside the details tag, and also the new empty form is also inside the first details tag which is … -
is there a way to define a customized method inside a Django class based view to handle requests at a specific URL?
What I have for now? in the urls.py file, I defined: path('groups', views.GroupView.as_view(), name="group"), I have a GroupView class to handle requests at /groups endpoint in view.py file, inside of which there are some methods to handle HTTP requests: class GroupView(APIView): def get(self,request) def post(self, request) def patch(self, request) What I'm trying to do: having a method to only deal with patch requests and only accept requests at 'groups/join' URL. I'm wondering if it's possible to define another customized method just inside the current class based view to implement this (instead of having another standalone function based view), I'm expecting something like: class GroupView(APIView): def get(self,request) def post(self, request) def patch(self, request) **def patch_join(self, request, url='/join')** Is this possible in Django? Thanks! -
Python update fields with matching name
I have three (or more in the future) integer fields with similar names: class Statistic(models.Model): first_count = models.IntegerField(default=0) second_count = models.IntegerField(default=0) third_count = models.IntegerField(default=0) I get a variable that tells me which one to update. If variable == "first" increment first_count, if variable == "second" then increment second_count... I am wondering, if there is a better way to do this? To paint you a better picture, this is what i would want to do: Statistic.variable+"_count" = Statistic.variable+"_count" + 1 #increment value But i do realize, that this wouldnt work and would also be a very bad practice. Is there a simpler solution I am not seeing? Thanks in advance -
mod_rewrite + django causing incorrect redirect URLs post login
I have a Django project with an app named "Survey" - it is desired that URLs such as http://example.com/Surveys/ViewInspection/1 are accessible via http://example.com/Inspections/ViewInspection/1. Using Apache 2.4 and mod_rewrite, I have the following set of rules in place to allow this: RewriteEngine On RewriteRule ^/Inspections(.+)$ /Surveys$1 [PT] and all appears to work fine, except where a non-authenticated user attempts to access the above URL (the view for which has the @login_required decorator. At this point, the user is bounced to the login screen with parameters: /Auth/Login?next=/Ins/Surveys/ViewInspection/1 After a bit of digging, "/Ins/Surveys/ViewInspection/1" is the value for request.path, whereas request.path_info is correctly set as /Surveys/ViewInspection/1 - the Auth code is taking .path and getting it wrong. If I use a shorter string than "Inspections" the Ins part decreases until disappearing, when it all works fine. mod_rewrite logs look correct in this instance: [Tue Feb 23 23:52:49.617840 2021] [rewrite:trace2] [pid 2760:tid 140156097316608] mod_rewrite.c(483): [client 213.18.147.204:4054] 213.18.147.204 - - [hostname/sid#7f78a4651338][rid#7f78a53910a0/initial] init rewrite engine with requested uri /Inspections/ViewInspection/2 [Tue Feb 23 23:52:49.617906 2021] [rewrite:trace3] [pid 2760:tid 140156097316608] mod_rewrite.c(483): [client 213.18.147.204:4054] 213.18.147.204 - - [hostname/sid#7f78a4651338][rid#7f78a53910a0/initial] applying pattern '^/Inspections(.+)$' to uri '/Inspections/ViewInspection/2' [Tue Feb 23 23:52:49.617940 2021] [rewrite:trace2] [pid 2760:tid 140156097316608] mod_rewrite.c(483): [client 213.18.147.204:4054] 213.18.147.204 - - … -
When I try to add a new product to my PRODUCTS group in the Django Admin site it gives me a no such table: main.auth_user__old error
I've been learning python and Im having a problem when I try to add another product in the admin page for Django. When I try to save the new product it brings me to a page that says OperationalError at /admin/products/product/add/ no such table: main.auth_user__old. I've been looking around and Ive found no fix for the problem I would like some help. This is some of the code. This is my models.py code. from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=4036) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() This is the main url.py code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] This is the secondary url.py code in my products folder from django.urls import path from . import views # # /products/1/detail # /products/new urlpatterns = [ path('', views.index), path('new', views.new) ] This is the views.py code from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def new(request): return HttpResponse('New Products') and finally this is the admin.py code from django.contrib import admin from.models import Product admin.site.register(Product) Does anyone know a fix for … -
How to make urls form one app seen by the other?
I did the following: Created an app usergui Included it in settings: INSTALLED_APPS = [ #default 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #local 'ticketsdb.apps.TicketsdbConfig', 'usergui.apps.UserguiConfig' ] Created urls.py inside usergui` from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.auth.as_view(), name="auth") ] Modified urls.py in the main folder as following: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include(usergui.urls)), path('admin/', admin.site.urls) ] And I am getting an error: File "/home/me/Desktop/ticketing/ticketing/ticketing/urls.py", line 5, in <module> path('', include(usergui.urls)), NameError: name 'usergui' is not defined Why does it not recognize the app? -
Django custom login, how can I add ForeignKey to REQUIRED_FILED
I tried to create a custom login for Django, and one of the fields in User(AbstractBaseUser) class User(AbstractBaseUser): user_email = models.EmailField(verbose_name='Email right here', max_length=70, unique=True, primary_key=True) password = models.CharField(max_length=256) password_salt = models.CharField(max_length=15) create_date = models.DateTimeField(auto_now=True) role = models.ForeignKey(Roles, on_delete=models.PROTECT) info = models.ForeignKey(PersonalInfo, on_delete=models.CASCADE) USERNAME_FIELD = 'user_email' #username REQUIRED_FIELDS = [info.lastname, info.firstname] #email and pass is required by defaut object = UserManager() def __str__(self): """ Return user email """ return self.user_email def get_email(self): """ Return user email """ return self.user_email def get_info(self): """ return user info """ return self.info I have my PersonalInfo model like this class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) work_email = models.EmailField(verbose_name=' email', blank=True) email = models.EmailField(blank=True) lastname = models.CharField(max_length=50, db_column='Last name', verbose_name="Last name") firstname = models.CharField(max_length=50, db_column='First name', verbose_name="First name") address = models.CharField(max_length=255, null=True, blank=True) work_phone = models.CharField(max_length=20, null=True, blank=True, db_column='Work Phone', unique=True) cell_phone = models.CharField(max_length=20, null=True, blank=True, db_column='Cell Phone', unique=True) home_phone = models.CharField(max_length=20, null=True, blank=True, db_column='Home Phone', unique=True) note = models.CharField(max_length=1000, null=True, blank=True) class Meta: db_table = 'PersonalInfo' def __str__(self): """ return lastname and firstname """ return self.firstname + ' , '+ self.lastname and I got this ERROR : REQUIRED_FIELDS = [info.lastname, info.firstname] AttributeError: 'ForeignKey' object has no attribute 'lastname' How can I use info.lastname, and info.firstname … -
is there a way to combine using scala and python
So i am thinking of learning Scala, I'm quite proficient at python use it quite often and want to diversify my skills a bit. Is it possible that I can use python for a web app say a combination of django/flask [python}, html and css and js for front end and some scala for all the data analysis ? -
Custom AutoField Integer Sequence in Django
I have Django with default IDs, and I want to distribute the system without use of random UUIDs. I take that in my use case, the number of servers won't exceed a N=1000, so, I'd like to reserve IDs sub-sequences to each server, so that: SERVER 1 would have IDs 1001, 2001, 3001,... SERVER 2 would have IDs 1002, 2002, 3002, etc. I'd like to do that globally, including all models, even Django system models, so I've defined a function to get the last ID of the subsequence, like: # Used to split primary key spaces. SERVER_ID = int(os.getenv('SERVER_ID', 1)) # Function to compute different next primary key for each server: def DB_NEXT_PK(Model): ID_LENGTH = 3 FACTOR_10 = 10**ID_LENGTH last = Model.objects.filter(id__endswith=f'%.{ID_LENGTH}d' % SERVER_ID).last() if last is not None: return ((last.pk // FACTOR_10) + 1) * FACTOR_10 + SERVER_ID else: return FACTOR_10 + SERVER_ID So, suppose I want to use such or equivalent function for the IDs. How would I have to override the django.db.fields.AutoField to properly do this? I found the latest Django 3.2, here has an option to customize AutoField, but I don't quite get how it is best to do to accomplish this. I'm currently looking into … -
(subprocess on Dokku) FileNotFoundError: [Errno 2] No such file or directory: 'node'
I deployed a Django app to dokku, which has a functionality that needs to execute a script using node. This functionality is called via subprocess: subprocess.check_output( [ "node", "-r", "esm", "path/to/script", script_argument, ], ) This runs fine in local. In production, I get: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/app/elearningapp/views.py", line 325, in add_question new_question = form.save() File "/app/elearningapp/forms.py", line 72, in save instance = super(QuestionForm, self).save(self) File "/app/.heroku/python/lib/python3.8/site-packages/django/forms/models.py", line 460, in save self.instance.save() File "/app/elearningapp/models.py", line 202, in save self.rendered_text = tex_to_svg(self.text) File "/app/elearningapp/utils.py", line 29, in tex_to_svg res = subprocess.check_output( File "/app/.heroku/python/lib/python3.8/subprocess.py", line 411, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "/app/.heroku/python/lib/python3.8/subprocess.py", line 489, in run with Popen(*popenargs, **kwargs) as process: File "/app/.heroku/python/lib/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/app/.heroku/python/lib/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) 15.734401568Z app[web.1]: FileNotFoundError: [Errno 2] No such file or directory: 'node' The error is pretty straightforward, but I still don't understand why it's taking place. Node is installed on my vps. Is there any tinkering I need to do with the … -
How to pass a User Certificate from NGINX Reverse server to a different server running NGINX?
I have two total separate servers, ServerA and ServerB. ServerA is serving as the NGINX Reverse Proxy Server using Docker/Docker-Compose. Here is ServerA's docker-compose.yml file: version: '3.5' services: proxy: build: ./ # image: nginx:1.19-alpine container_name: proxy ports: - 80:80 - 443:443 restart: unless-stopped Here is the Dockerfile contents: FROM nginx:1.19.0-alpine # Remove default configuration RUN rm /etc/nginx/nginx.conf RUN rm /etc/nginx/conf.d/default.conf # New default conf containing the proxy config COPY ./default.conf /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/nginx.conf # Backend not found html response COPY ./backend-not-found.html /var/www/html/backend-not-found.html # Nginx Proxy and SSL shared configs COPY ./includes/ /etc/nginx/includes/ Here is the content of nginx conf, nginx.conf: user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 4096; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } The main configuration of the proxy comes from this file, default.conf: # 80 Redirect server { listen 80; listen [::]:80; server_name localhost $host; return 301 https://$host$request_uri; } # ServerB proxy config for app running on port 443. stream { } server { listen 443 ssl; server_name App1.CUSTOMDOMAIN.org; # Configure SSL ssl_certificate … -
tweaking LoginRequiredMixin django
I have a custom user model extending Abstract User. There is another model storing the user types. There are two types of users: clients(id is 1) and Professional(id is 2). I am trying to restrict the professionals from seeing a few links. These links are classified to the clients only. I am trying to tweak the LoginRequiredMixin and use it in my views. Here is the Mixin I wrote: from django.shortcuts import redirect, render from django.contrib.auth.mixins import AccessMixin class ClientLoginMixin(AccessMixin): def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated or not request.user.usertype_id == 2: return render(request, 'clients/restricted.html') return super().dispatch(request, *args, **kwargs) Here is the original Mixin: from django.shortcuts import redirect, render from django.contrib.auth.mixins import AccessMixin class ClientLoginMixin(AccessMixin): def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return render(request, 'clients/restricted.html') return super().dispatch(request, *args, **kwargs) Here are the models: class UserList(AbstractUser): UserMiddleName = models.CharField(max_length=100, null=True) usertype = models.ForeignKey(UserType, on_delete=models.CASCADE) Application = models.ForeignKey(AppliationList,on_delete=models.CASCADE, null=True) class UserType(models.Model): UserType = models.CharField(max_length=15, choices=user_type, default="Customer") UpdatedDate = models.DateField(auto_now_add=True) But this gives me an error User has no attribute usertype_id. I tried printing the user and there was a usertype_id present. {'Application_id': 2, 'ContactCell': '8697707501', 'UserMiddleName': None, 'date_joined': '2021-02-19T18:46:03.966', 'email': 'ankur@gmail.com', 'first_name': 'Ankur', 'id': 1, 'is_active': True, 'is_authenticated': True, 'is_staff': … -
'NoneType' object has no attribute 'items' Error
I've tried to reuse some code from a previous project and am now getting an error: 'NoneType' object has no attribute 'items' Before I show you this code, I need to warn you that there's some really sloppy code in it as I'm new to wagtail and even programming so some bits need to be refactored! haha Blocks.py: from django import forms from wagtail.core import blocks from wagtail.core.blocks import StructBlock from wagtail.images.blocks import ImageChooserBlock from wagtail.contrib.table_block.blocks import TableBlock from django.db import models from wagtail.core.models import Page from wagtail.images.blocks import ImageChooserBlock from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel, StreamFieldPanel from wagtail.images.edit_handlers import ImageChooserPanel from django.core.exceptions import ValidationError from wagtail.core.fields import StreamField from django.core.exceptions import ValidationError from django.forms.utils import ErrorList class RadioSelectBlock(blocks.ChoiceBlock): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.field.widget = forms.RadioSelect( choices=self.field.widget.choices ) # Create your models here. class TitleBlock(blocks.StructBlock): text = blocks.CharBlock( required= True, help_text = 'Text to display' ) class Meta: template = "streams/title_block.html" icon = "edit" label = "Title" help_text = "Centered text to display on a page" class LinkValue(blocks.StructValue): ## Additional login for links to simplify the template logic and only have one value for the # link depending on which is entered i.e. an internal … -
query filter django equivalent mysql
What is the equivalent of this SQL statement in django? SELECT * FROM names WHERE CONCAT(name, ' ', last_name) LIKE '%Lennon%'; -
Missing Patch method with corsheaders only on chrome
I have a Django app that's using corsheaders package and its in settings.py like this: INSTALLED_APPS = [ ..., corsheaders, ...] ... MIDDLEWARE = [ # on top "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ... ] ... CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True When I'm trying to do a PATCH request on Google Chrome after the OPTIONS method I get this: The Access-Control-Allow-Methods is missing PATCHand the next request fails with CORS methods error. But I tried the same method on Firefox and its working as intended. -
How to send websocket deferred group messages with Django Channels?
I'm creating browser game on Django Channels. Player of which must answer the question during 1 minute. First of all I send event with question and then want to send message with minute delay. I'm using RedisChannelLayer and JsonWebsocketConsumer. class RoomConsumer(JsonWebsocketConsumer): def connect(self): room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'game_' + room_name async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() self.send_json(connection_event()) def send_message(self, event): self.send_json(event.get('data')) def receive_json(self, data, **kwargs): try: print(data) event_type = data.get('eventType') if event_type == 'start': tasks = [] ... async_to_sync(self.channel_layer.group_send)(self.room_group_name, { 'type': 'send_message', 'data': start_event(tasks) }) # here want to send deferred message except Exception as e: print(e) Was planing to do it with async sleep, but need to be able to pause and play this message or stop and resend with new delay. async def send_delayed_message(self, event): await sleep(60) await self.send_json(event.get('data')) Do you have cases to send such messages with delay with no stoping consumer? -
Django media play not able to play video in middle or chosen time
I am playing a video using django media get but the problem is that if I try to start watching video in middle, the video start at biggning. <video> <source src="{{ video.uploaded_video.url }}" type="video/mp4" /> </video> What advices will help me to allow play it on an duration/time of video I want? -
How to return list of ID-s with Django Rest framework serializer?
With this type of serializer, I got as an ID value inside the post object of the id of the user that made the post but I want a list of users that liked the post. Following Django documentation, I think that it should look like this but apparently, something is wrong. User = get_user_model() class StudentSerializer(serializers.ModelSerializer): class Meta(UserCreateSerializer): model = User fields = ['id', 'name', 'email' ] class ProjectSerializer(serializers.ModelSerializer): class Meta: model = ProjectPost fields = ['id', ... 'published',] class LikeSerializer(serializers.ModelSerializer): class Meta: model = Like fields = ['id'] class PostSerializer(serializers.ModelSerializer): student = serializers.SerializerMethodField() project = serializers.SerializerMethodField() likes = serializers.SerializerMethodField() class Meta: model = Post fields = ['id', 'student', 'project', 'likes'] def get_like(self, obj): return LikeSerializer(obj).data def get_student(self, obj): return StudentSerializer(obj.student).data def get_project(self, obj): return ProjectSerializer(obj.project).data And here are my Models User = get_user_model() class Post(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="student") project = models.OneToOneField(ProjectPost, on_delete=models.CASCADE, default=None, null=True, blank=True) #bookmark = models.ManyToManyField(User, blank=True, related_name='bookmark') def get_student(self): return self.student.name class Like(models.Model): user = models.ForeignKey(User,unique=True, on_delete=models.CASCADE, default=None, null=True, blank=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, default=None, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def get_user(self): print(self.user.id, 'aaa') return self.user.id -
invalid hook call on data retrieved by axios
I'm trying to retrieve the JSON data from here and then update the state in a functional component. Even though the code seems fine I'm getting an error saying its an invalid hook call. On the react documentation it said that I might have 2 different react apps in the same folder however I checked it with the command they gave and there was only 1. However I am running this from a django server and there is a different react app in a different django app (so in a completely different folder). const App = () => { const [posts, setPosts] = useState([]); useEffect(() => { let url = "https://jsonplaceholder.typicode.com/posts"; axios.get(url).then(res => { console.log(res.data); // The code crashes here saying that it is an invalid hook call useState(res.data); }).catch(err => console.log(err)); }, []); return ( <div> This is just a place holder. </div> ); } I have a feeling this might have something to do with the other react application in the django project but if anyone can see something that I can't I would appreciate the help. -
Django 3: is_valid() is always false using FileField and FloatField
I am trying to make a simple form in Django that accepts some file upload fields and a few float fields. However, when I run this in my browser, the is_valid() never gets triggered even when all forms are filled in. I have looked through the Django docs and have tried to recreate the examples as much as possible, but I can't figure out what is wrong. I know that the is_valid() is not true because the page does not redirect to another page when submit is pressed. Also, if I go into the admin page, no instances of MyModel are made. Here is my code. models.py: from django.db import models # Create your models here. class MyModel(models.Model): file1 = models.FileField() file2 = models.FileField() x = models.FloatField() y = models.FloatField() z = models.FloatField() def __str__(self): return self.file1 forms.py: from django import forms from django.forms import ModelForm from .models import MyModel class MyForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' views.py: from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import MyForm # Create your views here. def index_view(request): if request.method == 'POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('some_page') else: form = DocumentsForm() return … -
Django save form with m2m field
TypeError: 'NoneType' object is not iterable this is model class Package(models.Model): id = models.UUIDField(u'Ид', primary_key=True, default=uuid.uuid1) region_code = models.IntegerField(u'Код региона', default=APP_REGION_CODE[:2], help_text='PackageUUID') persons = models.ManyToManyField(Person, verbose_name=u'Персоны', null=True, related_name='packages') model Person is simple name surname and primary key auto field class PackageForm(ModelForm): class Meta: model = Package fields = ('id', 'region_code', 'persons') widgets = { 'id': widgets.TextInput(attrs={'size': 30}), 'persons': widgets.CheckboxSelectMultiple(attrs={'size': 30}) } this is part of view that proccess form if request.method == 'POST': form = PackageForm(request.POST) # проверяем коррекность введенных данных и сохраняем. Связанные модели будут привязаны к пакету if form.is_valid: form.save() messages.append(u'Операция прошла успешно!') return HttpResponseRedirect(reverse_lazy('list')) else: form = PackageForm() form.fields['persons'].queryset = Person.objects.all() in debugger i get after post request request.POST['persons'] = u'1933' but form.cleaned_data { 'id': UUID('3102af8c-7614-11eb-ad4a-107b4493a520'), 'persons': None, 'region_code': 66} why form don't set persons field from POST data? -
view can't find objects
Hi I have a article model and I want to show my 5 newest articles. when I go to the url I give not fount error but i have 5 articles i don't know why doesn't show me. class Article(models.Model): page_title = models.CharField(max_length=200, null=True, blank=True) article_title = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique=True, allow_unicode=True) image = models.ImageField(upload_to='articles_pic/%Y/%m/%d/') content = RichTextUploadingField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) show = models.BooleanField(default=True) def __str__(self): return self.article_title . class NewestArticles(generics.ListAPIView): queryset = Article.objects.filter(show=True).order_by('-created')[:5] serializer_class = ArticleSerializer permission_classes = (AllowAny,) . path('new_articles/', views.NewestArticles.as_view(), name='new_articles') -
My python manage.py runserver Not Working?
recently I have been learning Django and what I did was: 1 pip install Django 2 make a file 3 run server My code was: python manage.py runserver but when I wanted to make the server it showed 'python' is not recognized as an internal or external command, operable program, or batch file. please someone help (Am very noob at Django ) -
How to call a function after creating object in Django Rest Framework?
I have a tour and a group model. Whenever a new group gets created I would like to adjust the tour size fields. If I understood correctly, the dispatch() method is the right place for this. However I receive following error: AttributeError at /booking/newgroup/ 'WSGIRequest' object has no attribute 'data' def reduceTourSize(id, pers): t = Tour.objects.get(id=id) t.available_size = t.available_size - int(pers) t.current_size = t.current_size + int(pers) t.save() return t.current_size class NewGroup(generics.CreateAPIView): serializer_class = GroupListSerializer queryset = Group.objects.all() def dispatch(self, request, *args, **kwargs): myresult = reduceTourSize(request.data['tour'], request.data['persons']) return Response(data={"current_size": myresult}) So how can I access the parameters passed in via POST? -
return error in front when permissions enable django rest
I have a view with permission_classes enabled class ProjectCopyView(APIView): permission_classes = [IsAuthor] class IsAuthor(BasePermission): '''Проверка права на авторство проекта''' message = "Only the author of the project can share it" def has_permission(self, request, view): try: if Project.objects.get(id=view.kwargs['project_id'], user=request.user): return True except: return False This works in postman, but when I try to repeat this request for js the error Access to fetch at 'http://127.0.0.1:8080/api/editor/project/1/copy/' from origin 'null' has been thrown blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. Django console gives 401 unautorized async function testSizze(){ const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9" }, body: JSON.stringify({ "to_user": "admin@mail.ru", "permission": ["read"], "all_users": "False" }) }); const json = await res.json(); console.log(json) }