Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Traverse Foreign Keys
I have 3 models and I am trying to create a dashboard with a list of Trials that spans all Client Sessions for a specific client chosen via a filter. Here are the models: class Trial(models.Model): behavior_name = models.ForeignKey(Behavior, on_delete=models.CASCADE) client_session = models.ForeignKey(Client_Session, on_delete=models.CASCADE) frequency_input = models.PositiveIntegerField(default=0, blank=True) duration_input = models.DurationField(blank=True, default=timedelta(minutes=0)) class Meta: verbose_name_plural = 'trials' def __str__(self): return str(self.id) class Client_Session(models.Model): name = models.CharField(max_length=200, null=False) session_date = models.DateField(blank=False,null=False) client = models.ForeignKey(Client, on_delete=models.CASCADE) behaviors = models.ManyToManyField(Behavior, null=False) therapist = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Meta: verbose_name_plural = 'clientsessions' def __str__(self): return self.name class Client(models.Model): #user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES,blank=True) gaurdian_first_name = models.CharField(max_length=200, blank=True) gaurdian_last_name = models.CharField(max_length=200, blank=True) diagnosis = models.CharField(max_length=200, choices=DIAGNOSIS_CHOICES, blank=True) therapist = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.last_name Here is the view that im trying to create def dashboard(request): # filter list of client sessions by selected client client_sessions = Client_Session.objects.filter(therapist=request.user) client = DashboardClientFilter(request.GET, queryset=client_sessions) client_sessions = client.qs #Create list of Trials across Client Sessions for the filtered client trial_list = Trial.objects.filter(client_session__client=client) -
method to test get_queryset using Pytest
I've created a get_queryset function in order to fetch multiple product Id's filter_fields = ( "id", "name", "mass", ) ordering_fields = ( "id", "name", "mass", ) def get_queryset(self): queryset = Product.objects.all() id_value = self.request.query_params.get('id') if id_value is not None: queryset = queryset.filter(id__in = id_value) return queryset I would like to test this in test.py using pytest to check if the code is actually working with multiple id's. I am not very fond of django testing so how could I test this code out by creating a def test function in test.py The current approach to test function is def test(self, client, authenticated_headers): request = RequestFactory().get('/views/ProductsView') view = ProductsView view.request = request input_data = [ { "id": "1" * 100, "name": "Test Product1111111", "mass": 100, }, { "id": "1" * 100, "name": "Test Product1111111", "mass": 100, }, ] qs = view.get_queryset() res = client.post( reverse("______"), data=input_data, **authenticated_headers, ) self.assertQuerysetEqual(qs, Product.objects.all()) assert res.status_code == 200 -
Two querysets in one view in Django
so I'm trying to make two lists in one view but with different filters. They also change whether the campaign is paused or is running. This is what I came up with but it throws this error: TypeError: init() got an unexpected keyword argument 'queryset_paused' This is my views.py def home_view(request): #campaigns in progress queryset = Campaign.objects.filter(is_active=True, completion_percent__lt=100) if request.method == "POST": form_type = request.POST.get('id') if form_type == 'campaign_status': formset = CampaignStatusFormSet( request.POST, request.FILES, queryset=queryset, ) formset.save() else: formset = CampaignStatusFormSet(queryset=queryset) campaigns_and_forms = list(zip(queryset, formset)) #paused campaigns queryset_paused = Campaign.objects.filter(is_active=False, completion_percent__lt=100) if request.method == "POST": form_type = request.POST.get('id_paused') if form_type == 'campaign_status_paused': formset_paused = CampaignStatusFormSet( request.POST, request.FILES, queryset_paused=queryset_paused, ) formset_paused.save() else: formset_paused = CampaignStatusFormSet(queryset_paused=queryset_paused) campaigns_and_forms_paused = list(zip(queryset_paused, formset_paused)) context = { 'formset': formset, 'campaigns_and_forms': campaigns_and_forms, 'formset_paused': formset_paused, 'campaigns_and_forms_paused': campaigns_and_forms_paused, } return render(request, 'campaigns_in_progress.html', context) Here is my template for the two lists <table class="table table-striped table-hover table-bright table-bordered align-middle"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Nazwa</th> <th scope="col">Temat</th> <th scope="col">Nadawca</th> <th scope="col">Procent Realizacji</th> <th scope="col">Start Kampani</th> <th scope="col">Stan</th> </tr> </thead> <tbody> <form method="post" id="campaign_status"> {% csrf_token %} <input type='hidden' value='campaign_status' name='id'> {{ formset.management_form }} {% for campaign, form in campaigns_and_forms %} <tr> <td>{{ campaign.campaign_id }}</td> <td>{{ campaign.name }}</td> <td>{{ campaign.topic }}</td> … -
Django PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
I upload files to Google Drive by uploading files to the system first and then to Google Drive, after that I immediately delete them from website directory in one process. But here I get an error. I'm not deleting files on google drive but deleting files in the website directory. views.py tfile = request.FILES['file'] temp = db.FileTemp(files=tfile) temp.save() media_metadata = { 'name': str(tfile), 'parents': [folder.objects.filter(user__username=user)[0].id_folder] } media = MediaFileUpload(os.path.join(temp.files.path), mimetype='image/jpeg', resumable=True) upfile = drive.files().create(body=media_metadata, media_body=media, fields='id').execute() user_permission = { 'type': 'anyone', 'role': 'reader', } perm = drive.permissions().create(fileId=upfile.get('id'), body=user_permission).execute() link = drive.files().get(fileId=upfile.get('id'), fields='webViewLink').execute() result['status'] = True result['link'] = link['webViewLink'] temp.delete() models.py class FileTemp(models.Model): files = models.FileField(upload_to="file") @receiver(post_delete, sender=FileTemp) def foto_file_delete_handler(sender, **kwargs): filed = kwargs['instance'] storage, path = filed.files.storage, filed.files.path storage.delete(path) -
Extending multiple CustomViewsets - as readonly with Django
in our project, our lead developer assigned a task to refactor some viewsets in our project. Create a readonly Asset view that will return all defaults and romy assets So the original code looks like this class DefaultAssetViewSet(viewsets.ModelViewSet): queryset = DefaultAsset.objects.all() serializer_class = DefaultAssetSerializer permission_classes = [IsAdminUser] filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] filterset_fields = ['name'] search_fields = ['name', 'default_value'] @action(detail=False, methods=['get']) def defaults(self, request): defaults = {} for d in self.queryset.all(): defaults[d.name] = d.default_value return Response({'defaults': defaults}) def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **kwargs) except models.ProtectedError: return Response( {'detail': ErrorDetail('Unable to perform this action.')}, status=status.HTTP_403_FORBIDDEN) class RomyAssetViewSet(viewsets.ModelViewSet): queryset = RomyAsset.objects.all() serializer_class = RomyAssetSerializer permission_classes = [IsAdminUser] filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] filterset_fields = [ 'romy', 'default_asset' ] search_fields = [ 'romy', 'default_asset' ] So my first idea to come to my mind is to extend these two Views into AssetViewSet class class AssetViewSet(RomyAssetViewSet, DefaultAssetViewSet,viewsets.ReadOnlyModelViewSet): """ some code here""" Is it possible to extend custom viewsets like these? And also how to implement get or list for both RomyAssetViewet and DefaultAssetViewset inside AssetViewsetClass? -
How to pass type arguments when using a django generic class based view?
I want to use django.views.generic.edit.FormView and since it's a generic, I'm giving it a type argument (MyForm): class MyView(FormView[MyForm]): ... But it causes this error: TypeError: 'type' object is not subscriptable What's the proper way to pass type arguments to FormView? -
Heroku Posgres' DATABASE_URL cannot be loaded in Django's setting.py and application error occurs
When building an API server using Django+REST framework and uploading it to Heroku, hard-coding Heroku Postgres' DATABASE_URL in the DATABASES of setting.py as follows will work on Heroku without problems. (xxx is originally the information of DATABASE_URL, but we dare to hide it this time) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxx', 'HOST': 'xxx', 'PORT': '5432', 'USER': 'xxx', 'PASSWORD': 'xxx, } } However, you can add a .env file to your Django project, stating the following (where xxx is the information originally entered for the DATABASE_URL, but we've dared to hide it this time) DATABASE_URL=postgres://xxxx In setting.py import dj_database_url from dotenv import ( find_dotenv, load_dotenv, ) load_dotenv(find_dotenv()) DATABASES = { 'default': dj_database_url.config(conn_max_age=600), } If I put something like this, it works in the local environment, but when I upload it to heroku, I get an application error. Do you know the cause? -
Don't know how to query a complex SQL in django
I have these two models below class Category(models.Model): id = models.AutoField(primary_key=True) cate_id = models.CharField(max_length=16, editable=False, default=utils.generate_random_str) name = models.CharField(max_length=64, default="") class Record(models.Model): id = models.AutoField(primary_key=True) record_id = models.CharField(max_length=16, editable=False, default=utils.generate_random_str) count = models.IntegerField(blank=True) user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) And I want to make SQL Query distinct cate_id and Sum their values and Group them like this: SELECT B.name , SUM(A.count) AS count_sum FROM app_record AS A, app_category AS B WHERE A.`user_id` = 1 AND B.cate_id IN ( SELECT DISTINCT(B.cate_id) FROM app_record AS C, app_category AS D WHERE C.category_id = D.id ) AND A.category_id = B.id GROUP BY B.cate_id; I expect the results should be like this: +---------+-----------+ | name | count_sum | +---------+-----------+ | Test1 | 494 | | Test2 | 18 | | Test3 | 269 | +---------+-----------+ 3 rows in set (0.001 sec) I want to make that query in Django but I couldn't work out on my own. I have tried this but it didn't seem to work out: Record.objects.filter( user=user ).distinct().annotate( record__category_id=F('category__id') ).aggregate( count_sum=Sum('count') ) I don't know how to do that, hope someone can solve this.Thanks a lot. -
How to write an ajax like button for django like object that uses foreign key?
So I have been trying to write a jquery ajax button that would stop page reload effect when a post object is liked, As I'm having a challenge doing so because my like model object is using a foreign key on my webapp, As I can do this with a many to many field but my challenge is when I change my like button to a ManyToMany field i wouldn't be able to recover already liked post on my app and I find it would be much convenient if I could write jQuery ajax to handle the foreign key like object instead. This is what i have been able to come up with , but it doesn't trigger the like button ! #Model for like class Like(models.Model): user_like = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_likes', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='user_likes', on_delete=models.CASCADE) like_date = models.DateTimeField(auto_now=True) View.py def like_button(request, pk, c_slug=None): user = request.user if request.method =="POST": if request.POST.get("operation") == "like_submit" and is_ajax(request=request): content_id=request.POST.get("content_id",None) content=get_object_or_404(Like,pk=content_id) if liked.likes.filter(id=request.user.id): #already liked the content content.likes.remove(request.user) #remove user from likes liked=False else: content.likes.add(request.user) liked=True resp = { 'liked':liked,'like_id':content_id, } response = json.dumps(resp) return HttpResponse(response,content_type = "application/json") product = Product.objects.get(pk=pk, slug=c_slug) liked= False like = Like.objects.filter(user_like=user, product=product) if like: like.delete() else: … -
Django How to format JSON response from drf API?
I would like to know how to modify the way I represent the JSON Response of my requests to the API created with DRF, tabs, spaces, etc..., in order to respond exactly to my frontend app. I have the following code: My models.py extract: class Email(models.Model): user_email = models.CharField(primary_key=True, max_length=200) user_phone_number = models.IntegerField() user_device_id = models.CharField(max_length=200)#request.META.get('HTTP_DEVICE', '') lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) user_address = models.CharField(max_length=200) creation_date = models.DateTimeField(default=None) email_status = models.BooleanField(default=False) email_score = models.IntegerField() valid_email = models.BooleanField(default=False) fraud = models.BooleanField(default=False) My views.py extract: class UserListView(APIView): serializer_class = EmailSerializer queryset = Email.objects.all() pagination_class = StandardResultsSetPagination def get_serializer_class(self): if self.action == 'list': return EmailListSerializer return EmailSerializer def post(self, request, *args, **kwargs): parametros = request.POST email='email=' + request._full_data['user_email'] response = UserConnector(email).get_user_data() obgs = response[1]['results'] if len(obgs) == 0: user_email = self.request.POST.get('user_email') email_stat = '' email_scor = '' email_valid = '' frau = '' else: obg = response[1]['results'][0] user_email = self.request.POST.get('user_email') email_stat = obg.get('email_status') email_scor = obg.get('email_score') email_valid = obg.get('valid_email') frau = obg.get('fraud') NewEmail = Email( user_email = user_email, user_phone_number = self.request.POST.get('user_phone_number'), user_device_id = request.META.get('HTTP_DEVICE', ''), lat = self.request.POST.get('lat'), lng = self.request.POST.get('lng'), user_address = self.request.POST.get('user_address'), creation_date = timezone.now, email_status = email_stat, email_score = email_scor, valid_email = email_valid, … -
Problem with .only() method, passing to Pagination / Serialization --- all fields are getting returned instead of the ones specified in only()
I am trying load some data into datatables. I am trying to specify columns in the model.objects query by using .only() --- at first glance at the resulting QuerySet, it does in fact look like the mySQL query is only asking for those columns. However, When I try to pass the QuerySet into Paginator, and/or a Serializer, the result has ALL columns in it. I cannot use .values_list() because that does not return the nested objects that I need to have serialized as part of my specific column ask. I am not sure what is happening to my .only() db_result_object = model.objects.prefetch_related().filter(qs).order_by(asc+sort_by).only(*columns_to_return) paginated_results = Paginator(db_result_object,results_per_page) serialized_results = serializer(paginated_results.object_list,many=True) paginated_results.object_list = serialized_results.data return paginated_results -
Why are my items not showing in my cart? Django
Can someone tell me why my products are not showing up on my cart? They are being added to the database but somehow not showing up on my page. I will attach some screenshots of my project: These are the important views: enter image description here This is the form used to add the products to cart: enter image description here And this is the cart.html, where nothing shows up: enter image description here This shows up once I open the cart on the browser: enter image description here -
TypeError: test_load_category_from_OFF() missing 1 required positional argument: 'monkeypatch'
def test_load_category_from_OFF(self, monkeypatch): def mockreturn(): test_category_loaded = [ {'category_name': 'Aliments et boissons à base de végétaux', 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-et-boissons-a-base-de-vegetaux'}, {'category_name': "Aliments d'origine végétale", 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-d-origine-vegetale'}, {'category_name': 'Snacks', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks'}, {'category_name': 'Viandes', 'category_url': 'https://fr.openfoodfacts.org/categorie/viandes'}, {'category_name': 'Snacks sucrés', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks-sucres'} ] return test_category_loaded monkeypatch.setattr(category_importer, 'load_category_from_OFF', mockreturn) expected_results = [{'category_name': 'Aliments et boissons à base de végétaux', 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-et-boissons-a-base-de-vegetaux'}, {'category_name': "Aliments d'origine végétale", 'category_url': 'https://fr.openfoodfacts.org/categorie/aliments-d-origine-vegetale'}, {'category_name': 'Snacks', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks'}, {'category_name': 'Viandes', 'category_url': 'https://fr.openfoodfacts.org/categorie/viandes'}, {'category_name': 'Snacks sucrés', 'category_url': 'https://fr.openfoodfacts.org/categorie/snacks-sucres'} ] category_loaded = self.category_importer.load_category_from_OFF() category_fetched = self.category_importer.fetch_category(category_loaded, 5) assert category_fetched == expected_results I don't understand where is my error. When I run the test, I have the message below : E TypeError: test_load_category_from_OFF() missing 1 required positional argument: 'monkeypatch' But I don't know where I'm wrong. Please help ^^' this my file of category : """Internal imports""" from requests import get from purbeurre_website.models import Category class CategoryImporter: """ Import category of products from the API OpenFoodFacts(OFF) and insert it in the database. """ def __init__(self): self.category_table = Category.objects.all() @staticmethod def load_category_from_OFF(): """ Loads the categories datas from the URL address in OFF. """ categories_url = "https://fr.openfoodfacts.org/categories&json=1" request = get(categories_url) # To get the json format categories_url_json = request.json() return categories_url_json @staticmethod def fetch_category(categories_url_json, nb_category): # We … -
DRF TimeZoneField: not JSON serializable error
I have django model: from django.db import models from timezone_field import TimeZoneField class Client(models.Model): time_zone = TimeZoneField(choices_display='WITH_GMT_OFFSET') And APIView for this model: class ClientAPIView(APIView): def get(self, request: Request, pk: int, format=None) -> Response: client = get_object_or_404(Client, pk=pk) client_serializer = ClientListSerializer(client) return Response(client_serializer.data) I get an error from GET request: TypeError: Object of type ZoneInfo is not JSON serializable Serializer code: class ClientListSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ('id', 'time_zone') How fix code of Model, Serializer or View (I don't know what exactly) so that instead of ZoneInfo there is just a string. UPDATE: if change serializer: class ClientListSerializer(serializers.ModelSerializer): time_zone = serializers.CharField(max_length=256) GET request will be work, but POST request give me error, if send invalid string for time zone. For example {"time_zone": "invalid string"} Result: django.core.exceptions.ValidationError: ["Invalid timezone 'invalid string'"] My POST method code: def post(self, request: Request, format=None) -> Response: client_serializer = ClientSerializer(data=request.data) if not client_serializer.is_valid(): return Response(client_serializer.errors, status=status.HTTP_400_BAD_REQUEST) client_serializer.save() return Response('client was created successfully', status=status.HTTP_201_CREATED) SOLVED Maybe this is not the best solution, but now requests work correctly after modify serializer: import pytz from rest_framework import serializers class ClientSerializer(serializers.ModelSerializer): time_zone = serializers.ChoiceField(choices=pytz.all_timezones) class Meta: model = Client fields = ('id', 'time_zone') If you know better solution, … -
Stripe Checkout with django-stripe: how pass fees on to customers (surcharging)?
I am using django-stripe to generate Stripe Checkouts. I would like to pass the Stripe fees on to my customers ("surcharging"). I found a help article from stripe regarding this. It says in general how to calculate the fees to put on top of the price of the product. The problem is, that different payment methods have different fees. And when creating the Checkout, I must calculate the final price (including the fees I want to pass on) before I know what payment method the customer will select (and therefore what fees the customer will have to pay). So I don't know the fees when I must put them on top of the price the user has to pay in the Checkout. Is there a way out of this dilemma? -
Use Django Model to find 1 record per hour, and the most recent one from another timestamp
Django 3.2.9 db: (PostgreSQL) 14.0 Model class InventoryForecast(models.Model): count = models.IntegerField() forecast_for = models.DateTimeField(null=False) forecasted_at = models.DateTimeField(null=False) Data id count forecast_for forecasted_at 8 40910 2022-10-10 11:00 2022-09-04 12:00 9 40909 2022-10-10 11:00 2022-09-05 12:00 10 50202 2022-10-10 11:00 2022-09-06 12:00 (most recent forecast) 11 50301 2022-10-10 12:00 2022-09-04 12:00 12 50200 2022-10-10 12:00 2022-09-05 12:00 13 50309 2022-10-10 12:00 2022-09-06 12:00 (most recent forecast) How would I use Django Model to find 1 record per forecast_for hour, and the most recent one for the forecasted_at value? So in this example, 2 records. Desired results id count forecast_for forecasted_at 10 50202 2022-10-10 11:00 2022-09-06 12:00 13 50309 2022-10-10 12:00 2022-09-06 12:00 What I've tried >>> from django.db.models.functions import TruncHour >>> from django.db.models import Max >>> InventoryForecast.objects.annotate( hour=TruncHour('forecast_for') ).values('hour').annotate( most_recent_forecasted_at=Max('forecasted_at') ).values('hour', 'most_recent_forecasted_at') SELECT DATE_TRUNC('hour', "app_inventoryforecast"."forecast_for" AT TIME ZONE 'UTC') AS "hour", MAX("app_inventoryforecast"."forecasted_at") AS "most_recent_forecasted_at" FROM "app_inventoryforecast" GROUP BY DATE_TRUNC('hour', "app_inventoryforecast"."forecast_for" AT TIME ZONE 'UTC') LIMIT 21 Execution time: 0.000353s [Database: default] <QuerySet [{'hour': datetime.datetime(2022, 10, 10, 12, 0, tzinfo=<UTC>), 'most_recent_forecasted_at': datetime.datetime(2022, 9, 6, 11, 0, tzinfo=<UTC>)}, {'hour': datetime.datetime(2022, 10, 10 , 11, 0, tzinfo=<UTC>), 'most_recent_forecasted_at': datetime.datetime(2022, 9, 6, 11, 0, tzinfo=<UTC>)}]> That works correctly in the GROUP BY, but I need the … -
I have an error "TypeError: can't multiply sequence by non-int of type 'str'"
Throwing an error "TypeError: can't multiply sequence by non-int of type 'str'" text1 = "Hello" text2 = "World" result = text1 * text2 print(result) Error message: result = text1 * text2 TypeError: can't multiply sequence by non-int of type 'str' -
Django - compare values of keys in dictionaries in two different lists
I have two lists of dictionaries that I have pulled from an XML file using elementtree. Each list of dictionaries contains dozens of keys/values but for simplicity sake let's say it's similar to the below: list1 = [{'id': '100', 'first_name': 'john'}, {'id': '101', 'first_name': 'joe'}] list2 = [{'id': '100', 'last_name': 'doe'}, {'id': '101', 'last_name': 'bloggs'}] I'm using Django to build a table with the data and want to put the first names (from list1) and last names (from list2) on the same row of the table where there's a match in the 'id' values, but I can't figure out how to do this. If I wanted to list them in python I would use: for v in list1: print(v['id']) print(v['first_name']) for i in list2: if i['id'] == v['id']: print(i['last_name']) But I can't figure out how to write this with django tags in the HTML template. Here's what I've tried (and variations thereof): {% for v in list1 %} <tr> <td>{{v.id}}</td> <td>{{v.first_name}}</td> {% for i in list2 %} {% if {{v.id}} == {{i.id}} %} <td>{{i.last_name}}</td> {% endif %} {% endfor %} </tr> {% endfor %} -
Django notification hq mark_as_read
I am using django-notifications-hq for make notifications working on a Django app. I am having problems with the function "mark_as_read". What I am trying to achieve is to have a notification list and, when clicking on a notification, mark it as read and redirect to the url of the post. The problem is that, basically, I am having problems with that. I tried many different ways on the template such as: <a href="{% url 'main:question_details' pk=notification.target.question.id slug=notification.target.question.slug %}?next={{notification.mark_as_read}}" class="text-reset notification-item"> {% if notification.unread == True %} <div class="d-flex alert-warning"> {% else %} <div class="d-flex"> {% endif %} <div class="flex-1"> <span class="text-dark small">Commento</span> <span class="text-dark small float-end"><i class="mdi mdi-clock-outline"></i> {{notification.timestamp|naturaltime}}</span> <h6 class="mb-1">{{notification.verb}}</h6> <div class="font-size-12 text-muted"> <p class="mb-1">{{ notification.target.comment }}</p> </div> </div> </div> </a> In this case the redirect works but, as soon as I press the dropdown menu, the notification is already marked as read. If I remove the ?next={{notification.mark_as_read}} the redirect works but the notification isn't marked as read. Anyone has ever worked with django notifications had an issue like that? -
Why am I getting No module named 'django.utils.lru_cache' error?
I am working a Django project. I have created a form and tried to use Crispy-forms to style the form. However, when I runserver I get the following error. File "D:\Django_Project\venv\lib\site-packages\django\template\backends\django.py", line 131, in get_package_libraries raise InvalidTemplateLibrary(django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to 'crispy_forms.templatetags.crispy_forms_field': No module named 'django.utils.lru_cache' This is the template where I am using crispy-forms {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form |crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %}``` I am using Django==4.0.6 Crispy-form==1.14.0 Have searched online for possible fix unsuccessfully. Please I need help. -
How to upload file from request to google drive using django
I made a web with django, where when I upload a file with a form, the file will be uploaded to google drive. The question is how do I get the file that I got from request.FILE['file'] to upload to google drive? this my code user = request.user.social_auth.get(provider='google-oauth2') tfile = request.FILES['file'] drive = build('drive', 'v3', credentials=Credentials(user)) media_metadata = { 'name': tfile, 'parents': [folder.objects.filter(user__username=user)[0].id_folder] } media = MediaFileUpload(tfile, mimetype='image/jpeg') upfile = drive.files().create(body=media_metadata, media_body=media, fields='id').execute() -
Django - Can't import other app's model from same directory
I've got a problem with importing model from another app for Foreign key. I tried two ways to use field from other model: Import it as a string, it doesn't provide any errors before migrating model: from_city = models.ForeignKey('cities.City', blank=True, null=True, related_name='from_city_set', on_delete=models.CASCADE) It provides an error when i'm trying to use "makekigrations" or "migrate" command Import it as python object, but there is a strange moment. It tries to import 'city' app from src folder like that: from src.cities.models import City from_city = models.ForeignKey(City, blank=True, null=True, related_name='from_city_set', on_delete=models.CASCADE ) Both variants provides the same traceback: Traceback (most recent call last): File "C:\TrainProject\src\manage.py", line 22, in <module> main() File "C:\TrainProject\src\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\TrainProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\TrainProject\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\TrainProject\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 196, in handle loader.project_state(), File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\loader.py", line 361, in project_state return self.graph.make_state( File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\graph.py", line 329, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\operations\models.py", line 724, in state_forwards state.alter_model_options( File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\state.py", line … -
Django Unit Tests - Changes to self properties are persisting from test to test
I have a test class that has a setup like this. We import a dictionary from a test_helpers file that has some default data. The data is set as FORM_DATA['value_A'] = 0 and FORM_DATA['value_B'] = 1000000 from the start. Whether I set FORM_DATA to a self.form_data value, or assign it to a variable in each test, doesn't matter. The 2nd test seems to persist the dictionary changes from the 1st test, which is not ideal for testing. I added a bunch of print debug statements to show what is happening. Even in the setUp() for the 2nd test, it shows the values from the previous test! What is happening here? Why can't the dictionary self.form_data be the default imported data every time I have a new test? from test_helpers import FORM_DATA class TestBaselineScenarios(TestCase): @classmethod def setUpClass(cls): super(TestBaselineScenarios, cls).setUpClass() long_running_data_setup() def setUp(self): self.form_data = FORM_DATA print("setUp", self.form_data['value_A'], self.form_data['value_B']) def test_one(self): print("1") print(self.form_data['value_A'], self.form_data['value_B']) self.form_data['value_A'] = 25000 self.form_data['value_B'] = 700000 print("2") print(self.form_data['value_A'], self.form_data['value_B']) simulation = test_helpers.create_simulation(form_data=self.form_data) simulation.run() self.assertEqual(0.8416667, round(simulation.success_rate(), 7)) def test_two(self): print("3") print(self.form_data['value_A'], self.form_data['value_B']) self.form_data['value_A'] = 10000 print("4") print(self.form_data['value_A'], self.form_data['value_B']) simulation = test_helpers.create_simulation(form_data=self.form_data) simulation.run() self.assertEqual(0.9916667, round(simulation.success_rate(), 7)) setUp 0 1000000 1 0 1000000 2 25000 700000 setUp 25000 700000 3 25000 … -
How to deploy Django 3 and Vue JS 3 website on AWS? [closed]
I am trying to deploy my app which has Django as the backend and Vue JS CLI as the frontend on AWS. It is using Django REST framework to send and receive data. I was able to deploy the Django app on AWS using Elastic Beanstalk but now how do I deploy the Vue JS app and how do I connect the two in the same way that they do locally. I am new to deployment so any help will be appreciated. -
get the incorrect data from serializer.data
i want to get the data (amount) from serializer but the serializer get back the none. but when i get the date from the request data i get the correct data.can someone help to solve this issue?? this is the response body of serializer data and request data. got the {'amount': 1000000} the request body and the {'amount': None} from serialized data: System check identified no issues (0 silenced). August 23, 2022 - 16:19:21 Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. {'amount': 1000000} {'amount': None} Internal Server Error: /api/zarinpal/request/ Traceback (most recent this is the function get the request @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def request_to_pay(request): data = request.data print(data) serializer = RequestToPaySerializer(data=data) serializer.is_valid(raise_exception=True) print(serializer.data) and this is the serializer class: class RequestToPaySerializer(serializers.Serializer): amount = serializers.DecimalField(max_digits=20, decimal_places=3) description = serializers.CharField(required=False)