Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In this image we are using transaction.atomic and i wanna know what is ( F ) in line 44
In this image we are using transaction.atomic and i wanna know what is ( F ) in line 44 -
Update method does not support writable dotted source error when updating user profile
Getting the error The `.update()` method does not support writable dotted-source fields by default. Write an explicit `.update()` method for serializer `signup.serializers.UpdateUserSerializer`, or set `read_only=True` on dotted-source serializer fields. I would like to enable users to update their profile info. I extended the custom user class in my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() here is my urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) and my serializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city') country = serializers.CharField(source='profile.country') class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name','city','country'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) … -
I'm trying to set geo coordinates through address using mapquest. but it give me an error[ django.contrib.gis.gdal.error.GDALException: OGR failure. ]
I'm trying to set geo coordinates through address using mapquest, gdal, gis. but it give me an error. I never used gdal and gis so i can't figue out the problem but i think there is problem on models.py. please help me to figue out the [OGR failure] error Any help would be appreciated! - Let me know if I should update this question with my settings.py or other relevant files. Here is me Logs. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/job/job/add/ Django Version: 4.0.3 Python Version: 3.10.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'django_filters', 'job.apps.JobConfig', 'django.contrib.gis'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\Django\Jobbee\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Django\Jobbee\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\contrib\admin\options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\contrib\admin\sites.py", line 242, in inner return view(request, *args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\contrib\admin\options.py", line 1885, in add_view return self.changeform_view(request, None, form_url, extra_context) File "D:\Django\Jobbee\env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "D:\Django\Jobbee\env\lib\site-packages\django\utils\decorators.py", line 133, … -
File download using React Django? able to download file but content is missing getting file correpted error
Backend @api_view(['POST']) def download_attachment(request): body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) file_name = body_data['file_name'] migration_typeid = body_data['migration_typeid'] attach_type = body_data['AttachmentType'] object_type = body_data['object_type'] featurename = body_data['fname'] fid = body_data['feature_id'] filter_files = Attachments.objects.filter( Feature_Id=fid, AttachmentType=attach_type, filename=file_name) filter_values = list(filter_files.values_list()) file_path = filter_values[0] fl = open(file_path[4], 'rb') mime_type, _ = mimetypes.guess_type(file_path[4]) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % file_name return response Frontend(React) const handleDownload = (att_Type, migtypeid, id, obj_type, att_name, fid) => { let body = { file_name: att_name, migration_typeid: migtypeid, object_type: obj_type, AttachmentType: att_Type, id: id, fname: detaildata.Feature_Name, feature_id: fid, responseType: "blob", }; let conf = { headers: { Authorization: "Bearer " + config.ACCESS_TOKEN(), "Content-Type": "application/json", }, }; // console.log(conf.headers); axios .post(`${config.API_BASE_URL()}/api/download_att`, body, conf) .then((res) => { fileDownload(res.data, att_name); }) .catch((err) => { }); }; i am able to download the file but content is not coming in the file for txt files it is working but other than txt not supporting getting corrupted error can you anyone tell me the solution how it works? -
'bool' object has no attribute 'id',how can i fix this error in my django project [closed]
@api_view(['POST']) @permission_classes((permissions.AllowAny,)) def login(req): email = req.data.get('email') username = req.data.get('username') password = req.data.get('password') user = TokenObtainPairSerializer( data=req.data).is_valid(raise_exception=True) if user is not None: try: token = RefreshToken.for_user(user) print(token, "Token") except Exception as e: return Response({'message': "Login Failed " + str(e)}) else: pass return Response({'message': "Login Successful"}) I was trying to make a custom simple jwt authentication with rest_framework_simplejwt but getting the error "'bool' object has no attribute 'id',can anyone explain me why this is happenning. -
How to add Latest Post Of Category Show in the Detail Article
Views.py def PostView(request,slug): Postdata = Post.objects.get(slug=slug) side_data = Post.objects.all() category_posts = Post.objects.filter(category__cat_slug=slug) return render(request,'post-detail.html',{'Postdata':Postdata,'side_data':side_data,'category_posts':category_posts}) Models.py class Category(models.Model): name = models.CharField(max_length=100) category_description = FroalaField() cat_slug = models.SlugField(max_length=200, null=False) def __str__(self): return self.name options = ( ('draft', 'Draft'), ('published', 'Published'), ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) category = models.ForeignKey( Category, on_delete=models.CASCADE,null=True,) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='myapp_post') updated_on = models.DateTimeField(auto_now= True) content = FroalaField() feature_img = models.ImageField(upload_to = 'images/', null=False) status = models.CharField(max_length=10, choices=options, default='draft') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title Post-detail.html <h4>Related Post</h4> <br> {% for data in category_posts %} <h4>{{data.title}}</h4> {% endfor %} I'm trying to Add Category Related latest Posts in the Article. For Example If an article in which category name is Django Tutorial. In the Article Detail, I want to add the Related latest post of this category. -
htmx and django : dependant select options
I am trying to develop an app in Django where I add partials, using HTMX, everything works properly except for one critical thing. In the form I am loading from the partial, there are 2 select options, that are dependant on each others, traditionally without HTMX, I use a simple Javascript to link them both <script> $("#id_data_form").live('change', function() { var url = $("#extractor_query_builder").attr("data-fields-url"); var dataformId = $(this).val(); $.ajax({ url: url, data: { 'data_form': dataformId }, success: function (data) { $("#id_data_fields").html(data).height(150); } }); }); </script> This works fine when I work without HTMX, but when I add the HTMX way of doing it, it seems like the javascript does not find the DOM corresponding to the form elements when the form is injected in the main document my form looks like this <div hx-target="this" hx-swap="outerHTML" class="mt-3 py-3 px-3 bg-white shadow border border-gray-100"> <form class="form-horizontal" id="extractor_query_builder" method="POST" data-fields-url="{% url 'getFields' %}" novalidate> {% csrf_token %} {{ form | crispy }} {% if extract %} <button type="submit" hx-post="{% url 'update-extract' extract.id %}"> Submit </button> <button hx-get="{% url 'detail-extract' extract.id %}" type="button"> Cancel </button> {% else %} <button type="submit" hx-post="."> Submit </button> {% endif %} </form> </div> but I noticed when I submit the … -
Referencing static files in Django
FILES: settings.py STATICFILES_DIRS = [ BASE_DIR / "static" , ] base.html {% load static %} How do I reference my static files in the following line of html code?... <li class="ftco-animate"><a href="#" data-toggle="tooltip" data-placement="top" title="Facebook"><span class="ion-logo-facebook"></span></a></li> -
Invalidate Cloudfront Caching of Django Rest Framework whenever I make changes like HTTP POST/PUT
I have a django rest framework running in AWS behind a cloudfront distribution. When I call a HTTP POST or HTTP PUT to one of my APIs, the corresponding HTTP GET to the same API does not get updated. How do I invalidate my API endpoint? -
RestrictedPython: Call other functions within user-specified code?
Using Yuri Nudelman's code with the custom _import definition to specify modules to restrict serves as a good base but when calling functions within said user_code naturally due to having to whitelist everything is there any way to permit other user defined functions to be called? Open to other sandboxing solutions although Jupyter didn't seem straight-forward to embed within a web interface. from RestrictedPython import safe_builtins, compile_restricted from RestrictedPython.Eval import default_guarded_getitem def _import(name, globals=None, locals=None, fromlist=(), level=0): safe_modules = ["math"] if name in safe_modules: globals[name] = __import__(name, globals, locals, fromlist, level) else: raise Exception("Don't you even think about it {0}".format(name)) safe_builtins['__import__'] = _import # Must be a part of builtins def execute_user_code(user_code, user_func, *args, **kwargs): """ Executed user code in restricted env Args: user_code(str) - String containing the unsafe code user_func(str) - Function inside user_code to execute and return value *args, **kwargs - arguments passed to the user function Return: Return value of the user_func """ def _apply(f, *a, **kw): return f(*a, **kw) try: # This is the variables we allow user code to see. @result will contain return value. restricted_locals = { "result": None, "args": args, "kwargs": kwargs, } # If you want the user to be able to … -
Cannot find image from path
I am trying to build a web app using Django for the backend and a Bootstrap ui template for the frontend. Currently I am trying to load the CSS and images from a folder named 'static'. This image shows the packages and the path of the image I'm trying to display. This is what the site looks like when I run it on localhost and include the '{%load static%}'. This is what VS Code says when I try to follow the path using CTRL+CLICK -
handle a request in django that takes a long time to process is a lambda function and api gateway better? OR async django function
I have a function in my django rest framework api that I am working out. I suspect that it will take a long time to finish. About a minute. Given api requests expect a response I suspect this is a problem. My initial thought was set up a aws lambda function that is tied to a aws api gateway, secured by a api key. The idea being that the front end calls the api gateway url, and the url and the api key are sent over by my server only when the user who requests the url and apikey has access. But is this secure enough? Or is it better to have a django function that runs async? Meaning run the work that needs to be done async and immediately return the 200 response? Then just have another endpoint that polls the server to see if the work has been done? Can the async behavior even be done in the way I describe? https://docs.djangoproject.com/en/4.0/topics/async/ after reading the docs it doesn't seem to do what i expect it to. I guess we can't return 200 while the function works. So AWS amazon gateway seems to be the win. But I worry … -
How is the file from OneToOne Model's FileField accessed, read in views.py and passed to template?
I am developing a simple Data Visualization App, where a user can register, login upload a file and visualize its content. I am using default User model, and a Detail Model having OneToOne relation with User Model. The Detail has 3 fields, which are: OneToOne(User) FileField() TextField() Now, I want to access the file that is saved in FileField, in views.pyand read it's content, then visualize it using Python'sNumPyandMatplotlib`, then finally show visualization results on the frontend. I need a guidance that how should I start and approach this task? Basically, I need deep guidance in how to access and read the file in views.py? My models.py is: class Detail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) file = models.FileField(verbose_name="CSV File", upload_to='csv_files/') file_desc = models.TextField("CSV File Description") def __str__(self): return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name)) and in views.py, I am approaching it this way: class VisualizeAPI(View): template_name = 'accounts/visualize.html' def get(self, request): msg = {'message': "Please login to view this page."} if request.user.is_authenticated: detail, _ = Detail.objects.get_or_create(user=request.user) context = {'detail': detail} return render(request, self.template_name, context) return render(request, self.template_name, msg) and in template, I am approaching it this way: <body> <h1>Visualized Details</h1> {% if request.user.is_authenticated %} {{ detail }} {% else %} <h2>{{ message … -
Extended user class properties not updating
Would like to allow users to update their profile, getting the error Field name 'city' is not valid for model 'User'. For context, I extended my default user class in models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() When a user updates a profile I use this endpoint in urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), Here is my UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) and my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User fields = ['username', 'email', 'password', 'first_name', 'last_name','city','country'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in … -
Implementing a search query inside a filter
I've been trying to implement a search bar inside my application, but I don't know how to query for similar names inside my db. Here is my view.py queryprms = request.GET name = queryprms.get('name') status = queryprms.get('status') if name: moderatorRoom = PokerRoom.objects.values("id", "first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug' ).filter(Q(user=user), Q(name=name)).order_by("-datetime") The problem is that when the user search for a similar word, say "Alch" for "Alchemy", the query returns empty even if "Alchemy" object exist inside my db. I want that the query returns similar objects for the user's search. How can I do that? By the way, I'm using Postgre and Django 3.1.5. -
Retrieve all dynamic fields from dynamic html form in Django
I created a dynamic html form. Now I want to retrieve the dynamic data in my django view function can anyone guide me on how to do that. This is the HTML of the dynamic section: <div class="dynamic-section" name="dynamic-section" id="dynamic-section"> <div class="single-container" id="single-container-1"> <div class="triple"> <div class="sub-triple"> <label>Relation</label> <select name="relation-1" id="relation-1"> <option value="Mentions">Mentions</option> <option value="Does not mention">Does not mention</option> </select> </div> <div class="sub-triple"> <label>Category</label> <select name="category-1" id="category-1"> <option value="Person">Person</option> <option value="Organization">Organization</option> <option value="Time">Time</option> <option value="Location">Location</option> </select> </div> <div class="sub-triple"> <label>Value</label> <input type="text" name="value-1" id="value-1" placeholder="Name.." required/> <ul class="value-1-list"></ul> </div> <div class="close-btn"> <button class="danger" onclick="removeTriple('single-container-1')" id="close-1"> <i class="fa fa-close"></i> </button> </div> </div> </div> </div> This is the javascript function to add more fields in this dynamic section: function addTriple() { triple_index += 1; var single_section = document.createElement('div'); let sectionID = 'single-container-' + triple_index; single_section.setAttribute("id", sectionID); single_section.setAttribute("class", "single-container"); var andOrSelect = document.createElement('select'); let andOrSelectID = 'andOr-' + triple_index; andOrSelect.setAttribute("name", andOrSelectID); andOrSelect.setAttribute("id", andOrSelectID); newAndOrHtml = ` <option value="and">and</option> <option value="or">or</option> ` newTripleHTML = ` <div class = "triple"> <div class = "sub-triple"> <label>Relation</label> <select name="relation-` + triple_index + `" id="relation-` + triple_index + `"> <option value="Mentions">Mentions</option> <option value="Does not mention">Does not mention</option> </select> </div> <div class = "sub-triple"> <label>Category</label> <select name="category-` + triple_index … -
Django CacheOps - Secondary read-only redis node
We use both the default django cache and CacheOps. All backed by Redis, the default cache has some nice docs on setting up a secondary ReadOnly node (https://django-redis-cache.readthedocs.io/en/latest/advanced_configuration.html#master-slave-setup) but can't find the same instructions for Cacheops. Any pointer? Redis is not in cluster mode, managed by AWS. -
django.core.exceptions.FieldError: Unknown field(s) specified for User
I have a hard time understanding the whole registration, login, edit profile part. I feel that I get very confused when writing the code. I was following a tutorial to be able to make a page to edit the profile but I get this error: django.core.exceptions.FieldError: Unknown field(s) (fax, phone1, zip, alternativeContact, city, address, socialMedia1, phone2, socialMedia2, website, state, country) specified for User But at no point do I see where those fields are, I don't have it, even in EditProfileForm there are only two fields "state and zip" could you give me a guide to know what is happening url path('profile/edit-profile/',UserEditView.as_view(),name='edit-profile'), models.py class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,default=0) image=models.ImageField(default='profilepic.jpg',upload_to='profile_pictures') location=models.CharField(max_length=100,default=0) phone1=models.IntegerField(default=0) phone2=models.IntegerField(default=0) fax=models.IntegerField(default=0) email=models.CharField(max_length=100,default=0) website=models.CharField(max_length=100,default=0) socialMedia1=models.CharField(max_length=100,default=0) socialMedia2=models.CharField(max_length=100,default=0) socialMedia3 = models.CharField(max_length=100,default=0) alternativeContact=models.CharField(max_length=100,default=0) country = models.CharField(max_length=100, default=0) address=models.CharField(max_length=100, default=0) city=models.CharField(max_length=100,default=0) state=models.CharField(max_length=100,default=0) zip=models.CharField(max_length=10,default=0) def __str__(self): return self.user.username views.py class UserEditView(generic.UpdateView): form_class=EditProfileForm template_name='Usuarios/edit-profile.html' success_url=reverse_lazy('profile') def get_object(self): return self.request.user forms.py class EditProfileForm(UserChangeForm): state = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) zip = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model=User fields = ('state', 'zip') -
Cannot update a Django user profile
I have a react app interacting with django to create and update user profiles. I am encountering this error message when I try to update a user profile, specifically the first name and last name properties I get a response that indicates that my user profile has not been updated {"username":"***","email":"emmanuelsibanda21@gmail.com","password":"****","first_name":"","last_name":""} This is what I have in my urls.py: path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile'), UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) UpdateUserSerializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) class Meta: model = User fields = ['username', 'email', 'password', 'first_name', 'last_name'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}} def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] … -
Django REST API - Forbidden CSRF Cookie not set
When I try to login into my angular aplication occurs the error in the image bellow. I have already tried to comment django.middleware.csrf.CsrfViewMiddleware in the settigns.py file and already put @csrf_exempt on the Django method("login_view") but the error keeps occurring. I'm using an HTTP service and not HTTPS settings.py ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True ... views.py @csrf_exempt @api_view(["POST",]) @permission_classes([AllowAny]) def login_view(request): ... -
Django models: which field to use for position/order of an object
My project is a basic scrum board with a model Column, of which there can be unlimited instances. Each column is displayed side by side, and I want the order of the columns to be customizable. My thought was to use an IntegerField to determine numerical position, but I'm struggling with how to set the max_value equal to the total number of columns since it varies by board. Here's how I set it up: class Column(models.Model): name = models.CharField(max_length=25) board = models.ForeignKey(Board, on_delete=models.CASCADE) position = models.IntegerField(unique=True,min_value=1, max_value=???) My problem was what to use as the max_value. I tried solving it by doing this: class Column(models.Model): max_value = Column.objects.get(board=board).count() name = models.CharField(max_length=25) position = models.IntegerField(unique=True,min_value=1, max_value=max_value) I know this obviously won't work. Could I somehow use class Meta to set constraints instead, or what would be a good way to approach this? -
Django: Method Not Allowed (GET)
I'm creating an e-commerce project just for studies, all the apps created in django are working perfectly, except where the account creation would be. The problem: I don't get any exceptions in the code, but when I try to view the page in the browser there's nothing but a blank page, as if django couldn't get to the .html. My views.py: from django.views import View from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView from django.contrib.auth.models import User from django.contrib.auth import authenticate, login import copy from . import models, forms class AccountBase(View): template_name = 'account/create.html' def setup(self, *args, **kwargs): super().setup(*args, **kwargs) self.cart = copy.deepcopy(self.request.session.get('cart', {})) self.account = None if self.request.user.is_authenticated: self.account = models.Account.objects.filter( user=self.request.user).first() self.context = { 'userform': forms.UserForm( data=self.request.POST or None, user=self.request.user, instance=self.request.user, ), 'accountform': forms.AccountForm( data=self.request.POST or None, instance=self.account ), } else: self.context = { 'userform': forms.UserForm( data=self.request.POST or None ), 'accountform': forms.AccountForm( data=self.request.POST or None ), } self.userform = self.context['userform'] self.accountform = self.context['accountform'] self.renderer = render(self.request, self.template_name, self.context) def get(self, *args, **kwargs): return self.renderer class Create(View): def post(self, *args, **kwargs): if not self.userform.is_valid() or not self.accountform.is_valid(): return self.renderer username = self.userform.cleaned_data.get('username') password = self.userform.cleaned_data.get('password') email = self.userform.cleaned_data.get('email') if self.request.user.is_authenticated(): user = get_object_or_404(User, username=self.request.user.username) … -
How do I use the virtual env in Arch Linux?
enter image description here How do I create a virtual environment in Arch Linux? -
How do i make Django get text after comma for editing?
my form before clicking the edit button my form after clicking the edit button the input isn't showing all the strings after comma ``` def UpdateMainCategory(request, slug): maincat = MainCategories.objects.get(slug=slug) if request.method == 'POST': if len(request.FILES) != 0: if len(maincat.icon) > 0: os.remove(maincat.icon.path) maincat.icon = request.FILES['iconimage'] maincat.name = request.POST.get('maincat') maincat.status = request.POST.get('catstatus') maincat.meta_title = request.POST.get('metatitle') maincat.meta_keywords = request.POST.get('metakeywords') maincat.meta_description = request.POST.get('metadescription') maincat.save() messages.success(request, "Main Category Updated Successfully.") return redirect('/products/categories/')``` my .html code sample ``` <input type="text" name="maincat" class="form-control" placeholder="Baby Products..., Electronics..." maxlength="100" value={{ maincat.name }} required data-validation-required-message="This field is required" />``` -
Django filter, if only last value in a query is true
How to filter all objects of the ViewModel if only the last InfoModel.check_by_client_a is True ? I have the structure like this: class InfoModel(model.Models): ... service = ForeingKey(ServiceModel) check_by_client_a = BooleanField() check_by_client_b = BooleanField() check_date = DateTimeFiled() ... class ServiceModel(model.Models): ... class ViewModel(model.Models): ... service = ForeingKey(ServiceModel) ...