Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Micrososoft One drive save files from django
I have been trying to save my files to onedrive from django rest framework. I have tried following documentation of one drive sdk for python but nowhere it seemed to explain how to make it work th django. Documentation can be found at https://github.com/OneDrive/onedrive-sdk-python. I have made a drf model which is as follows: class ReportVersionModel(models.Model): report_version_name = models.CharField(max_length=255) report = models.ForeignKey(ReportModel, on_delete=models.CASCADE) created_by = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True, null=False, blank=False) file = models.FileField(upload_to='message/%Y/%m/%d/', max_length=100, blank=True) what I need help is regarding how to use this model with the one drive sdk. -
item.delete(force_policy=HARD_DELETE) does not working
I have the following model class User(SafeDeleteModel, AbstractUser, PermissionsMixin, BaseModel): name = models.CharField( blank=True, null=True, max_length=255) I tried this. from safedelete import HARD_DELETE, HARD_DELETE_NOCASCADE item = User.objects.get(id=3) item.delete(force_policy=HARD_DELETE) but when I say User.objects.get(id=3) I am still getting the user instead of a 404 error. -
Hi, I have two problems and I am new
My first problem is that in VS fertilizer when (from django) I put a line in each part below it and it does not recognize it, and my second problem is that I enter my code in the Django file in the Models section And then in the code terminal python (manage.py makemigrations) We make an error, thank you for your help. -
Error receiving POST request and uploading to db from form Django
I ran into a problem when entering data into the form. Nothing is added to the database, although there are no errors in the terminal (but the POST request is not highlighted in green, I attach a screenshot) . Created "else:return render(request, "food/test.html ")" to check for an error, I've already searched half the Internet, I can't understand what the error is (there is a suggestion that it's about adding an image) I'm fixing all the files. models.py from django.db import models class Recipe(models.Model): recipe_title = models.CharField(max_length=20) recipe_time = models.IntegerField() recipe_ingridients = models.IntegerField() author_name = models.CharField(max_length=30) image = models.FileField(upload_to='') recipe = models.TextField(max_length=300) forms.py from django.forms import ModelForm, TextInput, Textarea, NumberInput, FileInput from .models import Recipe class FoodForm(ModelForm): class Meta: model = Recipe fields = ["recipe_title", "recipe", "recipe_time", "recipe_ingridients", "author_name", "image"] widgets = { "recipe_title" : TextInput( attrs={ "class" : "title_form", "placeholder" : "Введите название рецепта" } ), "recipe": Textarea( attrs={ "class": "form_of_all", "placeholder": "Введите ваш рецепт" } ), "recipe_time" : NumberInput( attrs={ "class" : "ingr", "placeholder" : "Введите время" } ), "recipe_ingridients": NumberInput( attrs={ "class": "ingr", "placeholder": "Введите кол-во ингридиентов" } ), "author_name" : TextInput( attrs={ "placeholder" : "enter quthor name" } ), "image" : FileInput( attrs={ 'type' : "file", … -
i am trying to develop a web app using django framework i uploaded an excel file now iam looking to find the top 10 values from it. tell me the logic
This is the code for uploading an excel file in django. i want to take the top 10 values and least 10 values and print it in a page. how can i do that? views.py def excel(request): if "GET" == request.method: return render(request, 'blog/excel.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["report"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'blog/excel.html', {"excel_data":excel_data}) -
Edit multiple Models using one form or view in Django
I am using the default User model in Django and a OneToOneField in a Profile model where extra info such as user bio is stored. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) I am able to create basic forms for the two models independently from django.contrib.auth.models import User class UserForm(ModelForm): class Meta: model = User fields = ['username', 'email'] class ProfileForm(ModelForm): class Meta: model = Profile fields = ['bio'] What is the best method to create a page where a user can edit fields of either model? So a User can edit Username,Email or Bio on the same page? -
Read data from the google sheets and dump into the different tables of database python django
I am looking for direction in which I can dump data from the google sheets(which have more than one sheet). I have a database in which there is a many-to-many relationship, one-to-one relationship, etc. so I am looking for any blog, documentation, or video tutorial for this purpose. My stack is Python, Django and Postgresql -
how to submit a selected option of a drop-down list in django?
I'm trying to create a list of jenkins' jobs and build the sected one in django but I didn't know how to implement the right code of the submit button in the views.py to build the job. index.html the index.html views.py the views.py file Any help please?!!! -
How to query additional databases using cursor in Django Pytests
I am developing a Django app that uses cursor to perform raw queries to my secondary DB: my_db2, but when running tests, all the queries return empty results, like if they were running on parallel transactions. My test file: @pytest.mark.django_db(transaction=True, databases=['default', 'my_db2']) class TestItems: def test_something(self): person1 = PeopleFactory() # Adds 1 person to my_db2 assert fetch_all_persons() == 1 # Fails Returns 0 My function: from django.db import connections def fetch_all_persons(): with connections['my_db2'].cursor() as cursor: cursor.execute(f"SELECT * FROM Persons") return len(list(cursor.fetchall())): According documentation transaction=True should prevent this issue, but it doesn't, does somebody know how to fix it? -
Creating and updating Model object using form
models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now_add=True) title = models.TextField(null=True) body = models.TextField(null=True) def __str__(self): return str(self.user) class ImagesPostModel(models.Model): post = models.ForeignKey(PostModel, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True) views.py def post(request): post = PostModel(user=request.user) post.save() if request.method == 'POST': form = PostModelForm(request.POST, instance=post) images = request.FILES.getlist('images') for image in images: ImagesPostModel.objects.create(post=post, images=image) if form.is_valid(): form.save() return redirect('/Blog/home/') else: form = PostModelForm(request.POST) return render(request, 'post.html', {'form': form}) I created a PostModel object post and save it in the database using save() method. I have provided the instance parameter as post object in the form, so the form should be updating the above created post but it is creating another PostModel object and inserting into the database by itself. So there are two post begin created and being inserted into the database, first one is because of post = PostModel(user=request.user) and I dont know why the second one is being created. why is this happening? -
How to parse to json multi select from postgres function in django
I have two select queryies that will return refcursors, they are in one function: open Ref1 for select * from TMP limit page_size offset (page - 1) * page_size; return next Ref1; ---- open Ref2 for select totalRecord as totalRecord , pageTotal as pageTotal; return next Ref2; In view django I use a cursor to execute above function like that: with connection.cursor() as cursor: cursor.execute('select * from fnc_get_news(1, 30)') row = cursor.fetchall() I dont know how to do next and I know I can try pyodbc to do it. I try to install Django 3.2, odbc-postgresql (latest) and when run server I got: File "/usr/local/lib/python3.8/dist-packages/django_pyodbc/base.py", line 98, in > < raise ImproperlyConfigured("Django %d.%d is not supported." % DjangoVersion[:2]) <django.core.exceptions.ImproperlyConfigured: Django 3.2 is not supported. I am standstill with this problem, please help me. -
Cookies not being sent with Axios
I have a form built on Nuxt/vuejs. On the backend side on django the CSRF protection is enabled which now expects two things in the Api call X-CSRFToken as a header and csrftoken as a Cookie , I tested the Api by calling the Api through Postman which works fine but in case Of Vue it is not sending the Cookies with post request let me show you my code Axios post request const headers = { "X-CSRFToken": "some token", "Cookie": "csrftoken=some token", } await axios.post(`onboarding/first-name-last-name-email/`, { "first_name": "uneeb2", "last_name": "sad", "email": "asdsa@asd.colm" }, { headers: headers }, { withCredentials: true }) one important thing to mention here CORS is enabled by server, so I am not doing anything specific for that. I also tried setting the cookie as natively by document.cookie = "csrftoken=some token; Path=/; Expires=Mon, 16 Feb 2023 08:02:50 GMT;"; through this I can see the Cookie being set on browser but this still not sends the cookie with post request As you can see I've also tried withCredentials: true which was one of the common proposed solutions by in my case this did not work as well. About the Server config , the Django server is a … -
Use filename insted of 'Download'
On my Django page I have a paragraph to download attached files: {% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}" >Download</a></p>{% endfor %} How can I show File name insted of word 'Download'. Users don't know which file is which when downloading, in case of many files. Also, if extension is possible. So, insted of: Attachment: Download I would like to have: Attachment: image.png -
Getting "'type' object does not support item assignment" in django
I am using django referrer policy middleware and it is giving me intermittent error of type assignment. Below is the error trail. File "/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/env/lib/python3.6/site-packages/django_referrer_policy/middleware.py" in __call__ 36. response['Referrer-Policy'] = settings.REFERRER_POLICY Exception Type: TypeError at / Exception Value: 'type' object does not support item assignment Django : 2.0.3 Python : 3.6 Thanks in advance. -
Django: How to group a QuerySet by two ForeignKeys then apply Sum
I have the following simplified models: class Workout(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="workouts") # ... class Exercise(models.Model): # ... class WorkoutSet(models.Model): dt = models.DateTimeField(default=timezone.now) workout = models.ForeignKey( Workout, on_delete=models.CASCADE, related_name="sets") exercise = models.ForeignKey( Exercise, on_delete=models.PROTECT, related_name="sets") repetitions = models.PositiveSmallIntegerField() weight = models.DecimalField(max_digits=6, decimal_places=2) # ... Assume I have the following data in the WorkoutSet table: Workout ID Exercise ID Repetitions Weight DateTime 1 1 10 15 02/02/2022 1 1 10 15 02/02/2022 1 1 10 15 02/02/2022 1 2 8 30 02/02/2022 1 2 8 35 02/02/2022 1 2 8 35 02/02/2022 2 1 10 20 15/02/2022 2 1 10 20 15/02/2022 2 1 10 20 15/02/2022 And assuming today is the 16th of February, 2022. Ultimately, I want, for each exercise (if it happens to be their best performance), to say: "This week, you achieved your best for exercise 1 with a total load of 600 (20X10+20X10+20X10), which is 150 higher (15X10+15X10+15X10) than your previous personal record (PR)". This is how I'm thinking of tackling this: Get this week's WorkoutSet objects related to the user Group the results by Workout ID and Exercise ID, and annotate with the sum of the multiplication of Repetition and Weight Get the … -
Using prefetch_related_objects on nonhomogenous objects with a shared relationship
ModelA has a Many-to-One relationship to ModelC ModelB has a Many-to-One relationship to ModelC I have a situation where I need to access the related objects through both like model_a_instance.model_c and model_b_instance.model_c and I don't want to fire off N additional queries. I found that using prefetch_related_objects(list_of_model_a_instances + list_of_model_b_instances, 'model_c') works as expected. However, peaking into prefetch_related_objects code I noted this. # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] Are there any side effects I should be worried about here? I did notice that the related instances are identical. list_of_model_a_instances[0].model_c is list_of_model_b_instances[0].model_c Out[1]: True So, downstream code will need to not unexpectedly modify the related objects to prevent undefined behavior. Anything else I should be worried about here? -
Javascript (Ajax ) function of combined events in Django application
I 'm building a restaurant eCommerce api using Django framework. Now I 'm working on cart application part. The restaurant offers several products (categories) incl. pizza, burger... For pizza, the product variants contains size (small, medium and large) as well as base (thin, standard). For burgers, it contains different sauces as its variants. Different combinations give different prices. For example, the price of pizza with salami (product id =1), small size (size id=1) and standard base (base id=2) is 12 euro. The corresponding productAttribute id (salami+small+standard) is 3. The purchasing workflow would be, after customer choosing a product (pizza salami) and selecting size and base, the price would be automatically updated. I 'm wondering how should I implement this logic. Any comments? Thanks! -
is it ok to call REST API inside normal Django app
So I am creating an app which has mobile version as well as web version but most of the users will be on mobile and very less on web,I am done with rest API now I have to create a client site but I dont want to use react or any other framework. So do you think is it possible to create a normal django project and call API under each view signup, login and then return the response through render to web page? -
custom group with foreignkey didn't work on permission control
I need to add some fields to my group model, so I make my own custom model that linked to original group with ForeignKey. when I tried the custom group with permission control it didn't work. custom group model : class Roles(models.Model): id = models.CharField(max_length=255, blank=True, primary_key=True) name = models.CharField(max_length=255, blank=True) label = models.CharField(max_length=255, blank=True) desc = models.TextField(blank=True, null=True) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) custom user model : class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True) label = models.CharField(max_length=255, blank=True) roles_id = models.ForeignKey(Roles, on_delete=models.CASCADE, blank=True, null=True) desc = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is there anything wrong with my model? -
Possible to get queryset from list of queryset -Django
I wanted to take queryset from multiple models. I am trying to achieve multiple search with and condition. views.py, def list(self, request, *args, **kwargs): search_query = self.request.query_params.get('search') split_query = search_query.split() employment = None employee1 = [] employment1 = [] for query in split_query: print("hi", query) # query = self.request.query_params.get('search') employee = PositionFulfillment.objects.filter( Q(employment__employee__code__icontains=query) | Q(employment__employee__person__name__icontains=query) | Q(employment__employee__person__surname__icontains=query) ) # emp = list(chain(employee)) employee1.append(employee) print("employee", employee1) active_employee = PositionFulfillment.objects.filter(primary_flag=True, thru_date=None) if active_employee: employment = active_employee.filter( Q(position__position_type__name__icontains=query) | Q(employment__organization__name__icontains=query) | Q(employment__status__status__employment_status__icontains=query) ) employment1.append(employment) all_results = list(chain(map(lambda x: x, employee1), map(lambda y: y, employment1))) # all_results = list(chain(employee, employment)) print("all_results", all_results) serializer = EmployeeSearchSerializer(all_results) return Response(serializer.data, status=status.HTTP_200_OK) I have got output like below, all_results, [<QuerySet [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]>, <QuerySet []>, <QuerySet []>, <QuerySet [<PositionFulfillment: 28>]>] Expected output, [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]> ,<QuerySet [<PositionFulfillment: 28>]>] How can i achieve this??? -
How can I get the donation amount field against each employee in Django from frontend?
I am working on a donation app. In this app, I am changing a feature that every employee of the organization gets an equal amount of donation to a customized amount of donation. I will be receiving different donation amounts for each employee from the frontend. I don't exactly know how to do that. Here is my code: class BusinessDonation(): def create(self, request, response, business): employees= Employment.objects.filter(business=business, active=True) try: amounts = int(request.payload.get("amounts")) total = int(request.payload.get("total")) except ValueError: return response.bad_request("Invalid donation amounts, %s, should be in whole dollars" % amounts) error = run_employee_donation(business.id, to_cents(amounts)) if error != '' and error is not None: return response.bad_request(error) response.set(**{'success': True} -
Django application not running inside docker
[ex][1] Django response from browser -
Django: aggregate if all boolean model fields is True
from django.db import models class Car(models.model): sold = models.BooleanField(default=False) I can detemine if all cars were sold by making two queries: sold_count = Car.objects.filter(sold=True).count() all_count = Car.objects.count() are_all_sold = (all_count - sold_count) == 0 Since this operation is very frequent on my app, I am wondering if it is possible to do it in just one DB query? e.g. using Aggregation or Query Expressions, etc. -
What is error for when install psycopg2==2.7.*?
pip3 install psycop2==2.7.* I try to install Django project on a live server but when I install the package I am getting error! pip install psycopg2==2.7.* -
Django How to check a request is Ajax
The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.