Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running test together fails, running test alone succeeds
I'm using pytest. Going through the tests with a debugger, running both test_joining_previously_entered_queue_returns_previous_queue_details and test_joining_queue_enters_correct_position together, test_joining_previously_entered_queue_returns_previous_queue_details succeeds but test_joining_queue_enters_correct_position fails at queue = get_object_or_404(Queue, pk=kwargs["pk"]) in the JoinQueue view, where the view throws a 404 If I run test_joining_previously_entered_queue_returns_previous_queue_details individually, then the test will pass no problem. What should happen is that create_company_one creates a Company object, which in turn creates a Queue object (shown in the overridden save method of Company). The associated Queue object does not seem to be created if test_joining_queue_enters_correct_position is run with the other test, but works if the test is run standalone Why does this happen and how can I fix it? test_join_queue.py def create_company_one(): return Company.objects.create(name='kfc') @pytest.mark.django_db def test_joining_previously_entered_queue_returns_previous_queue_details(authenticated_client: APIClient): create_company_one() url = reverse('user-queue-join', args=[1]) first_response = authenticated_client.put(url) first_data = first_response.data second_response = authenticated_client.put(url) second_data = second_response.data assert first_data == second_data @pytest.mark.django_db def test_joining_queue_enters_correct_position(factory: APIRequestFactory): """ Makes sure that whenever a user joins a queue, their position is sorted correctly based on WHEN they joined. Since all users in self.users join the queue in a time canonical manner, we can iterate over them to test for their queue positions. """ create_company_one() users = create_users() view = JoinQueue.as_view() url = reverse('user-queue-join',args=[1]) request = … -
In django, can I prevent attacker from re-using a session from one domain to gain access to another domain?
I have a django project serving two different purposes. On one subdomain, let's call it public.example.com, I allow unprivileged users to access a portal to edit their profile and settings. On another domain, private.example.com, I give the user access to some management functions. I have the default django session cookie settings, so when I log in to public.example.com and then try accessing private.example.com, I get redirected to a login page. This is normal and expected because the browser will not send the session cookie to any domain other than public.example.com. If I copy the session cookie that is sent to public.example.com and tamper with the request made to private.example.com so that I send the public cookie to the private domain, django responds with a 200 OK answer and renders the page as if I am a user that has logged in to that domain. I can not find any documentation that tells me that sessions are limited to the domains that they originated from, other than the default browser behaviour of limiting cookies to their respective domains. Is it possible to prevent such unwanted access without serving the project on two different instances with two different databases? -
Slow dropdown menu for foriegn key
I have created a backend website and is in production. It is using jawsdb and one of my models have 15000 records. The problem is when I click on the dropdown list of another model in admin panel it to select a model, it takes too much time for the list to appear and the search bar on the dropdown list hangs as well while writing. Is it because of cheap heroku plans and jawsdb. I could nt have messed up in the code. -
Error Heroku , desc="No web processes running" method=GET path="/favicon.ico"?
2023-01-24T12:48:09.490016+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=pizza.herokuapp.com request_id=cb7658a6-061a-4ae1-8e3c-f07247d956fc fwd="78.141.167.114" dyno= connect= service= status=5 03 bytes= protocol=https 2023-01-24T12:48:10.638376+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=pizza.herokuapp.com request_id=0a379b0d-021f-4dc8-967b-b897ff678596 fwd="78.141.167.114" dyno= connect= servic e= status=503 bytes= protocol=https I don't understand this error, what it means by the /favicon.ico being unable to have the get method? -
Why i am getting "error": "user_not_found" whenever i call "users.profile.get" slack API?
So, I created the slack bot and it was working completely fine but, When I distributed the slack bot app to another workspace I started facing the "user not found" error on API call of "users_profile_get" as I have also cross-checked the required scopes for this API, user_id, and access token and they are completely fine but still API call returns user not found. I need your help guys on it as I am missing something while distributing the app or Is there any other problem? There is also One strange thing that I can call "chat.postMessage" API of slack and it runs successfully. result = app.client.users_profile_get(user=slack_id) While calling this API, I am getting error : { "ok": false, "error": "user_not_found" } -
Additional DRF serializer field with search request only
I'm working with postgis and geodjango and i have a Store model as follow: from django.contrib.gis.db import models . . class Store(models.Model): . . . # Storing the exact location of the store with (longtitude, latitude) geo_location = models.PointField(null=True, blank=True, srid=4326) . . . and the serializer: from rest_framework import serializers from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import Store class StoreSerializer(GeoFeatureModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') # This field is generated only when there is a near by store filter distance = serializers.DecimalField(source="dist.m", max_digits=10, read_only=True, decimal_places=2) class Meta: model = Store geo_field = "geo_location" fields = '__all__' The view: from rest_framework import generics from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated from rest_framework_gis.pagination import GeoJsonPagination from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.db.models.functions import Distance from rest_framework_gis.filters import DistanceToPointFilter, DistanceToPointOrderingFilter from .serializers import StoreSerializer from .models import Store from .permissions import IsOwnerOrReadOnly class StoreListView(generics.ListCreateAPIView): def get_queryset(self): queryset = Store.objects.all() # If there are user coordinates in the query params point = self.request.query_params.get('point', None) if point : # in case of white space after the simicolon in lat, lng ex: (point='12.2123, 5.21354') coordinates = [crd.strip() for crd in point.split(',')] user_point = GEOSGeometry('POINT('+ coordinates[0]+ ' ' + coordinates[1]+ ')', srid=4326) queryset = queryset.annotate(dist=Distance('geo_location', user_point)).order_by('dist') return queryset queryset = Store.objects.all() … -
How to print a form in PHP or django to already structured pdf?
all right? I have a doubt about how I can make a form in php or django in which the client completes it, then it is sent to the server and when I refresh the page, the pdf document will appear for printing. In this case, the pdf will already have a ready-made structure with gaps, these gaps will be filled in with the customer's information. I just need to fill out this form and print it later, if it is not necessary to save it on the server, no problem. -
Copy data from guest user Account and delete the guest user and send data to logged in or registered user with pure django
I'm currently working on an e-commerce website and the customer can order without logging in, but what I'm looking for is that after the customer add product to the cart, when they decide to Checkout must login or register. What I want is for the guest user account to be deleted and the card data to be transferred to the logged in or registered user account. ` """ My custom user manager """ class Account(AbstractBaseUser): phone_number = models.CharField(unique=True, max_length=11, validators=[MinLengthValidator(11)], blank=True) session_key = models.CharField(max_length=40, null=True, blank=True) USERNAME_FIELD = 'phone_number'` `class OrderSummaryView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'shop/ordersummary.html', context) except: """ **here i can create Guest user account with session_key** """ session_key = self.request.COOKIES['sessionid'] customer, created = Account.objects.get_or_create(session_key=session_key) order = Order.objects.get(user=customer, ordered=False) context = { 'object': order } return render(self.request, 'shop/ordersummary.html', context)` `def CheckoutView1(request): """ **Here when the guest user wants to checkout, he/she has to login or register And when they log in I want to remove the guest account and send the data to the logged in or registered account.** """ if not request.user.is_authenticated: return redirect("login") context = {} if request.POST: form = CheckOutUpdateForm(request.POST, instance=request.user) if form.is_valid(): … -
JWT authentication module not being recognized in django rest api even after being installed
I'm implementing JWT authentication in my API made from Django. I installed the recommended package (rest_framework_jwt) and added it to the required files according to the documentation. However, upon running the server, I'm getting the following error:- Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/local/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework_simplejwt' Here is my settings.py file:- import … -
Send scheduled message everyday to all users using the slack bot
I am creating a slack bot project using Django. Here I would like to send a scheduled message to every user of the workspace. Every day, the bot will ask specific questions to all users, but personally. In that case, how can I post questions every day within a specific schedule? Which tool or django-package will be appropriate to fulfill my problem? -
Django image dosen't show when searching?
I have an inventory app with products and its name, photo. I query the records in HTML page and all works fine and the images showing. when i try to search the result come without the photo. View: def inventory_search_view(request): query = request.GET.get('q') product_search = Inventory.objects.filter(name__icontains = query).values() print(product_search) context = {'object_list': product_search} return render(request, 'inventory_search.html', context = context) HTML: <div class="product-image"> <img src="{{object.image}}" alt="{{object.name}}" /> <div class="info"> <h2> Description</h2> <ul> {{object.description}} </ul> </div> </div> </div> search form: <form action="search/"> <input type="text" name="q"> <input type="submit" value="Search"> </form> Thanks in advance. -
Django - How to get object on another app model without direct relationship in the parent model?
I have a Profile model, Award model as child of the Profile model [which takes other award details like achievement detail], and a List_of_awards model as child of the Award model [which takes list of awards and a count of how may profiles has the specific award]. Award model is inline with the Profile model using Foreignkey and List_of_awards model as Foreignkey field in the Award model for the choices of awards. What I am trying to do is, display the List_of_awards in the Profile model. The idea originated when I was able to display the List_of_awards in the list_display of the Award model', so, I was trying to link List_of_awardsin theProfile` which has no direct relationship. class Profile(models.Model): first_name = models.CharField(verbose_name=_('First Name'), max_length=255, null=True, blank=True, ) middle_name = models.CharField(verbose_name=_('Middle Name'), max_length=255, null=True, blank=True) last_name = models.CharField(verbose_name=_('Last Name'), max_length=255, null=True, blank=True) .... class Award(models.Model): list_of_award = models.ForeignKey('system_settings.Ribbon', related_name='awards_ad_ribbon', on_delete=models.DO_NOTHING, verbose_name=_('Type of Award'), blank=True, null=True) achievement = models.TextField(verbose_name=_('Achievement')) profile = models.ForeignKey('reservist_profile.Profile', related_name='awards_ad_profile', verbose_name=_('Profile'), on_delete=models.DO_NOTHING, blank=True, null=True) def image_tag(self): from django.utils.html import format_html return format_html('<img src="/static/media/%s" title="" width="75" /> %s' % (self.list_of_award.image,self.list_of_award.award)) image_tag.short_description = 'Award' class Ribbon(models.Model): award = models.CharField(verbose_name=_('Award'), max_length=255, null=True, blank=True) award_desc = models.TextField(verbose_name=_('Description'), max_length=255, null=True, blank=True) image = models.ImageField(verbose_name … -
How to get selected attributes as a serialized representation in DRF?
When I serialize data using this statement: serializer = serializers.MySerializer(members, many=True) return Response(serializer.data) It will return a list of serialized data as a response. But if I want to print only some attributes as a serialized representation,not all attributes, how to do that? -
why do I get such an error? if on ubuntu/apache in the OpenSSH client all this works
module 'clr' has no attribute 'AddReference' Traceback (most recent call last): File "/home/djangoexample4/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/djangoexample4/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/djangoexample4/mainapp/views.py", line 135, in index clr.AddReference('/home/djangoexample4/btclinux2/MyLibraryName/bin/Debug/net7.0/ubuntu.22.04-x64/MyLibraryName.dll') Exception Type: AttributeError at / Exception Value: module 'clr' has no attribute 'AddReference' in openSSH client all work it: monop -r /home/djangoexample4/btclinux2/MyLibraryName/bin/Debug/net7.0/ubuntu.22.04-x64/MyLibraryName.dll Assembly Information: MyLibraryName Version=1.0.0.0 Culture=neutral PublicKeyToken=null MyLibraryName.Class1 Total: 1 types. namespace MyLibraryName{ public class Class1 { public int method1() { return 777; } } } python3 >>>import clr >>>clr.AddReference('/home/djangoexample4/btclinux2/MyLibraryName/bin/Debug/net7.0/ubuntu.22.04-x64/MyLibraryName.dll') >>>from MyLibraryName import Class1 >>>variable = Class1().method1() >>>print (variable) 777 in openSSH client all work it: in django website no: pip uninstall clr pip uninstall pythonnet pip install pythonnet module 'clr' has no attribute 'AddReference' -
Data is shown before form submission in Django 4.1
community! My goal is to create an app, which takes some user input, does machine-learning stuff and shows the results. I want to know whether the result was correct for each prediction. That's why I'm trying to implement a feedback system, where a user could mark the answer as "correct" or "incorrect" if one wants to do so. To be exact, I have two buttons: "the prediction looks like true" and "the prediction was incorrect". After clicking on one of these buttons I have a pop-up dialog shown with 3 checkboxes, where a user can provide additional information (it is not required). forms.py with these checkboxes looks like this: from django import forms class checkboxForm(forms.Form): is_winner_reason_true = forms.BooleanField(required=False, label="The first place in importance coincides with reality", label_suffix='') is_top5_reason_true = forms.BooleanField(required=False, label="Top 5 includes friends with high importance", label_suffix='') is_other_reason_true = forms.BooleanField(required=False, label="Other", label_suffix='') class checkboxFormFalsePred(forms.Form): is_winner_reason_false = forms.BooleanField(required=False, label="The other person should come first in importance", label_suffix='') is_top5_reason_false = forms.BooleanField(required=False, label="Top 5 includes friends with low importance", label_suffix='') is_other_reason_false = forms.BooleanField(required=False, label="Other", label_suffix='') I want to get data from clicking on one of two buttons (the value will be either True or False) and then, if a user decided to … -
Generic detail view UserRegister must be called with either an object pk or a slug in the URLconf
I'm getting this error when trying to register to my to-do list web Generic detail view UserRegister must be called with either an object pk or a slug in the URLconf. views.py class UserRegister(CreateView): model = User form_class = UserRegisterForm template_name = 'users/form_register.html' redirect_authenticated_user = True success_url = reverse_lazy('tasks') # Forbid logged in user to enter register page def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('tasks') return super(UserRegister, self).get(*args, **kwargs) # Send email verification def post(self, request, *args, **kwargs): self.object = self.get_object() form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your account' message = render_to_string('users/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('login') else: return self.form_invalid(form) urls.py urlpatterns = [ path('register/', UserRegister.as_view(), name='register'), path('login/', UserLogin.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('activate/<uidb64>/<token>/', ActivateAccount.as_view(), name='activate'), ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Maybe it got something to do with the models.py? But to be honest I don't really know what else to put there. Keep in mind I have two apps, the user app for registration and login and whatnot, and the tasks app for displaying tasks, creating, deleting task, etc. -
How to reuse properties from table with django?
oke. I have one table. like: class AnimalGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to="photos/groups") class Meta: verbose_name = "animalgroup" verbose_name_plural = "animalgroups" def __str__(self): return self.group_name And this are animal groups. Like: mammals fish reptils But then I hava a subgroup where a user can enter the same properties as by AnimalGroup. And the AnimalGroup can have multiple subgroups. Like: mammals: cats, dogs, cattles. And then you have the animal it self: cats: siamese cat, ragdoll, etc. My question is: how can I resuse this properties for the three objects? So AnimalGroup subgroup animal So that a user can enter in the admin panel of django: mammals fish reptils and then can enter cats and choose from dropdown mammals. Because all the objects: AnimalGroup subgroup animal have in common the fields: name description images -
can solve this error ? ( NoReverseMatch )
I'm ratherly amatour in django and cant solve this problem, error: NoReverseMatch at /blog/ Reverse for 'single' with keyword arguments '{'pid': ''}' not found. 1 pattern(s) tried: \['blog/(?P\<pid\>\[0-9\]+)\\Z'\] urls.py : from django.urls import path from blog.views import \* from django.conf.urls.static import static app_name= 'blog' urlpatterns = \[ path('',home,name='home'), path('\<int:pid\>',single, name='single'), \] views.py : from django.shortcuts import render from blog.models import Post import datetime def single(request,pid): single_post= Post.objects.filter(pk=pid) def counting_single_views(n): n.counted_views += 1 n.save() counting_single_views(single_post) context = {'single_post':single_post} return render(request,'blog/blog-single.html',context) def home(request): now = datetime.datetime.now() posts= Post.objects.filter(published_date__lte= now) context={'posts':posts} return render(request,'blog/blog-home.html',context) blog-home.html : {% for post in posts %} \<a href="{% url 'blog:single' pid=post.pk %}"\>\<h3\>{{post.title}}\</h3\>\</a\> \<p class="excert"\> {{post.content}} \</p\> {% endfor %} i tried with id instead of pk , but no differ, -
Django Variations not displayed
In order to list my variations_value i render data into context but when i pass the object to the frontend it's recognised as a queryset but i can't use data from it Model variation_category_choice = ( ('color', 'color',), ('size', 'size',), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=100, choices=variation_category_choice) variation_value = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now=True) def __unicode__(self): return self.product View def product_detail(request, category_slug, product_slug): try: single_product = Product.objects.get(category__slug=category_slug, slug=product_slug) in_cart = CartItem.objects.filter(cart__cart_id=_cart_id(request), product=single_product).exists() variations = Variation.objects.filter(product=single_product) except Exception as e: raise e context = { 'single_product': single_product, 'in_cart': in_cart, 'variations': variations } return render(request, 'store/product_detail.html', context) HTML <h1>{{variations.variation_value}}</h1> -
How can I make the selection value in the model form Django based on the value selected above?
Good day! I have a model table in order to add data to this model. [Citizen_2] At me in the field the country is selected by the user. The form then records the city based on the selected country value. You need to save them in the [Citizen_2] table model so that the city corresponds to its country in the corresponding fields. I've been thinking about how to do this for a week now. I would be very grateful for any hints. I would like users to enter their country of residence first, it's like a simple one-field form. And then a form of two fields - where it is proposed to select the country of residence from the value already entered in the (name_country) field. For example, I have users added three countries there. Then they add the cities - for those respective countries. In the drop-down form field, select a country and write down your city there. And send the data to the model table. It is necessary that the data be saved in such a way that the city corresponds to the country to which the user wrote it down in the form. This is then used … -
Django & postgress sometime result into empty resultset
I have a table name finance_details. When I query using invoice_id_id = value and is_paid = False. Data exist in table but resultset is empty. Below code finance_details = FinanceIORDetails.objects.filter(invoice_id=sample_string, is_paid=False).first() if not finance_details: Can anyone pls help as this is happening on production. Data exists in table but resultset is empty -
How to add a checkbox column in your Django template
I have a Django application, I want to show pandas dataframe in my template, so I parse it using df.to_html() and pass it in the render, and show it in my template using <table>{{data|safe}}</table>, my data is displayed as I expect, but I want some modification, I want an extra column in my data frame, each cell in that column will have a checkbox, user can check/uncheck it. I want to get information that which cells are checked so I display some more information about those rows. What I have: What I want: -
How to parse request.body for multipart file in django
I have used below code to post data to url public void updateLogo(String clientKey, MultipartFile file) { MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("file", file.getResource()); Settings prevData = repo.findFirstByClientKey(clientKey); WebClient webClient = WebClient.builder().baseUrl("http://localhost/") .defaultHeader(HttpHeaders.AUTHORIZATION, String.format("Token %s", userToken)).build(); Mono<SettingsLogo> resObj = webClient.post().uri("api/upload-logo") .contentType(MediaType.MULTIPART_FORM_DATA).body(BodyInserters.fromMultipartData(builder.build())) .retrieve().bodyToMono(SettingsLogo.class) .onErrorResume(WebClientResponseException.class, ex -> { logger.error("Exception", ex); return Mono.empty(); }); } On Django post function class UpdateJiraAppLogo(APIView): def post(self, request, *args, **kwargs): print('POST', request.POST) print('BODY', request.body) print('FILES', request.FILES) logo = request.body now = timezone.now() logo_name = "logo_" + str(now.strftime('%d_%m_%Y') + "_" + now.strftime('%H%M%S')) + ".png" try: with open("media/logos/" + logo_name, "wb+") as f: f.write(logo) f.close() except Exception as e: print(e) Following is printed POST <QueryDict: {}> BODY b'--3oqd3VUazPhxbazUKCTiNsp2MeoS9RgQqbQLnj7X\r\nContent-Disposition: form-data; name="file"; filename="clock.png"\r\nContent-Type: image/png\r\nContent-Length: 1959\r\n\r\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00x\x00\x00\x00x\x08\x03\x00\x00\x00\x0e\xba\xc6\xe0\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00u0\x00\x00\xea`\x00\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x01\xefPLTE\x00\x00\x00\xe399\xde11\xde33\xdc33\xdd44\xdd33\xdd33\xdd33\xdd33\xdd33\xde44\xdf@@\xff\x00\x00\xdb55\xdc33\xdd33\xdd33\xdd33\xdd44\xde44\xdb11\xde77\xdc22\xde44\xdd33\xdd22\xde22\xdc..\xdb$$\xde22\xdd33\xdd33\xdd33\xdd22\xdc44\xe633\xdf33\xdc33\xdd33\xde44\xdd55\xdd33\xdd33\xdd33\xdd55\xdc33\xde33\xdc44\xdd33\xdb11\xe399\xde33\xdd33\xdc22\xdb11\xdd33\xdd33\xff\x00\x00\xde11\xdd22\xdd33\xdd33\xdd33\xdd33\xde44\xbf@@\xdd44\xd5++\xdc55\xdd33\xdb77\xe022\xdd33\xdc33\xdd33\xde44\xdd33\xdd44\xdd33\xdd33\xdc44\xdd33\xdd33\xdd33\xde33\xdd33\xcc33\\x00\x00\x00%tEXtdate:create\x002019-06-02T16:58:33+00:00.c\xfc\x1c\x00\x00\x00%tEXtdate:modify\x002019-06-02T16:58:33+00:00_>D\xa0\x00\x00\x00\x00IEND\xaeB`\x82\r\n--3oqd3VUazPhxbazUKCTiNsp2MeoS9RgQqbQLnj7X--\r\n' FILES <MultiValueDict: {}> the file is saved but it is corrupted. How to save file when file is received in request.body rather than FILES or POST? -
django.db.utils.IntegrityError: and django.db.utils.OperationalError:
raise integrityerror( django.db.utils.integrityerror: the row in table 'hazeapp_orderitem' with primary key '1' has an invalid foreign key: hazeapp_orderitem.product_id contains a value '5' that does not have a corresponding value in hazeapp_newarrival.id.enter image description here I am trying to build 2 different models that include different product with their prices, name etc and render those two model products in two different template using for loop. But while creating an OrderItem model which includes both above foreign model leads to integrity error mostly. The code i tried was: class NewArrival(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=200, null=False, blank=True) price = models.FloatField(default=0) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): collection = models.ForeignKey(Collection, on_delete=models.SET_NULL, blank=True, null=True) newarrival = models.ForeignKey(NewArrival, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = 0 if self.collection: total += self.collection.price * self.quantity if self.newarrival: total += self.newarrival.price * self.quantity return total -
get foreign key related data in django using filter
This is the model : class Requirement(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey( User,on_delete=models.CASCADE, related_name = 'user' ) assigned_user = models.ForeignKey( User,related_name = "assigned",on_delete=models.CASCADE, ) I am running this query: requirementsOb = Requirement.objects.filter(user = currentUser) Where currentUser is logged in user. The result returns multiple requriements. I also want to get all user related data. How can i get user related data?