Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to construct url path with two detailview
I have following url patterns urlpatterns = [ path('', CategoryListView.as_view(), name='forum'), path('category/<int:pk>/', CategoryDetailView.as_view(), name='forum-detail'), ] Inside the CategoryDetailView I will list the posts related to that category. So, when I click the any of the post I want the post detail view inside the category, because when I will create post with CreateView class I want category already predefined. I could also do the following path('post/<int:pk>/', ForumPostDetailView.as_view(), name='forum-post-detail'), path('post/new/', ForumPostCreateView.as_view(), name='forum-post-create'), ] In this case user should choose the category by himself when he or she will try create the post. But I want the category to be chosen already something like this ( I know this is wrong) path('category/<int:pk>/post/<int:pk>/', ForumPostDetailView.as_view(), name='forum-post-detail'), path('category/<int:pk>/post/new/', ForumPostCreateView.as_view(), name='forum-post-create'), ] So how to do it? -
How to allow access to base without permissions in django
How can I allow access to the base route while I have my Default permission classes set to IsAuthenticated in the global settings. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', # 'rest_framework.permissions.AllowAny', 'rest_framework.permissions.IsAuthenticated', ], } I know you can just set permission_classes = [AllowAny] in the individual views. But I want my base route to have the same i.e no permissions. Here is how i have the routes set in urls.py router_public = DefaultRouter() ''' PUBLIC ROUTES HERE ''' router_public.register( r'cars', car_viewset.Car_Public_Viewset, base_name='Cars') router_public.register( r'planes', plane_views.Plane_Public_ViewSet, base_name='Planes') urlpatterns = [ path('admin/', admin.site.urls), path('api/admin/', include(router_admin.urls)), path('api/public/', include(router_public.urls)), ] Since I have set permission_classes for cars and planes to AllowAny in the vews, I can access them without Authentication. How can I do the same for the base route http://localhost:8000/api/public/ since there's no view associated with it. -
Auto add user firstname in author field in django with custom User model
I created Custom User model in django using below code class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_("Username"), max_length=50, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] objects = CustomUserManager() def __str__(self): return self.email And I also created another model for user profiles like below. class UserProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) first_name = models.CharField(_("First name"), max_length=50) middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True) last_name = models.CharField(_("Last name"), max_length=50) dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False) profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True) webiste_link = models.URLField(_("Websites"), max_length=200, null=True, blank=True) At last I created another model for Category like below. class Category(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_( "Author"), on_delete=models.CASCADE, related_name='blog_category') title = models.CharField(_("Title"), max_length=50) I want to auto save logged in user full name instead of user email address. By the way i used below code to auto save logged in user. It works but It only save user email address. But I want user full name instead of email or username. obj.author = request.user super().save_model(request, obj, form, change) -
django.db.utils.IntegrityError: duplicate key value violates unique constraint, while 2 of 4 rows are different
I have a row in the DB that is: order_id: product_type_id: is_child: child_type_id: 1 2 True 3 I want to add a row with this code: order = 1, product.parent = 2 order_item = OrderItem.objects.create(order=order, product_type=product.parent, child_type_id=None, is_child=False) but it raises this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "order_orderitem_order_id_product_type_id_ee5c1733_uniq" DETAIL: Key (order_id, product_type_id)=(1, 2) already exists. while 2 of 4 rows are different, why I face this problem? -
What is causing this error in Django: NOT NULL constraint failed: mainapp_comment.post_id
I am in the middle of making a social network web application in Django. I have nailed most of the features needed, but I am stuck on making the commenting system work. I originally had it so users could make their own name for comments, but decided against that. The posting system has it, so the user who is logged in and makes the post, their name will be displayed for the author of the post. That's why some of the code is copy-pasted between the 2. I have tried all kinds of things, such as making the view a class instead of a function. It didn't work, and I am back to square one. Right now the user can make a post no problem, however the user's name isn't recorded and I have to set the author manually in the admin interface. The relevant code in views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'mainapp/post_details.html' form_class = PostForm model = Post def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('mainapp:post_detail',pk=post.pk) def form_valid(self, form): form.instance.author = self.request.user … -
Saving modelform gives 'NoneType' object is not iterable error
I'm showing a form and formset in one template and trying to save each. Formset would save fine but when I add the form, it gives 'NoneType' object is not iterable error. Django shows I'm erroring at this stage and Chrome shows my variables as folows. po = purchaseorder_form.save() ▼ Local vars Variable Value ProductBatchFormset productbatch_formset purchaseorder_form request submitted False # forms.py class PurchaseOrderForm(forms.ModelForm): class Meta: model = PurchaseOrder fields = '__all__' issuedAt = forms.DateField( widget=forms.DateInput(format='%Y%m%d', attrs={'placeholder': 'YYYYMMDD'}), input_formats=('%Y%m%d', ) ) referencePurchaseOrders = forms.ModelChoiceField(widget=forms.SelectMultiple, queryset=PurchaseOrder.objects.all(), required=False) internalManager = forms.ModelChoiceField(queryset=CustomUser.objects.all(), required=False) issuedBy = forms.ModelChoiceField(queryset=Company.objects.all(), required=False) issuedTo = forms.ModelChoiceField(queryset=Company.objects.all(), required=False) productSpendType = forms.ModelChoiceField(queryset=ProductSpendType.objects.all(), required=False) class ProductBatchForm(forms.ModelForm): class Meta: model = ProductBatch fields = '__all__' product = forms.ModelChoiceField(queryset=Product.objects.all(), required=False) quantity = forms.CharField(required=False) unitprice = forms.CharField(required=False) unitcurrency = forms.ModelChoiceField(queryset=Currency.objects.all(), required=False) productSpendType = forms.ModelChoiceField(queryset=ProductSpendType.objects.all(), required=False) # models.py class PurchaseOrder(models.Model): def __str__(self): return str(self.pk) purchaseOrderId = models.CharField(max_length=30, null=True, blank=True, db_index=True) issuedBy = models.ForeignKey('users.Company', null=True, blank=True, db_index=True, on_delete=models.CASCADE, related_name='issued_POs') issuedAt = models.DateTimeField(null=True, blank=True, db_index=True) issuedTo = models.ForeignKey('users.Company', null=True, blank=True, db_index=True, on_delete=models.CASCADE, related_name='received_POs') referencePurchaseOrders = models.ManyToManyField('self', symmetrical=False, null=True, blank=True, db_index=True, related_name='related_POs') internalManager = models.ForeignKey('users.CustomUser', null=True, blank=True, db_index=True, on_delete=models.CASCADE, related_name='managed_POs') note = models.TextField(max_length=500, null=True, blank=True, db_index=True) class ProductBatch(models.Model): def __str__(self): return str(self.pk) purchaseOrder = models.ForeignKey('PurchaseOrder', null=True, blank=True, db_index=True, on_delete=models.CASCADE) … -
unable to process a function inside a view using navigation bar
I'm making a website using django and i have navigation bar that has a few items when i click on another item which is "delete" I am not able to see the page i intended to see presently the 'insert' tab is my default tab and if i want to see the other link using delete tab i am not able the views file is like this def home(request): form=insert() form1=insert() if request.method=="POST" and 'b1' in request.POST: form=insert(request.POST) if form.is_valid(): form.save() return render(request,'employee/form.html') if request.method=="POST" and 'b2' in request.POST: allobjs=emp.objects.all() return render(request,'employee/form.html',{'form1':allobjs}) if request.method=="POST" and 'b3' in request.POST: allobjs=emp.objects.all().delete() #return render(request,'employee/form.html',{'form1':allobjs}) return render(request,'employee/form.html',{'forms':form,'form1':form1}) def dele(request): return render(request,'employee/emp.html') my code for navigation bar is <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="{%url 'employee-insert' %}">Insert Record</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url 'employee-delete' %}">Delete Record</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Update Records</a> </li> <li class="nav-item"> <a class="nav-link " href="#">Assign Duties</a> </li> <li class='nav-item'> <a class='nav-link' href="">View The duties</a> my app which is called employee has url.py like this urlpatterns = [ path('',views.home,name='employee-insert'), path('',views.dele,name='employee-delete'),] -
i get 500 error in /graphql page in production
I have deployed my django application to server using heroku. Other pages gets loaded but when i try to load /graphql page i get 500 server error. I have even used graphiql mode as True. why am i getting this issue? Here is my urls for it urlpatterns = [ path('admin/', admin.site.urls), path('', pdf_generation), path('graphql', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True))), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) GRAPHENE = { 'SCHEMA': 'config.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], } it works in local environment. Here is the logs 2019-09-08T05:35:45.069808+00:00 heroku[router]: at=info method=GET path="/graphql" host=serene-beach-03946.herokuapp.com request_id=88088a0e-8571-4b18-9986-eb65b1603749 fwd="110.44.125.137" dyno=web.1 connect=1ms service=53ms status=500 bytes=373 protocol=https 2019-09-08T05:35:45.072219+00:00 app[web.1]: 10.65.66.5 - - [08/Sep/2019:05:35:45 +0000] "GET /graphql HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 encors/0.0.6" 2019-09-08T05:43:02.257886+00:00 heroku[router]: at=info method=GET path="/graphql" host=serene-beach-03946.herokuapp.com request_id=79395058-c64b-4576-ba6e-b3684311584d fwd="110.44.125.137" dyno=web.1 connect=0ms service=945ms status=500 bytes=373 protocol=https 2019-09-08T05:43:02.258405+00:00 app[web.1]: 10.113.243.77 - - [08/Sep/2019:05:43:02 +0000] "GET /graphql HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 encors/0.0.6" 2019-09-08T05:43:03.279183+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=serene-beach-03946.herokuapp.com request_id=48c30a98-8581-4bed-ad10-e3d9c39d7353 fwd="110.44.125.137" dyno=web.1 connect=0ms service=26ms status=404 bytes=411 protocol=https -
How to get the whole queryset
I have a model called PostForum class PostForum(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='forum_likes', blank=True) In my class based view I have following code class CategoryDetailView(DetailView): model = Category template_name = 'forum/forum_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = get_object_or_404(Category, id=self.object.id) posts = PostForum.objects.filter(category=category) context['posts'] = posts, return context In template I cant reach posts title or content. I shows nothing {% for post in posts %} {{post.title}} <p>{{post.content}}</p> {% endfor %} when I render {{post}} to see the whole queryset it shows <QuerySet [<PostForum: My first post>]> How to reach posts' title or content -
Invalid signature in Django Rest Frameworl JWT
I've created a custom login view to override obtain_jwt_token view as followed. class LoginView(ObtainJSONWebToken): def post(self, request, *args, **kwargs): user = User.objects.using(self.request.session.get('shop')).get(mobile=str(request.data['mobile'])) if not user.check_password(request.data['password']): return Response({'Error': "Invalid mobile or password"}, status="400") exp = datetime.datetime.now() + datetime.timedelta(seconds=settings.TOKEN_EXP_TIME) exp = int(datetime.datetime.timestamp(exp)) orig_iat = int(datetime.datetime.timestamp(datetime.datetime.now())) if user: payload = { 'user_id': user.id, "username": user.mobile, "exp": exp, "email": "", 'mobile': user.mobile, "orig_iat": orig_iat } jwt_token = {'token': jwt.encode(payload, settings.SECRET_KEY)} return Response(jwt_token, status=status.HTTP_200_OK) else: return Response({'Error': "Invalid credentials"}, status=status.HTTP_400_BAD_REQUEST) response = super().post(request, *args, **kwargs) return response after login token will created successfully but when I want to call an API (from postman) get {"detail": "Invalid signature."} error. I'm using my API using get method and I've added JWT MY_TOKEN in Authorization in header. Any idea? -
how to save dropdown list value to database in django
I am doing an attendance system and the student is able to mark their attendance by looking for their name in the dropdown list value. The student will then press submit and the information will be stored in MarkAtt database. MarkAtt contains: class MarkAtt(models.Model): studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=0) attendance = models.IntegerField(default=1) #1 is present The Template displays the class information, today's date and the student's name in a drop drown list box. <form method="post" enctype="multipart/form-data"> {% csrf_token %} Lab Group: {{group.classGrp}} Day: {{group.day}} Time: {{group.time}} Today's date: {{today.date}} <p>{{form.att.label_tag}} {{form.as_p}} </p> The view: def mark_stud(request, class_id,id): if (not class_id or not id): return HttpResponseForbidden() else: try: classGrp = None information = {} information['studName'] = Namelist.objects.get(name=id) form = studentAttendanceForm(request.POST) if form.is_valid(): att = form.save(commit=False) att.studName = information['studName'] att.currentDate = datetime.datetime.now.date() form.save() return redirect('namelist.html') except ObjectsDoesNotExist: print("no entries") return redirect('namelist.html') return render(request, 'namelist.html', {'information' :information, 'form':form}) However, the form did not display in the template page and i am unable to save the value in the database. Really appreciate your help. Thank you so much. -
Should i start web development with django
I want to start web development and am confused whether i should start with django or not. I am a begineer in web development but have some experience in programming. -
A issue to use URL template tag in django
I am currently learning Django. When I apply a url template tag, I found that the output of the url tag is not what I expected. I have read the Django Documents, but it does not help. <a href ="{% url 'movies:detail' movie.id %">{{ movie.title }}</a> from django.urls import path from . import views app_name = 'movies' urlpatterns = [ path('', views.index, name='index'), path('<int:movie_id>', views.detail, name='detail') ] The output of the url tag is localhost/movies/%7B%%20url%20'movies:detail'%20movie.id%20% which is not as I expected: localhost:8000/movies/1 -
Proper way to authenticate graphql with facebook
I'm doing web application using graphql (ariadne) + Django. Now I want to integrate it with Facebook authentication without using DRF. So I wanted to use jwt. Is there any good practice or suggestions ? What is the proper way of doing authentication in graphql ? -
Django with watchtower region error when deploying to Elastic-Beanstalk
I am attempting to use watchtower with my Django API when deploying to AWS Elastic Beanstalk and I have just about run out of Google pages. When I deploy using AWS EB CLI I get an error stating that: ValueError: Unable to configure handler 'watchtower': You must specify a region. I have tried adding my credentials in multiple ways to try to solve this. I have put them in the settings.py file, the credentials file in the .aws dir (both csv and no extension). Settings.py: import os from datetime import timedelta from boto3.session import Session from boto3 import client # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) AWS_ACCESS_KEY_ID = 'MY-KEy' AWS_SECRET_ACCESS_KEY = 'Shhh Secret Key' AWS_REGION_NAME = 'us-east-2' boto3_session = Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION_NAME) as I stated I also have a dir named ".aws" in my root dir with the credentials: [default] region = us-east-2 aws_access_key_id = key aws_secret_access_key = key My config files: option_settings: - namespace: aws:elasticbeanstalk:container:python option_name: WSGIPath value: Wesbite/wsgi.py - option_name: DJANGO_SETTINGS_MODULE value: Wesbite.settings - namespace: aws:elasticbeanstalk:cloudwatch:logs option_name: StreamLogs value: true container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "python manage.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' option_settings: aws:elasticbeanstalk:application:environment: … -
Can't Figure out the Syntax Error in App.js
I am using this tutorial to install React for the front with an API built in Django. https://sweetcode.io/how-use-djang-react-ap/ My repository for this projects so far is here: https://github.com/AlexMercedCoder/DjangoReactCRM When I npm run dev I get a syntax error in App.js, I've played with it and can't seem to figure it out. The error I get is. ERROR in ./frontend/src/components/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C:\Users\alexm\projects\DjangoReactCRM\drcrm\frontend\src \components\App.js: Unexpected token, expected "," (29:6) 27 | 28 | wrapper ? ReactDOM.render(<app>, wrapper) : null; > 29 | </app> App.js import React, { Component } from "react"; import ReactDOM from "react-dom"; class App extends Component { state = { data: '' }; componentDidMount() { fetch("/api") .then(response => { return response.json(); }) .then(data => this.setState({ data: JSON.stringify(data)})); } render(){ return ( <p>Jason data = {this.state.data}</p> ) } } wrapper ? ReactDOM.render(<app>, wrapper) : null; </app> -
'stripeToken' error when attempting to submit payment form
I'm following an outdate django e-commerce course using django and stripe. The course is about 4 years old so a lot has changed with django and stripe, which has allowed me to do a ton of research on both. I'm at the end of the tutorial and have run into an issue while creating the checkout page and more importantly using stripe to 'Create Charge'. I am receiving the following error message: django.utils.datastructures.MultiValueDictKeyError django.utils.datastructures.MultiValueDictKeyError: 'stripeToken' I read in the documentation for Creating Charge which states token = request.POST['stripeToken'] # Using Flask is for Flask (I think), however when i remove ['stripeToken'], I receive this error message: stripe.error.InvalidRequestError stripe.error.InvalidRequestError: Request req_kikB88HKbEkq9W: Could not find payment information I need a way to pass Stripe the payment information when the form is submitted. Also, I came across this post but the publisher was receiving error message do to multiple forms view.py from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render import stripe stripe.api_key = settings.STRIPE_SECRET_KEY # Create your views here. @login_required def checkout(request): publish_key = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': token = request.POST['stripeToken'] stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, statement_descriptor='Custom descriptor', ) context = {'publish_key': publish_key} template = 'checkout.html' return … -
overriding __getattr__ on model breaks django-model-utils InheritanceManager
I am using django-model-utils package and I am trying to override getattr on a model for which i am also defining a InheritanceManager on. I have multiple models inheriting from this same model and i am calling .select_subclasses() on the parent model to get a queryset of child models. The problem is that the InheritanceManager is doing a try/except on ObjectDoesNotExist exception while my getattr raises a AttributeError exception (which is the standard). This causes the queryset to fail since the AttributeError is not caught by the InheritanceManager. Any ideas on how i can resolve this. I don't think i want to raise ObjectDoesNotExist in my getattr method.. but am not sure what else to try. Thanks! -
space between paragraph missing after looping in a <div>?
Im trying to make it so that if my textfield has a {startformat}, it will make the following text look like code and with the change the background. But once it goes in and out of the , any space between paragraph goes missing, making everything one big text. <h2 class="article-title">{{ object.title }}</h2> <p class="article-content"> {% for line in object.content.splitlines %} {% if line == '{startformat}'%}<div class="card-header"><code class="text-dark"> {% elif line == '{stopformat}'%}</code></div> {% else %}{{line}} {% endif %}{% endfor %} </p> Output!!! Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. … -
Add custom fields in Django admin for every model
I'm working on my personal website and wanted to handle both frontend and database translations (ie having everything in 2-3 languages). While there are already quite a few third-party apps for handling translation in the database, I thought it'd be both fun and interesting to build my own. I'm at the last step. So far, everything's been working fine. Here's a quick recap on how it works (skipping over a few things): I have a "translation" app in my django project It provides a few different tables, most notably : Language: list of available languages Item: equivalent to saying "This is the 'name' field for the instance 33 of the 'Job' model" Translation: a ManyToMany between Languages and Items. Basically all the translations for a given item. This app provides an abstract model called "Translation model" Every model from your regular apps that have fields to be translated must inherit from this model Through signals and FK relationship, the app then handles both the creation and deletion of entries in the Item and Translation tables (automatically) Ok so let's say we have a "Job" model that has 2 fields that must be translated: title and description. Now whenever I create … -
Limiting the queryset RelatedFields to only currently related objects
I am overriding the get_queryset function in serializers.PrimaryKeyRelatedField to something like this achieve what I described in the title: def get_queryset(self): queryset = self.queryset return queryset.filter(**{str(self.root.instance._meta.verbose_name_plural) : self.root.instance}) This feels like an extremely hacky way to achieve it. Is there a cleaner syntax for getting related objects given a queryset and a root instance? I want the function to be generic so I can use it elsewhere. Or is there a rest framework's recommended way of setting queryset? -
The requested URL / was not found on this server. (Django)
While deploying my Django project using apache2 following this tutorial: https://pythonprogramming.net/deploying-to-server-django-tutorial/ I am getting Not Found The requested URL / was not found on this server. /var/www/portfolio/portfolio/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from main.views import blog_detail, project_detail urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls), path('tinymce/', include('tinymce.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /etc/apache2/sites-available/portfolio.conf <VirtualHost *:80> ServerName myhostname ErrorLog ${APACHE_LOG_DIR}/portfolio-error.log CustomLog ${APACHE_LOG_DIR}/portfolio-access.log combined WSGIDaemonProcess portfolio processes=2 threads=25 python-path=/var/www/portfolio WSGIProcessGroup portfolio WSGIScriptAlias / /var/www/portfolio/portfolio/wsgi.py Alias /robots.txt /var/www/portfolio/static/robots.txt Alias /favicon.ico /var/www/portfolio/static/favicon.ico Alias /static/ /var/www/portfolio/static/ Alias /static/ /var/www/portfolio/media/ <Directory /var/www/portfolio/portfolio> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/portfolio/static> Require all granted </Directory> <Directory /var/www/portfolio/media> Require all granted </Directory> </VirtualHost> I've tried going to /admin and it still 404s -
Exception Type: MultiValueDictKeyError Exception Value: 'username'
I get this error: Exception Type: MultiValueDictKeyError Exception Value: 'username' in POST method in the form. This is the HTML code: <form action="login" method="POST" class="needs-validation" novalidate> {% csrf_token %} <div class="col-md-6 mb-3"> <label for="validationTooltip01">Username</label> <input type="text" class="form-control" id = "username" placeholder = "Username" name="username" required> <div class="valid-tooltip"> </div> </div> <div class="col-md-6 mb-3"> <label for="validationTooltip03">Password</label> <input type="password" class="form-control" id = "pwd" placeholder = "Password" name="pwd" required> <div class="invalid-tooltip"> </div> </div> <button class="btn btn-primary" type="submit">LOGIN</button> </form> and this views.py from django.contrib.auth.models import auth, User from django.http import HttpResponse from django.contrib import messages def login(request): if request.method == "POST": user=request.POST['username'] pwd=request.POST['pwd'] User=auth.authenticate(username=user, password= pwd) if user is not None: auth.login(request,User) return redirect("dashboard") else: messages.info(request, 'Invalid credentials') return redirect('') elif request.method == "GET": return render(request,'login.html') Even I change user=request.POST['username'] pwd=request.POST['pwd'] by user=request.GET['username'] pwd=request.GET['pwd'] there is no change. -
How to use annotate in query set to extract a count of type in a location?
I can't seem to properly use annotate to extract the information I need from my models. I have the follow .model structure: class ArtistWorkPlaceQuerySet(models.QuerySet): def with_related(self): return self.select_related('artist','work', 'place') class ArtistWorkPlaceManager(models.Manager): pass class PersonWorkPlace(models.Model): artist = models.ForeignKey(Artist, verbose_name=_('artist'), related_name='work', on_delete=models.CASCADE) work = models.ForeignKey(Work, verbose_name=_('work'), related_name='place', on_delete=models.CASCADE) place = models.ForeignKey(Place, verbose_name=_('place'), on_delete=models.CASCADE) objects = PersonWorkPlaceManager.from_queryset(PersonWorkPlaceQuerySet)() class Work(models.Model): piece_type = models.CharField(max_length=100, null=True, blank=True) //This is like paintings or sculptures class Artist(models.Model): name = models.CharField(max_length=100) class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) Through this query I can get all of the work by this artist: works = PersonWorkPlace.objects.filter(person=self.kwargs['pk']) How do I go further and search for the number (a count) of works of the same the 'piece_type' at a particular place by the same artist? I would like to pass or extract from context for a particular view the following information: Artist A has 2 painting and 2 sculpture at Place A and 4 paintings at Place B 'context': { (place: 'Place A', painting: '2', sculpture: '2'), (place: 'Place B', painting: '4') } -
How to register new user with curl using djoser?
I am new to djoser and while following a tutorial, I tried to register a new user using the command : curl -X POST http://127.0.0.1:8000/api/users/ --data 'username=example%26password=mysecret' but unfortunately I am getting the output as : {"username":["This field is required."],"password":["This field is required."]} instead of: {"email":"","username":"example","id":1} my urls.py file urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^api/', include('djoser.urls')) ] my settings.py file REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', ] }