Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get Keyerror while set permissions in CustomUserAdmin
Hi I am a Python/Django beginner and have a problem with the implementation of a permission thing. I have also copied this from a tutorial, but it doesn't seem to work within my app. What do I want to achieve: It's about the admin module. There I want that only administrators can change the field with the same name. Should only a user or staff user have logged in, this field should be grayed out. with the following code, this also works wonderfully. However, if I then a new user then create / add I get a Keyerror, which also refers to the built-in code. Attached my code question segments that belong to the topic: admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import JobTitle, JobSkill, SkillSet CustomUser = get_user_model() @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): # see tutorial to this stuff: https://www.youtube.com/watch?v=wlYaUvfXJDc def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser if not is_superuser: form.base_fields["is_superuser"].disabled = True form.base_fields["user_permissions"].disabled = True form.base_fields["groups"].disabled = True return form add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser readonly_fields = ["last_login", "date_joined"] list_display = [ "username", "employed", "email", "job_title", "is_active", … -
RelatedObjectDoesNotExist at /users/edit/ User has no profile
I ran into a situation where I had developed a method called edit and passed both the profile and user forms into it when I wanted to modify a profile. @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user,data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request,'users/edit.html',{'user_form':user_form,'profile_form':profile_form}) this is my views.py where i have written the logic and coming to urls.py path('edit/',views.edit,name='edit'), and the edit.html code follows like this {% extends 'users/base.html' %} {% block body %} <h2>Edit profile form</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit"/> </form> {% endblock %} This is my models.py file from django.db import models from django.conf import settings # Create your models here. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True) def __str__(self): return self.user.username The main project urls.py from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('users/',include('users.urls')) ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) the output shows me like this I am expecting a better solution to resolve this issue -
How properly assign permissions when to user when saving model?
I want to assign Permissions to a user when I Change Group inside the Django admin. I'm adding this permission inside the custom User model in the save method. When I Save changes in the admin panel, no errors are raised, but permissions are not created in my local DB Here is how my model looks like class UserProfile(AbstractUser, PermissionsMixin): name = models.CharField(max_length=255, unique=False, default=None) email = models.EmailField(max_length=50, unique=True) email_verified = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) password = models.CharField(max_length=100, null=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] objects = CustomAccountManager() def is_member(self, group_name: Roles): return self.groups.filter(name=group_name.value).exists() def save(self, *args, **kwargs): if self.is_member(Roles.STAFF): permissions = Permission.objects.filter(codename__in=settings.STAFF_PERMISSIONS) self.user_permissions.add(*permissions) logger.info(f"Permissions {list(permissions)} added for user {self.email}") super().save(*args, **kwargs) For some reason, I can add permissions from CLI when creating a User instance, but not in the save method, what might be wrong here? -
why records are not being inserted into postgresql database in pytest-django?
I tried to use postgres database with pytest-django and I've encountered a problem. I have a fixture named populate_db which creates some records in the database. To check if pytest actually creates records, I put a 60-seconds sleep after creating the model objects and checked the panel admin but none of the created objects were present there. I think the pytest can't connect to my database and doesn't create any records in the database. Below are the functions that I have in my conftest.py file and I have another test file which tries to retrieve a database record from the API. Here is my code for the populate_db fixture: @pytest.fixture(autouse=True) def populate_db(): sport = Vertical.objects.create(name='sport') bazar = Vertical.objects.create(name='bazar') time.sleep(60) yield -
Unknown domain is connected to my server. Is it Bad purpose? [closed]
I am deploying Web application Using Elastic beanstalk Currently I've found out that unknown domain is conneted to my server. Ex) Our service domain is onenonly.io But test.hellobot.com is connected to my server too. Maybe I've got to set Allowed Host to secure it. But I want to know How bad people takeover secret infos by doing this. q1. some weird domain is connected to my server. Is it accident? or bad intention? q2. If it is bad purpose, then how they takeover secret infos by just pointing their domain to my server ip? I am using Application Loadbalancer with assigned Elastic IP. -
Why is for loop not working in django html?
yesterday i wrote an application using for loop that worked exactly as I wanted it to work, but today when I opened it up without changing a thing it is not working. and this is happening every time I try to make something similar. i also tried inspecting the page but I only see an empty div while there is actually for loop inside it. any help would be appreciated. thanksfor loop inspect window I also created new app and did exact same things. i just coppied code and it worked. but when i try to do same in this application it remains the same. -
How to install `distro-info===0.18ubuntu0.18.04.1`?
Trying to modernize an old Django project (2.2), and its requirements.txt (generated via pip freeze) has some lines that make pip install throw fits: distro-info===0.18ubuntu0.18.04.1 I interpreted the errors I got for the first one (see the error output in its entirety at the bottom) as the version string not conforming to PEP-518, but it doesn't even mention the === operator. This SO thread, What are triple equal signs and ubuntu2 in Python pip freeze?, has a similar issue, but: The errors they got is different (ValueError as opposed to my ParseError). The solution was to upgrade pip, but I'm already using the latest one. Now, pip install distro-info works so should I just go with that? update: The project I'm trying to update has been conceived around 2020, and according to the PyPI history of distro-info, it had a 0.10 release in 2013 and a 1.0 in 2021. Could this anything have to do with the weird pip freeze output? (From this PyPI support issue.) The error: ERROR: Exception: Traceback (most recent call last): File "/home/old-django-project/.venv/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py", line 3021, in _dep_map return self.__dep_map File "/home/old-django-project/.venv/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py", line 2815, in __getattr__ raise AttributeError(attr) AttributeError: _DistInfoDistribution__dep_map During handling of the above exception, another … -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f81fe558fa0>": "Post.author" must be a "UserData" instance
I'm trying to write simple tests for some endpoints but the second one keeps failing. Here's the test.py from rest_framework.test import APITestCase, APIRequestFactory, APIClient from rest_framework import status from django.urls import reverse from .views import PostViewSet from django.contrib.auth import get_user_model User = get_user_model() class PostListCreateTestCase(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.view = PostViewSet.as_view({"get": "list", "post": "create"}) self.url = reverse("post_list") self.user = User.objects.create_user( email="testuser@gmail.com", name="testuser" ) self.user.set_password("pass") self.user.save() def test_list_posts(self): request = self.factory.get(self.url) response = self.view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_post(self): print(User) print(self.user) client = APIClient() login = client.login(email="testuser@gmail.com", password="pass") self.assertTrue(login) sample_post = { "title": "sample title", "body": "sample body", } request = self.factory.post(self.url, sample_post) request.user = self.user print(isinstance(request.user, get_user_model())) response = self.view(request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) And here's the view: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() def get_queryset(self): posts = Post.objects.all() return posts def get_object(self): post = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) self.check_object_permissions(self.request, post) return post def create(self, request, *args, **kwargs): try: post = Post.objects.create( title=request.data.get("title"), body=request.data.get("body"), author=request.user, ) post = PostSerializer(post) return Response(post.data, status=status.HTTP_201_CREATED) except Exception as ex: print(str(ex)) return Response(str(ex), status=status.HTTP_400_BAD_REQUEST) def list(self, request, *args, **kwargs): posts = self.get_queryset() serializer = self.get_serializer(posts, many=True) return Response( data=dict(posts=serializer.data, total=len(serializer.data)), status=status.HTTP_200_OK, ) And here's what I get: Found 2 test(s). Creating test database for alias … -
How to select data from filtered Data to send POST request using ModelViewSet in DRF?
I have a model. class MyClass(models.Model): field1 = models.ForeignKey("Class1", on_delete=models.PROTECT) field2 = models.ForeignKey("Class2", on_delete=models.CASCADE) field3 = models.ForeignKey("Class3", on_delete=models.PROTECT) This is my ViewSet: class MyViewSet(ModelViewSet): serializer_class = serializers.MySerializer def create(self, request, *args, **kwargs): value1 = Class1.objects.filter(id__in={x.id for x in self.request.user.organization_modules}) value2 = Class2.objects.filter(organization=self.request.user.organization) value3 = Class3.objects.get(id=self.kwargs["pk"]) obj = MyClass(field1=value1, field2=value2, field3=value3) obj.save() return Response(status=status.HTTP_201_CREATED) This is the URL: path("api/", MyViewSet.as_view({"post":"create"})) In the above example,I am overriding create method of ModelViewSet and performing the data selection to save the data. But when I hit the API, I want to select values of field1, field2 and field3 from filtered data, not from all the data of Class1, Class2 and Class3. But in current implementation, all the data of Class1, Class2 and Class3 is shown. How to do that? -
Django, TokenAuthentication, REST Framework API, Authentication credentials were not provided
I'm new to backend. I'm trying to fetch my data in the backend via API token, and I followed this tutorial: https://www.django-rest-framework.org/api-guide/authentication/ When I add these two lines in my View code, I can't fetch my data: authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] The error is { "detail": "Authentication credentials were not provided." } and on my backend I got "GET /hello/ HTTP/1.1" 403 58 But if I delete those two lines, I can fetch my data successfully. This is my View class: `class HelloView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): print(request.auth) content = { 'user': str(request.user), 'auth': str(request.auth), } return Response(content)` In the tutorial, it says when I have those two lines, I will be able to view my user name and token in the user router. But I got none for my "auth". However, if I delete those two lines, I can view my "user" and "auth" on my Windows side. Screenshots: backend side, with those two lines frontend side, with those two lines frontend side, without those two lines Could anybody explain this to me please? Any help would be nice! Thank you so much! -
How to push data from html form to firebase realtime database in django(using pyrebase)?
I'm having a problem with pushing data from a form to firebase realtime database. Here is my view funcction. Just updated to include user token but hasn't helped. The data isn't displaying in the db. def post_add(request): name = request.POST.get('name') phone = request.POST.get('phone') location = request.POST.get('location') city = request.POST.get('city') website = request.POST.get('website') data = {"name": name, "phone": phone, "location": location, "city": city, "website": website} user = authe.get_account_info(request.session['uid']) db.child("restaurant").push(data,user['users'][0]['localId']) return render(request, 'restaurants.html') here is the db Just updated to include user token but hasn't helped. The data isn't displaying in the db. -
'WSGIRequest' object has no attribute 'front_page'
I want to link my post_create to frontpage.And im getting this error. Im a beginner and I dont really know how to link.Can you guy give me advice plz. This is error im getting.enter image description here This is my code in view.pyenter image description here This is my code in model.pyenter image description here This is my code in urls.pyenter image description here This is my code in templateenter image description here -
RelatedObjectDoesNotExist at /users/edit/ User has no profile
I ran into a situation where I had developed a method called edit and passed both the profile and user forms into it when I wanted to modify a profile. @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user,data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request,'users/edit.html',{'user_form':user_form,'profile_form':profile_form}) this is my views.py where i have written the logic and coming to urls.py path('edit/',views.edit,name='edit'), and the edit.html code follows like this {% extends 'users/base.html' %} {% block body %} <h2>Edit profile form</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit"/> </form> {% endblock %} the output shows me like this I am expecting a better solution to resolve this issue -
Django query data in template using JS and python functions
Let's say I have a form for a booking system based on a one-to-many relations with the visitors table..as in the attached image, I'm trying to implement a "Find" function linked to the visitor passport table so we don't need to re-enter the visitors data again. abasically we can enter the passport number and run a query so if his data is there it will come back and fil the form, otherwise we have to reenter it manually using a different form. The following JS function will query the visitor table by passport # and bring back data correctly. However I don't know how to fill out the booking form with the new data so it can be saved, because the data I get is in html format as a table. In my real case, I need to save two fields only from the returned data including the passport number in the booking form, so how I extract the passport # from the returned data, or maybe there is a better way to do so. function visitor_details(pass_num){ url = 'booking_vis_details' $.ajax({ type: "GET", url : url, data: { num: pass_num, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data) { $('#table_details').html(data); } }) } View: … -
Getting Back Python Frameworks
I'm accidentally deleted my Python Frameworks on my mac so i can't work learning Django can your guys help me to get back Python Frameworks Mac-MacBook-Pro:~ mac$ python3 --version Python 3.11.1 Mac-MacBook-Pro:~ mac$ python3 -m django --version Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/Users/mac/django/django/__main__.py", line 9, in <module> management.execute_from_command_line() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'django.core.management' has no attribute 'execute_from_command_line' Mac-MacBook-Pro:~ mac$ python -m django --version python: posix_spawn: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No such file or directory Mac-MacBook-Pro:~ mac$ -
Failed to establish a new connection: [Errno 113] No route to host'))
I am trying to connect Readthedocs and Gitlab to each other via gitLab OAuth 2.0, I say connect with gitlab without any problem via readthedocs, gitlab connects and I select authorize, but the following error appears, what could be the source of this problem? thankyou for support. HTTPSConnectionPool(host='gitlab.tutel', port=443): Max retries exceeded with url: /oauth/token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f22cac5fc10>: Failed to establish a new connection: [Errno 113] No route to host')) -
NoReverseMatch at /cars Reverse for 'car_details' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['carscars/(?P<id>[0-9]+)/
stackoverflow * ` In views.py def car_details(request, id): single_car = get_object_or_404(Car, pk=id), # id = 1 data = { 'single_car': single_car, # 'url': url, } # reverse('single_car', args=(id)) return render(request, 'cars/car_details.html', data) In urls.py urlpatterns = [ path('', views.cars, name='cars'), path('<int:id>/car_details', views.car_details, name='car_details'), ] In car.html {% for car in cars %} <div class="detail"> <h1 class="title"> <a href="{% url 'car_details' pk=car.id %}">{{car.car_title}}</a> </h1> <div class="location"> <a href="{% url 'car_details' pk=car.id %}"> <i class="flaticon-pin"></i>{{car.state}}, {{car.city}} </a> </div> {% endfor %} In models.py class Car(models.Model): id=models.IntegerField(primary_key=True,default=True) also tried with revrser function on views.py it gives same error ``*` also tried with revrsere function on views.py it gives same error -
Connection TimeOut in flutter when making a request to django Rest api locally
void reg() async { try{ http.Response response = await http.get(Uri.parse("http://10.0.2.2/api/alluser")); print(response.body); } catch(e){ print(e); } } It is working when I am doing in chrome( web) http://127.0.0.1:8000 but not working in android emulator. in Django's setting.py ALLOWED_HOST = [10.0.2.2 , 127.0.0.1] -
No Signature at the end of url using digital ocean cdn in django
This is my configutation AWS_ACCESS_KEY_ID = 'keyid' AWS_SECRET_ACCESS_KEY = 'accesskey' AWS_STORAGE_BUCKET_NAME = 'allio1' AWS_S3_ENDPOINT_URL = 'https://sfo3.digitaloceanspaces.com' AWS_S3_CUSTOM_DOMAIN = 'allio1.sfo3.cdn.digitaloceanspaces.com' AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'allio-static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '{}/{}/'.format(AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' There is no signature at the end of the url. It is just plain url for example https://allio1.sfo3.cdn.digitaloceanspaces.com/allio-static/assets/bootstrap/css/bootstrap.min.css There is no signature at the end of url and it says access denied -
Django Rest Framework objects.get produces matching query does not exist but filter shows the item does exist
I have a post model: class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user", related_name="user" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] get_latest_by = "created_at" def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug def one_image(self): return PostImage.objects.all().filter(post=self)[:1] and I have this post rating model for someone to rate a post: class PostRating(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) score = models.IntegerField(choices=list(zip(range(1, 6), range(1, 6)))) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user that gave rating" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "rating" verbose_name_plural = "ratings" db_table = "post_ratings" def __str__(self): return str(self.score) I am trying to get the rating of the post together with the post in an endpoint. Here are the serializers I am using to accomplish that: class UserPostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) profile = serializers.SerializerMethodField() bookmarked = serializers.SerializerMethodField() rating = serializers.SerializerMethodField() class Meta: model = Post fields = [ "id", "category", "body", "images", "video", "profile", "published", "bookmarked", "rating", "created_at", "updated_at", ] depth=1 def get_profile(self, obj): … -
Cross-Origin Request Blocked and Preflight executes View Django-project
In my Django and React project, I am trying to make a registration request which is failing due to a missing "Access-Control-Allow-Origin" header, resulting in a 504 error. The problem I believe I am facing is that the preflight (OPTIONS) request is already executing the View, which is causing issues with permissions for the subsequent POST request. Jan 21 10:11:20 AllKids python3[155868]: [21/Jan/2023 09:11:20] "OPTIONS /user/register/ HTTP/1.0" 200 0 Jan 21 10:11:20 AllKids python3[155868]: in View I am not sure why this issue is only occurring on this View, as all other views are working correctly. Jan 21 10:21:40 AllKids python3[156001]: [21/Jan/2023 09:21:40] "POST /user/validatePassword/ HTTP/1.0" 200 613 It is worth noting that the OPTIONS request is returning a 200 status code. I would like to share the following code with you for further analysis: let formData = { password: password, username: username, email: email, }; console.log(formData); let request = await fetch( `${process.env.REACT_APP_BACKEND_URL}/user/register/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), } ); console.log(response, 'WTF'); let response = await request.json(); The "WTF" line is not beeing reached since I am not getting the response... For comparison, here is an function that works perfectly fine(login): let formData = { … -
Django REST framework: Getting 403 when trying to test create a new post
I'm trying to create a test for creating a new post, but I'm getting Error 403. I've read the questions on this topic, but either they were not about testing or the solution they provided did not work (I'll provide info about what I've tried so far). Here is my code: urls.py: app_name = "blog_api" urlpatterns = [ path("<str:pk>/", PostDetail.as_view(), name="detail_create"), path("", PostList.as_view(), name="list_create"), ] and my permissions.py: class PostUserWritePermission(permissions.BasePermission): message = "Editing posts is restricted to the admin and author of the post only." def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return request.user.is_superuser or request.user == obj.author And here is my views.py: class PostList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] queryset = Post.post_objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = [PostUserWritePermission] queryset = Post.post_objects.all() serializer_class = PostSerializer And finally, my tests.py: class PostTests(APITestCase): def test_view_posts(self): url = reverse("blog_api:list_create") response = self.client.get(url, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_post(self): self.test_category = Category.objects.create(name="test category") self.test_user = User.objects.create_user( username="test_user", password="test_password", ) data = { "title": "new", "author": 1, "excerpt": "new", "content": "new", "slug": "new", } url = reverse("blog_api:list_create") response = self.client.post(url, data, format="json") print(response.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) So, when I test using py manage.py test command, the first test is ok, but the second … -
Permission denied /media files Django Nginx setup
I followed this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 Everything is working (static files are served etc) but by user uploaded media files show a ‘permission denied’ when trying to access the image: 2023/01/21 09:50:01 [error] 12912#12912: *266 open() "/home/hvn/intranet/intranet/media/images/werkstujk_1_Far44Li.2e16d0ba.fill-322x247-c100.jpg" failed (13: Permission denied), client: xxx.xxx.xxx.xxx, server: xxxxx.net, request: "GET /media/images/werkstujk_1_Far44Li.2e16d0ba.fill-322x247-c100.jpg HTTP/1.1", host: "www.xxxxxx.net", referrer: "https://www.xxxxx.net/blogs/" I’m using wagtail as cms system. The Gunicorn socket is running under user ‘hvn’ and group ‘www-data’. The directory and filepermissions are like: 750 for dirs and 644 for files: ll | grep media drwxr-xr-x 5 hvn www-data 4096 Jan 17 22:36 media/ -rw-r--r-- 1 hvn www-data 33857 Jan 21 00:24 werkstujk_1_Far44Li.2e16d0ba.fill-322x247-c100.jpg My nginx config file is serving the media folder: location /media/ { root /home/hvn/intranet/intranet; } What am I doing wrong? Please help me. Thnx in advanced. -
How can I create two user type in Django?
I'm creating a project, where I've two types of account. One is the default User (that use the normal params), and another one that is the account for businesses. Actually the model seem to be the hardest part. Also, in the future, I would like to add some fields that the normal User model doesn't have (like credit card, sector,...), I need a good way to create the account using the normal User fields that could be updated. forms.py class Business_RegisterForm(forms.ModelForm): email = forms.CharField(max_length=30) password = forms.CharField(max_length=30) def clean(self): cleaned_data = super(Business_RegisterForm, self).clean() email = cleaned_data.get('email') password = cleaned_data.get('password') class Meta: model = BusinessModel fields = [ 'email', 'password', ] views.py def Business_RegistrationView(request): if request.method == 'POST': form = Business_RegisterForm(request.POST) if form.is_valid(): \# clean data email = form.cleaned_data\['email'\] password = form.cleaned_data\['password'\] # user creation BusinessModel.objects.create_business( email=email, password=password ) # user auth **credentials business = authenticate( email=email, password=password ) # save the model business.save() form.save() # login after saved login(request, business) # redirect to home return HttpResponseRedirect('/') else: # Request's Error print("The POST request has failed.") form = Business_RegisterForm() urls.py path('business-registration/', Business_RegistrationView, name='business-registration'), models.py class BusinessModel(models.Model): email = models.OneToOneField(User, on_delete=models.CASCADE, related_name='business_email') password = models.OneToOneField(User, on_delete=models.CASCADE, related_name='business_password') # BELOW Changes in Admin … -
FAILED TO SAVE DJANGO INLINE FORMSET WITH HTML INPUT TO DB
I tried to return data from Purchase Order Model to Grn Form and i want to save it in Grn Model but i cant save it. Here is my view class and grn form which return data but cant save to db class view.py class CreateGrn(LoginRequiredMixin, CreateView): model= GrnModel template_name = "inventory/grn_create.html" class GrnCreate(LoginRequiredMixin, CreateView): model = GrnModel template_name = "inventory/grn_create.html" form_class = GrnForm success_url = reverse_lazy("/") def get_context_data(self, **kwargs): data = super(GrnCreate, self).get_context_data(**kwargs) if self.request.POST: data['formset'] = Grn_LineItemFormset(self.request.POST) else: data['formset'] = Grn_LineItemFormset() data['grn_no'] = GrnModel.objects.filter(company_grn = self.request.user.first_name).order_by('-id')[:1] pk = self.kwargs["pk"] data['form_lpo'] = PurchaseOrderModel.objects.get(pk = pk) #data['lpo_line_item'] = data['form_lpo'].purchaseorder_lineitem_set.all() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): form.instance.grn_user = self.request.user self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(GrnCreate, self).form_valid(form) html template <div class="container1" style="width: 125%;"> <form class="/purchase_order_list" method="POST" action="">{% csrf_token %} <div class="column is-one-third" style="line-height: 10px;"> <div class="field" style="margin-left: 85.7%; width: 150px; margin-top: 6%;"><br> <label>Lpo No.</label> <div class="control"> <input class="input form-control" value="{{ form_lpo.lpo_number }}"> </div> </div> </div> <div class="column is-one-third"> <div class="field" style="margin-left: 85.7%; width: 150px; margin-top: 0.2%;"> <label>Grn No.</label> <div class="control"> <input class="input form-control" value="{{ form_lpo.grn_number }}"> </div> </div> </div> </div> </div> <div class="columns is-centered"> <div class="column is-one-third"> <div class="col-md-4 mb-3"> …