Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what should I put in the views.py so that a specific user can add new complaints in a complaint management system
I have the model created for complaints. I tried a few methods to help a user create the complaint, but nothing works so I have given up and I just want to understand what to add in the views.py so that I can do that. The system basically has multiple users and I want the users to send in their complaints to the admin panel, so that they can be viewed, edited or deleted as per use on the dashboard. Right now my form does get created but it does not save the complaints in the admin panel. models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title what to add in the views.py? I've tried various things but I don't know what to do to make it work. this if my views.py but I feel like the entire thing is wrong so I want an entirely new views: class ComplaintCreate(CreateView): model = Complaints form = ComplaintForm fields = '__all__' success_url = reverse_lazy('New') template_name = 'new.html' I want the final page to look like this: -
best practises for role based permissions using django groups
currently I am working on my first ever website and I have recently started tackling the RBAC permission system. The goal of my website is that companies will register on my website, their company owner will create groups that are unique to the company and effectively will act as job roles. The group model that the company owner can add/remove permissions and user to is from django.contrib.auth.models. This as an example means that companies can hide/remove access to certain components on the front end from the user. The current user then absorbs the permissions from the groups it is in, using get_all_permissions() I obtain the current user's active permissions and send this to the React frontend to only show specific components. Question 1, is this the right way to go about implementing method of hiding components from users? Question 2 is, what would be the best way to ensure that these permissions are actively followed on the views/models? I saw that DjangoModelPermissions only works where querySet() are used, but I have views where that isnt used at all. Such as: class CompanyView(viewsets.ViewSet): permission_classes = [permissions.AllowAny] def create(self, request): try: company_name = request.data['company_name'] company_orders = request.data['company_orders'] company_owner = request.data['company_owner'] company_owner_obj = … -
DRF: UpdateAPI > 'int' object has no attribute 'save'
I am trying to create an UpdateAPI to update my model. I need to comply with this API schema. I have tried the following: api.py class AlarmstichworteUpdateApi(ApiErrorsMixin, APIView): permission_classes = [IsAuthenticated] class InputSerializer(serializers.ModelSerializer): updated = serializers.DateTimeField() name = serializers.CharField(max_length=100) class Meta: model = AlarmstichworteConfig fields = ( '__all__' ) def put(self, request, id, *args, **kwargs): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) update_alarmstichwort(id=id, **serializer.validated_data) return Response(status=status.HTTP_200_OK) services.py def update_alarmstichwort( *, id: int, updated: datetime, name: str, ) -> AlarmstichworteConfig: alarmstichwort = alarmstichwort_by_id(id=id).update( name=name, updated=updated, ) # alarmstichwort.full_clean() alarmstichwort.save() return alarmstichwort selector.py def alarmstichwort_by_id(*, id, filters=None): return AlarmstichworteConfig.objects.filter(id=id) However, I have the problem that this does not work. When I do it this way, I get the error: File "D:\04-Dev\project\{...}\services.py", line 48, in update_alarmstichwort alarmstichwort.save() AttributeError: 'int' object has no attribute 'save' Can you help me or tell me what the error is? Thank you in advance. -
Testing django geoodel with PointField results in TypeError
I have the following model: from django.contrib.gis.db import models as geo_model class UserAddress(geo_model.Model): user = geo_model.OneToOneField( User, on_delete=models.CASCADE, related_name="user_address" ) coordinates = geo_model.PointField() address = geo_model.CharField(max_length=255) city = geo_model.CharField(max_length=20) country = geo_model.CharField(max_length=20) def __str__(self): return self.name Now, I am trying to unit-test this model with pytest: @pytest.mark.django_db class test_seeker_address(): seeker_address = SeekerAddress( seeker=Seeker(), address="my address", city="Oran", country="Algeria", coordinates=(7.15, 35.0) ) seeker_address.save() But, this is resulting in the following error: TypeError: Cannot set SeekerAddress SpatialProxy (POINT) with value of type: <class 'tuple'> How should I pass datatype in coordinates? -
This backend doesn't support absolute paths
I have django website deployed on heroku and using aws s3. When i login into admin page i get this message This backend doesn't support absolute paths enter image description here -
serializer for the nested Json in Django
I have the following JSON. which I get from the api and i want to write a serializer for this JSON in Django, someone has any idea how to write it, I just wrote it down but it gives me "error invalid data or expected directory and got a list "etc. anyhelp will be highly appreciated { "artikelNr1": 254160, "groessenCode": 6, "groessen": [ { "artikelNr1": 254160, "artikelNr2": 0, "artikelGr": 3, "groessenText": "EU36", "sku": "254160.00.03", "istZl": 1, "verkPeriode": -1 }, { "artikelNr1": 254160, "artikelNr2": 0, "artikelGr": 4, "groessenText": "EU37", "sku": "254160.00.04", "istZl": 2, "verkPeriode": -4 }, ], "zlQty": 7, "productId": 152060, "published": true, "categories": [ { "categoryRoots": [ { "id": 1, "name": "Damen", "parentCategoryId": 0 }, { "id": 5, "name": "Schuhe", "parentCategoryId": 1 } ], "id": 128, "name": "Hohe Sandalen", "parentCategoryId": 67 } ], "productName": "Sandalen" } -
Django : link Twich and Discord in user profile after Steam login
I am very new in Django. Recently I am developing a project with django , in this project I implemented social login with steam by the help of social-auth-app-django,a django package. It successfully login and redirects to profile, but now I want to link twich and discord in profile, so that I can store twich user name and discord username related to specific steam account . please tell me how can I implement it . Help will be highly appreciated !! Screen shot of profile page -
How to Count on annotated field that is concatenated in Django
I need help figuring out how to Count an annotated field (farm_key in this case) that is a concatenation of multiple fields. My Query is as follows staff_visits = FMS.Userdetails.objects.using('fmslegacy').filter( Q(userid__userrole__roleid__in=(3, 6, 7, 8)), Q(FieldVisitDetails_by_userid__createdon__gte=todaydate) ).order_by('userid').annotate( name=Concat(F('firstname'),Value(' '),F('lastname')), role=F('userid__userrole__roleid__role'), farm_key=Concat(F('FieldVisitDetails_by_userid__farmercode'), Value('_'), F('FieldVisitDetails_by_userid__landid'), Value('_'), F('FieldVisitDetails_by_userid__visitno'), output_field=CharField()), ).values('name', 'userid', 'role', 'farm_key').annotate(farm_visits=Count('farm_key', distinct=True)) but it gives the following error, ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'UserDetails.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (8120) (SQLExecDirectW)") Here is a glimpse of the output that is currently working (except for the count of farm key part) { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011021_41636_3" }, { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011031_55858_1" }, { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011036_51460_2" }, { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011042_55850_2" }, My goal is to replace farm_key with count of distinct farm_keys for each User object. in this case it will be one user with 4 as count of farm_keys. I have tried adding a property method to the model, but apparently that doesnt work … -
Best way to get date information from web-scraped CSV (Django)
I would like to scrape CSVs containing satellite data that is produced daily into a Django database, including the date information. However, from what I can tell the only place that has the date info is in the filename, and on the website download page, as in the date isn't in the CSV itself. What is the best way to read the date information into the database? If relevant, the database I'm interested in is the VIIRS nightfire data from Earth Observation Group. Thank you! -
Django primary key issue
I have a current model in Django app like below class BasicInfo(models.Model): review_id = models.IntegerField(primary_key=True) owner = models.CharField(max_length=100, null=True, blank=True) I want to add one more column named sever and want to make review_id + server a composite key class BasicInfo(models.Model): id = models.AutoField(primary_key=True) review_id = models.IntegerField(null=False, blank=False) server = models.IntegerField(default=1) owner = models.CharField(max_length=100, null=True, blank=True) class Meta: unique_together = (('review_id', 'server'),) when I am trying to apply the migrations I am getting this error **$ python manage.py makemigrations review You are trying to add a non-nullable field 'id' to basicinfo without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option:** I have also tried to add a default value as 1 in the 'id' field but that doesn't work. Is there any way to overcome this issue? -
Django-Select2 doesn't work with many-to-many through fields
I have 3 models: Person, Company and they have many-to-many relationship through the Membership model with through fields When I create form for Person creation you have a possibility to add many Companies for this Person. But I wanna create autocomplete field (not just ModelChoiceField) when adding Company for Person. I go through the Django-Select2 tutorial, but widget displayed like this: Here is my form: class CompanyWidget(s2forms.ModelSelect2Widget): search_fields = [ "company_name__icontains", ] class MembershipForm(forms.ModelForm): person = forms.ModelMultipleChoiceField( queryset=Person.objects.all(), widget=forms.CheckboxSelectMultiple, help_text='Add existing persons from this company', required=False) # company = forms.ModelChoiceField( # queryset=Company.objects.all().order_by('company_name'), # required=False, # ) date_joined = forms.DateField() date_leaved = forms.DateField() class Meta: model = Membership fields = '__all__' widgets = { "company": CompanyWidget, } -
how to make Django recognize javascript variables and don't raise: VariableDoesNotExist?
I created a custom filter for the Django template and now I need to make filtering by queryset in Django like so: @register.filter def get_data(value, arg): return [value.get(id=arg).error_type, value.get(id=arg).student.student] now by this query, I need to show it when the user hovering one of images but of course, this filter use id to get the specific data filter so, I get this id from dataset attribute from HTML so, the code will look like that now in script: <script> elem_hovers.hover(function () { let data_pk = $(this).data('pk'); console.log(data_pk); // will return correct id number console.log("{{ resp|get_data:data_pk|safe }}") // variable does not exist }) </script> in the last line above will raise the next error: variable does not exist however, if I used the real number which is not coming from a variable which is: 12219 and that is the id number and I used it like so: console.log("{{ resp|get_data:12219|safe }}") then I will get an expected result from filter. so the general question now how can I make Django recognize the javascript variable dynamically without any error occurs? -
Celery worker broadcast thread doesn't have os.cwd()?
I broadcast a command to all celery workers with: app.control.broadcast("run_check") in run_check on the worker, I have: print(f"cwd: {os.getcwd()}") And I get the error: File "/execute/workerTasks.py", line 401, in run_check print(f"cwd: {os.getcwd()}") FileNotFoundError: [Errno 2] No such file or directory I'm a bit stuck - I need to use the filesystem (and I need to run curl and get the response) when my worker gets this command, but anything to do with the filesystem isn't working... what am I doing wrong? -
Forbidden (CSRF cookie not set.) when sending POST/DELETE request from Vue.js to Django
I have been trying for a while to send a POST or DELETE request from my Vue front-end to my Django backend. I am running Vue.js on my localhost:3000, and Django on localhost:8000. I have set up CORS with django-cors-headers, and I am able to GET requests. However, once I try to DELETE or POST, I get this error: Forbidden (CSRF cookie not set.) I understand, that I need to pass a CSRF token in my request's header, which I have: deleteImage() { const url = this.serverURL + 'images/delete/' + this.image_data.pk; const options = { method: "DELETE", headers: {'X-CSRFToken': this.CSRFtoken} }; fetch(url, options) .then(response => { console.log(response); if (response.ok){ // if response is successful, do something } }) .catch(error => console.error(error)); } I obtain this.CSRFtoken from a GET request, and the token is the same if I use the approach shown in Django docs. My Django settings.py looks like this: rom pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
How to Show Average of Star Rating in django
I want to show an Average 5 Star rating in Django. Like in the picture below. In the above image, there is an average rating of all users for a specific product and plus the Count of reviews. Hence to store the rating to DB I used something code like this. views.py def product_detail(request, id): product_detail = Product.objects.get(id=id) review = Review.objects.filter(product = product_detail) return render(request, 'detailpage/productdetail.html', {'product_detail':product_detail, 'review':review}) review.html <div class="container col-sm-7"> <form action="/product_review"> <input type="hidden" name="product_id" id="product_id" value="{{product.id}}"> <h4 style="font-weight:bold" class="mt-5">Create Review</h4> <hr> <h5 style="font-weight:bold">Overall Rating</h5> <div class="stars"> <input class="star star-5" id="star-5" type="radio" name="rate" value="5" /> <label class="star star-5" for="star-5"></label> <input class="star star-4" id="star-4" type="radio" name="rate" value="4"/> <label class="star star-4" for="star-4"></label> <input class="star star-3" id="star-3" type="radio" name="rate" value="3"/> <label class="star star-3" for="star-3"></label> <input class="star star-2" id="star-2" type="radio" name="rate" value="2"/> <label class="star star-2" for="star-2"></label> <input class="star star-1" id="star-1" type="radio" name="rate" value="1rate"/> <label class="star star-1" for="star-1"></label> </div> <h5 style="font-weight:bold">Add a headline</h5> <input type="text" name="subject" class="form-control" id="inputDefault" autocomplete="off"> <br> <h5 style="font-weight:bold">Add a written review</h5> <textarea class="form-control" name="comment" id="exampleTextarea" rows="3"></textarea> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> models.py class Review(models.Model): user = models.ForeignKey(User, models.CASCADE) product = models.ForeignKey(Product, models.CASCADE,null=True, blank=True) subject = models.CharField(max_length = 100, null=True, blank=True) comment = models.TextField(max_length=250, null=True, blank=True) rate = models.IntegerField(default=0) … -
Next parameter in URL does not redirect to the right page with Django
I have a Django app with an authentication system, where people need to ask access to an admin before being able to access the website. Admins receive an email with a link in it to accept of refuse the access, and you need to be logged in to do so. This is the function that is called when they click the link. @login_required() def valid_access(request): if (request.user.groups.filter(name='access_validators').exists()): temp_link = request.GET['temp_link'] demand = Demands.objects.get(temp_link=temp_link) if demand.status != 'validation': return render(request=request, template_name='index.html', context={'message': 'The request has already been ' + demand.status}) else: context = { 'firstname': demand.firstname, 'lastname': demand.lastname, 'email': demand.email, 'organisation': demand.organisation, 'motivations': demand.motivations, 'temp_link': temp_link } return render(request, 'validation.html', context) else: return render(request=request, template_name='index.html', context={'message': 'You don\'t have the right to do that.'}) My urls.py file : urlpatterns = [ path('', include('django.contrib.auth.urls')), path('valid_access', views.valid_access, name='valid_access'), ] If the admin is already logged in, it works fine. If the admin is not logged in, it redirect him to the login page as expected. The link looks like this : https://my.url.com/users/login/?next=https%3A//my.url.com/users/valid_access%3Ftemp_link%3DnAHWc7G3FvG%40Fj But once he's logged in, it does not redirect him to the validation page, but to the LOGIN_REDIRECT_URL I have set in the settings. My login.html looks like this {% extends … -
Is it Possible to Integrate React in an Existing Django Project's Template? Only for a specific template file (Like as- only in cart.html)
I have a complete Django Project, which is ok with all it's features and functionalities. But Now, I want to implement REACT in that project only for the CART Functionality. I want to use react only on cart.html template file. I know how to implement REACT with Django. But I don't know how to do it only in a particular html template file. Have any idea to show it in Django default port?? -
pymongo get relational object query issue
here is code get_category = db.interests.find({"interestStatus": int(page)}).sort([("sequenceId", -1)]) here is collection object {"_id":{"$oid":"60e01893d4cdee8f520b8145"},"interestName":"test1234","interestActiveIconUrl":"","interestInactiveIconUrl":"","sequenceId":{"$numberInt":"59"},"backgroundImage":"","interestStatus":{"$numberInt":"1"},"interestStatusText":"delete","categoryId":{"$oid":"5e5e5fd9527f71283e4582c6"},"createdOn":{"$numberDouble":"1583243225300.9"}} want to get category data by pymongo 'categoryName': i['categoryId']['categoryName'], but getting server error -
How to receive authorization token in Django?
A third party application has send a token to my website http://www.example.com. How to check or print the authorization token? -
Django reload current page without using path
this is probably a noobie question. I'm working on a Django project, after a request, I reload the page using: return redirect('home') Is there anyway to reload the current page without writing the url path? I don't need to specify it, since the page I need to reload is the one that is actually open. Hope someone can help and sorry for easy english -
How to get the variable from api and define in Nginx config file
I am using a GET api in which there is a parameter which is dynamic(a variable). I want to get that variable and give it to my Django server, but how do I tackle this in Nginx as I have a static api location. The code where I am hitting the api: Here waterQuantity is variable that will be provided by the user. http.Response response =await http.get('http://192.168.0.110/openValveConst/$waterQuantity'); This is my Nginx config file right now: location /openValveConst/ { # why should i add / at the end 5000/ to make it work proxy_pass http://127.0.0.1:8000/openValveConst/?format=json proxy_set_header X-Forwarded-For $remote_addr; } Please suggest changes that I should do to make this work. -
OpenEdx Android and IOS application important dates tab not visible
I have a query related to important dates tab in ios and android application, they both are not working the and showing [Unknown error please try again later]. Then i have implemented waffle flags in django for course dates and it starts working on application but now the web is not working. Please help if any have gone through the problem please help. Attaching logs of my android application the log is redirecting to some localhost url but i am unable to find from where it is coming? Android Logs -
my django form is not saving the inputs in the admin panel
How do I style my django form to look like my frontend template originally was? I created my django form and it does not look good and it is not saving the inputs in the admin panel either. Could you tell me what I need to add in the code or what I'm doing wrong? models.py class Complaints(models.Model): user = models.ForeignKey(User, on_delete= CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title views.py: class ComplaintCreate(CreateView): model = Complaints form = ComplaintForm fields = '__all__' success_url = reverse_lazy('New') template_name = 'new.html' template: </div> <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field"> {{form.title}} </div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr"> {{form.description}} </div> <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" class="btn btn-secondary save-btn" value="submit"><i class="fas fa-save"></i> Save</button> </form> </div> forms.py class ComplaintForm(ModelForm): class Meta: model = Complaints fields = '__all__' exclude = ['user'] Also the site looks like this atm: How do I make it look like this?: -
Reference static folder in view
How should I reference an app's static folder from within the app's view? At the moment I am doing the follow which works: background = Image.open("/home/me/django_apps/new_app/static/background.png").convert("RGBA") So I have a static folder in the root folder for my app. -
Django: Get each user Invoices, Expenses, Withdrawals. (ORM) relationship
I've been stuck for a couple of hours, and can't figure out the correct way to do it. So basically I know that looping is not a really good practice, because if we would have a lot of users, the system would start time outing. So my idea is to pick the correct way to get the things that I need. This is our core scheme: I need to make this kind of 'table', and these are the things that I need: This is the thing that will be displayed in our Front-End, so for now, I only need to collect the correct data and pass it into our FE. We use celery tasks, so the timing is always set (Mondays at 6 PM for ex.) This is what I've tried so far.. for user in User.objects.all(): start_date = timezone.now() - timedelta(weeks=1) # How to loop correctly over every user and check for invoices?? invoices = InvoiceItem.objects.select_related('invoice', 'invoice__operation_ptr_id') # invoices[0].operation_ptr_id ??? The looping for user in User.objects.all() should probably be replaced to annotate. How can I make the relationship to get invoices, withdrawals, expenses?