Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data from amoCRM through API?
I am trying to get data through API from amoCRM system but I am having some problems and I am really tired. The url: https://alamiri.amocrm.ru/api/v4/contacts This API should return contacts of users that contain (first name, email, number, ...). When I copy and paste the above link in the browser, I get the data and everything works fine but when I try to get that data in Python it returns the following: {'detail': 'Invalid user name or password', 'status': 401, 'title': 'Unauthorized', 'type': 'https://httpstatus.es/401' } my code in python (Django framework): import requests import pprint def get_contacts(): url = "https://alamiri.amocrm.com/api/v4/contacts" api_key = "def50200c1f820b24e23a1a776cec978ed0e3eb3c479b83b91bef4158728d" client_uuid = "e1899afa-85a8-45ca-93f9-7f4b26374a5d" client_secret = "jUlw4E6H4jIW39GXXjpLjratAwOEiaqPr3KDBKYwc9ZQLXK2UlhMcsuu" headers = { 'login': login, 'client_uuid': client_uuid, 'client_id': client_uuid, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'Authorization': f'Bearer {api_key}', } response = requests.get(url, headers=headers) pprint.pprint(response.json()) get_contacts() I am reading their documentation (amoCRM) and I tried a lot of things but none worked! 😥 https://www.amocrm.com/developers/content/platform/abilities/ I followed their instructions how to work with their API: https://nova-amocrm.notion.site/894277ffef5940e7a5daadd2abc746c8 But I am stuck and I don't know how to solve this problem! Any help please? If you don't know what is amoCRM, then -
Show ValidationError in the template - Django
I am developing a program that consists of sales. I want that when registering a sale, if there is not enough stock of the requested product, an error will appear indicating that there is no stock. I was able to do it but I get the ValidationError like this: ValidationError at /ventas/create/ ['No hay suficiente stock del producto.'] forms.py: class VentasForm(forms.ModelForm): """Formulario modelo de ventas.""" class Meta: """Meta class.""" model = Venta fields = ('fecha', 'cliente', 'producto', 'cantidad', 'forma_pago') def save(self): """Restar stock.""" data = super().clean() producto = Product.objects.get(id=data['producto'].pk) verificar_stock = producto.cantidad - float(data['cantidad']) if verificar_stock >= 0: producto.cantidad -= float(self.data['cantidad']) else: raise forms.ValidationError('No hay suficiente stock del producto.') producto.save() views.py: class CreateVentasView(CreateView): """Registrar venta.""" template_name = 'ventas/create.html' form_class = VentasForm success_url = reverse_lazy('ventas:list') context_object_name = 'venta' and in the template: {{ form.as_p }} -
Django Crispy Form loop through {% crispy %} object
I'm trying to use crispy form fields within each table's column. I can render it using: {% load crispy_forms_tags %} <tr> <form method="get" class="form-inline justify-content-center"> {% for field in filter.form %} <th>{{ field|as_crispy_field }}</th> {% endfor %} <input class='hidden-submit' type="submit"/> </form> </tr> And it looks like this which is what I want: But the problem is my Layout() which I'm using to add extra parameters such has placeholders etc to the form is not working because I'm using |as_crispy_field tag to render individual fields. Here is my form component: class CustomFiltersForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_tag = False self.helper.layout = Layout( ) for field_name, field in self.fields.items(): self.helper.layout.append(Field(field_name, placeholder="Search " + field.label)) Is there a way to loop through {% crispy filter.form %} or an alternative way to populate individual fields using cripsy forms? Something like: {% for field in {% crispy filter.form%} %} ... {% endfor %} -
Condition whether field A or B is required in Django Rest Framework
I have a serializer in which I would like to give the opportunity to send a NEW address with a POST request OR give an ID of an already existing address. One of both is required, but right now it asks for both to be given. Any possibility to achieve that it validates with a condition? class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order #fields = '__all__' exclude = ['in_calculation','canceled',] address = AdressSerializer() addressid = serializers.CharField(source='address') read_only_fields = ['id','user','status','costs',''] -
When are Django Querysets executed in the view?
I read the Querysets Django docs regarding querysets being lazy, but still am a bit confused here. So in my view, I set a queryset to a variable like so players = Players.objects.filter(team=team) Later on, I have a sorting mechanism that I can apply sort = '-player_last_name' if pts > 20: players = players.filter(pts__gte = pts).order_by(sort) else: players = players.filter(pts__lte = pts).order_by(sort) if ast < 5: players = players.filter(asts__lte = ast).order_by(sort) else: players = players.filter(asts__gte = ast).order_by(sort) context = {players: players) return render(request, '2021-2022/allstars.html', context) What I want to know is, when is the players queryset evaluated? is it when each page is rendered, or everytime I assign the queryset to a variable? Because if it's the former, then I can just apply the .order_by(sort) chain and the previous applications are redundant. -
What is the best way to learn Django?
What is the best way to learn Django? -
Saving values to django model through a for loop
I want to use a dictionary to store values in a model through a modelform and a view. Today I solve it like this: form.variable_1 = dictionary['variable_1'] form.variable_2 = dictionary['variable_2'] form.variable_3 = dictionary['variable_3'] form.variable_4 = dictionary['variable_4'] form.variable_5 = dictionary['variable_5'] form.variable_6 = dictionary['variable_6'] The keys in the dictionary are identical to the field names for the values I want to store. I would like to make the function a bit more pythonic - something like this: for field in form: form.field = dictionary['field'] However, I'm not sure how to use the Django ORM to achieve this. The fields I want to iterate are numbered 3-28 in the list of fields, so I guess I would have to slice the fields somehow and create a list based on that? -
foreach in javascript menutoggle should be active in the icon I clicked in only
I hope you are doing well, I am using django, problem is I have a list of items that contains a menuToggle my code is like this <!--here is code .... --> <div class="container"> {% ifequal request.user.username obj.author.user.username %} <div class="action1"> <div class="icon" onclick="menuToggle1();"> <img src="{% static 'images/ore.svg'%}" class="svg"> </div> <div class="menupost" id="menupost"> <ul> <li><i class="fa fa-refresh" aria-hidden="true" style="margin-right:10px;"></i><a href="{% url ''%}">Update</a></li> <li><i class="fa fa-trash-o" aria-hidden="true" style="margin-right:10px;"></i><a href="{% url ''%}">Delete</a></li> </ul> </div> </div> <h2 id="title" class="title">{{obj.title}}</h2> <!--and so on...--> </div> <script> function menuToggle1(){ document.querySelectorAll('.menupost').forEach(function(element) { element.classList.toggle('active'); }); }; </script> so when I click on one of them , I see all the menu of all items. so I don't want to see all menutoggle when I click on just one of them.I think you understand my question, I hope you guys can help me. -
problem getting filterset data originating from a MultipleChoiceFilter
Let's say I have the following FilterSet: class ReportFilter(django_filters.FilterSet): type = django_filters.MultipleChoiceFilter(field_name="type", lookup_expr='exact') ... and Client submits the following request: www.exmaple.com/reports/?type=1&type=2 I want to be able to get the filterset data from the multiple choice filter as a list, i.e. do something like this: class ReportFilter(django_filters.FilterSet): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) types = self.data["type"] I would expect types to give me a list [1, 2] but instead I am getting a string 2. The strange this is that if I print self.data of the filterset, it displays what I am expecting to see <QueryDict: {'type': ['1', '2']}> Any thoughts about what I am doing wrong here? -
Django Models - How to tell if an entry is being updated vs a new entry being inserted?
For one of my models I am using, there is some conditional logic that occurs, and part of what I need to know is if an entry is being made for the first time, or if it's updating an existing model. My Model is below, I will follow it with an example of what I am needing. Shipment Model class Shipment(models.Model): CARRIER_CHOICES = [ ('GW', 'Greatwide'), ('SM', 'Sample'), ] dateTendered = models.DateField(default=date.today) loadNumber = models.CharField(max_length=50) masterBolNumber = models.CharField(max_length=50) carrier = models.CharField(max_length=100, blank=True, choices=CARRIER_CHOICES, default='GW') destinationCity = models.CharField(max_length=70) destinationState = models.CharField(max_length=50) rateLineHaul = models.DecimalField(max_digits=15, decimal_places=2) rateFSC = models.DecimalField(max_digits=15, decimal_places=2) rateExtras = models.DecimalField(max_digits=15, decimal_places=2, default=0.00) rateTotal = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True, default=0.00) loadDelivered = models.BooleanField(default=False) customCarrierRate = models.BooleanField(default=False) deliveryDate = models.DateField(null=True, blank=True) deliveryTime = models.TimeField(null=True, blank=True) driverName = models.CharField(max_length=70, null=True, blank=True) driverCell = models.CharField(max_length=70, null=True, blank=True) rateTotalCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0) shipmentMargin = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) shipmentMarginPercentage = models.DecimalField(max_digits=15, decimal_places=3, null=True, blank=True) trailer = models.ForeignKey(Trailer, on_delete=models.PROTECT, blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Here are some examples of why I need to differentiate between an update or an insert. Possible Scenarios When Adding a Shipment a. Only required fields are entered. Then the following happens 1a. Calculate rateTotal 1b. … -
Django: Import data from uploaded excel file
I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is where I've managed to arrive by myself: my file is uploaded without problems and I can pass the information from the file to the variable first_row and second row. My problem now is how I can save the information in the database. My views code: VIEWS @login_required def file_upload(request): data = None if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) data_form = DatasetForm(request.POST, request.FILES) raw_file= request.FILES if file_form.is_valid() or data_form.is_valid(): data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") first_row = data.iloc[[0]] second_row = data.iloc[[1]] file_form.instance.user = request.user.profile file_form.instance.filename = raw_file['file_upload'].name file_form.save() return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': data, 'second_row': second_row, 'file_form': file_form, 'message': message, } return render(request, 'upload_file.html', context) These are how my data and models looks: DATA code tot sd name_1 aa 3 1 name_2 bb 7 2 MODEL class File(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) filename = models.CharField(max_length=250) file_upload = models.FileField(upload_to=path) upload_date = models.DateField(default=datetime.now) def __str__(self): return self.user.name + 'file' class Dataset(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE) name_user_A = models.CharField(max_length=250) code_user_A = models.PositiveIntegerField(null=True) total_user_A = models.PositiveIntegerField(null=True) sd_user_A = models.PositiveIntegerField(null=True) … -
Django custom authentication class is not reading AllowAny
Here is the REST authentication class: def get_authorization_header(request): raw_token = request.COOKIES.get('auth_token', ) or None auth = request.META.get('HTTP_AUTHORIZATION', ) if isinstance(auth, str): auth = auth.encode(HTTP_HEADER_ENCODING) return auth class JWTAuthentication(BaseAuthentication): keyword = 'auth_token' def authenticate(self, request): raw_token = request.COOKIES.get('auth_token', ) or None if raw_token is None: return None return self.authenticate_credentials(raw_token) def authenticate_credentials(self, key): try: user_model = get_user_model() payload = jwt.decode(key, settings.SECRET_KEY, algorithms="HS256") user = user_model.objects.get(email=payload['email']) except (jwt.DecodeError, user_model.DoesNotExist): raise exceptions.ParseError('Invalid token') except jwt.ExpiredSignatureError: raise exceptions.ParseError('Token has expired') if not user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted') return (user, payload) def authenticate_header(self, request): return self.keyword And here is the view: class GoogleLogin(APIView): permission_classes = [AllowAny] def post(self, request): data = request.data response = Response() token = data.get('tokenId', None) if not token: raise exceptions.AuthenticationFailed('No credentials provided.') try: token_info = id_token.verify_oauth2_token(token, requests.Request(), google_app_id) email = token_info['email'] user = authenticate(email) if not user: serializer = RegisterSerializer(data={'email': token_info['email'], 'first_name': token_info['given_name'], 'last_name': token_info['family_name']}) serializer.is_valid(raise_exception=True) serializer.save() jwt_token = gen_token(email) response.set_cookie( key='auth_token', value=jwt_token, expires=datetime.datetime.utcnow() + datetime.timedelta(days=30), secure=False, httponly=True, samesite='Lax' ) return response except ValueError: return Response('Invalid TokenId.', status=status.HTTP_400_BAD_REQUEST) I'm trying to implement Google social login where the frontend (ReactJS) sends tokenId to the backend (Django) to verify the token then returns a response with a JWT token stored in the cookies … -
How to get user object in template?
model.py class User(AbstractUser): is_agree = models.CharField(max_length=1, blank=True) is_verify = models.CharField(max_length=1, blank=True) type = models.CharField(max_length=1, blank=True) name = models.CharField(max_length=255, blank=True) address1 = models.CharField(max_length=255, blank=True) address2 = models.CharField(max_length=255, blank=True) bank_account = models.CharField(max_length=255, blank=True) phone_number = models.CharField(max_length=255, blank=True) I want to get users type in template. I tried {{ user.type }}. but was not worked -
Django declare subquery for re-use?
Is there a way to store a subquery in django the same way SQL DELCARE works? I've got multiple calculations using subqueries. I then reference these subqueries in further calculations. Problem is, once these subqueries are referenced, they "run again" and call another huge select query unnecessarily. Is there a way to call the query once then re use? Only stipulation is that this needs to be done in a single query using annotations. -
Why we use axios PUT method when we can use POST method that does the same job
I'm using axios in a REACT / Django project, the question that I didn't find an answer to is, Considering we can update a databate table, by first sending data with POST method from react to django view then django update the database table with .update function using the data in POST method... Then why we use PUT method or DELETE method ? Thank you -
How to disable sorting by multiple columns in Django Admin?
How can I disable sorting by multiple columns in Django Admin? I'd like to simplify sorting to only one column at a time. Currently, if you click on a column header, this column is added to the sorting order. I.e. http://localhost:8000/admin/core/user/?o=-2.5.3.1, where o query parameter determines the sort (see numbers 4, 1, 3 on the attached image) -
Python Django Async Def work with objects
I have this code in my Django Channels Consumer. async def connect(self): from .models import Chat, Menu from client.models import ChannelCommunication, VirtualAgent self.agents = await sync_to_async(VirtualAgent.objects.get, thread_sensitive=True)(pk=1) self.channel = await sync_to_async(ChannelCommunication.objects.get, thread_sensitive=True)(virtual_agent=agents.pk) self.chat = Chat() self.chat.channel = self.channel self.chat.menu_nav = await sync_to_async(Menu.objects.get(id=self.agents.flow_start)) await database_sync_to_async(self.chat.save)() self.menu_nav = self.chat.menu_nav # Join room group await self.channel_layer.group_add( self.general, self.channel_name ) await self.accept() And have error bellow: 2021-11-19 14:28:35,051 ERROR Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 173, in get rel_obj = self.field.get_cached_value(instance) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'flow_start' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in call return await application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/local/lib/python3.8/site-packages/channels/sessions.py", line 263, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "/usr/local/lib/python3.8/site-packages/channels/auth.py", line 185, in call return await super().__call__(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/middleware.py", line 26, in call return await self.inner(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 150, in call return await application( File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/consumer.py", line 58, … -
Adapt Django model (with djOngo) to MongoDB document
I have full database with documents like: { "_id": { "$oid": "6191419b42a21c7b38f028ae" }, "like_count": 58142, "slug": "the-elder-scrolls-iv-oblivion", "name": "The Elder Scrolls IV: Oblivion", "description": "The Elder Scrolls IV: Oblivion", "image": { "thumb": "https://cdn.website.com/c/04dcf5be7b651ef57c542bf5634b08c2/400x510/cdn.kanobu.ru/games/e17c468f-cd9e-48d7-bb23-6cbd736fa330.JPG", "origin": "https://cdn.website.com/games/e17c468f-cd9e-48d7-bb23-6cbd736fa330.JPG" }, "release_date": { "string": "20 марта 2006", "date": "2006-03-20", "is_precise": true, "precision_class": "day" }, "created": "2009-03-02T18:48:27", "rating": 8.94065934065934, "genres": [{ "id": 3649, "name": "Экшен", "slug": "action", "position": 10 }, { "id": 3656, "name": "Ролевые", "slug": "rpg", "position": 30 }], "platforms": [{ "id": 1, "name": "PC", "slug": "pc", "position": 0 }, { "id": 59, "name": "Xbox One", "slug": "xbox-one", "position": 2 }, { "id": 4, "name": "PlayStation 3", "slug": "ps-3", "position": 4 }, { "id": 6, "name": "Xbox 360", "slug": "xbox-360", "position": 5 }], "developers": [{ "id": 79, "name": "Bethesda Softworks", "slug": "bethesda-softworks" }], "publishers": [{ "id": 43, "name": "2K Games", "slug": "2k-games" }], "requirements": { "min_os": "Windows XP, Windows 2000, Windows XP 64-разрядная", "min_cpu": "Intel Pentium 4 с тактовой частотой 2 ГГц или аналогичный ", "min_gpu": "со 128 МБ видеопамяти, совместимая с DirectX 9.0 ", "min_ram": "1.0", "min_hdd": "5.0", "rec_os": "", "rec_cpu": "", "rec_gpu": "", "rec_ram": null, "rec_hdd": null } } I used CharField for fields like "name", "description", and EmbededField (from Djongo) for fields … -
Difference between web application architecture and design pattern?
I need to develop a photo album web app in Django, stored on cloud services, with user login authentication, metadata and database. It must be developed according to a specific software design pattern that is different to the architectural pattern chosen. Please explain the difference between design and architectural patterns. Any industry acceptable suggestions on these patterns, suitable for a small project as explained above, would be very helpful. -
Django RestFRamework filter a ManytoMany model field
In my django app i have these two models: class Device(models.Model): mac_id = models.CharField(max_length=400, primary_key=True, null=False) short_name = models.CharField(max_length=400, default='') ... class Anagrafica(models.Model): id = models.AutoField(primary_key=True) cod_imp = models.CharField(max_length=80, verbose_name="Codice impianto") rb_sel = models.ManyToManyField(Device) well i have to filter in my API using Django RestFramework the rb_sel field, so i try: in serialyzers.py: class RaspFilter(django_filters.FilterSet): rb_sel = django_filters.BaseInFilter( name ='rb_sel__short_name', lookup_type='in', ) class Meta: model = Anagrafica fields = ('cod_imp', 'rb_sel') class AnagraficaSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') rb_list = DeviceSerializer(read_only=True, many=True) class Meta: model = Anagrafica fields = ['id', 'cod_imp', 'soc', 'soc_sigla', 'regione', 'prov', 'comune', 'cap', 'indirizzo', 'coordinate', 'notes', 'rb_list', 'owner'] filter_class = RaspFilter and in my views.py i add: filter_backends = [DjangoFilterBackend] filter_class = RaspFilter but when i try my api i get a 500 error: TypeError at /api/anagrafica/ init() got an unexpected keyword argument 'name' where i am wrong? how can i filter on my manytomany rb_list field? So many thanks in advance -
show related images to product in Django?
Hi Here I am trying to display all the images related to a particular product in a popup My problem is the When I upload a photo for one of This Objects, it display on a both of Object how can i filter them for to display on the relavent object? Photo 1 Popup Admin Panel my models.py class Portfolio_Detail(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='Portfolio/') def __str__(self): return self.title class Portfolio_Image(models.Model): portfolio = models.ForeignKey(Portfolio_Detail, on_delete=models.CASCADE,related_name="portfolio") image = models.ImageField(upload_to='Portfolio_Image/') my views.py def home(request): portfolios = Portfolio_Detail.objects.all() portfolio_images = Portfolio_Image.objects.filter() context = { 'portfolios' : portfolios, 'portfolio_images' : portfolio_images, } return render(request, "index.html", context) My Template <!-- Portfolio Section Start --> <section class="portfolio-section sec-padding" id="portfolio"> <div class="container"> <div class="row"> <div class="section-title"> <h2>Recent Works</h2> </div> </div> <div class="row"> <!-- Portfolio Item1 Start --> {% for item in portfolios %} <div class="portfolio-item"> <div class="portfolio-item-thumbnail"> <img src="{{item.image.url}}" alt="portfolio item Thumb"> </div> <h3 class="portfolio-item-title">{{item.title}}</h3> <button type="button" class="btn view-project-btn">View Project</button> <div class="portfolio-item-details"> <div class="description"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> </div> <div class="general-info"> <ul> <li>Created : <span>4 dec 2020</span></li> <li>Technology : <span>Html</span></li> <li>Role : <span>Frontend</span></li> <li>View Online : <span><a href="#" target="_blank">www.domain.com</a></span></li> </ul> </div> </div> </div> <!-- Portfolio Item1 End --> {% endfor %} </div> … -
How to make a filtering in Django
I want to do a filtering in django and I want to do this with date_created from custumUser for my filter. I can show date_create using list_display to my admin panel, but I can't filter through it on the page. my models.py like that. class CustomUser(AbstractBaseUser): email = models.EmailField(max_length=200, unique=True, verbose_name='Email') username = models.CharField(max_length=150, verbose_name='Username') first_name = models.CharField(max_length=150, verbose_name='First Name') last_name = models.CharField(max_length=150, verbose_name='Last Name') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return self.email # this methods are require to login super user from admin panel def has_perm(self, perm, obj=None): return self.is_admin # this methods are require to login super user from admin panel def has_module_perms(self, app_label): return self.is_admin class Meta: verbose_name = ('user') verbose_name_plural = ('users') class EmailConfirmed(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) activation_key = models.CharField(max_length=500) email_confirmed = models.BooleanField(default=False) date_confirmed = models.DateTimeField(auto_now=True) def __str__(self): return self.user.email class Meta: verbose_name_plural = 'User Email Confirmed' @receiver(post_save, sender=CustomUser) def create_user_email_confirmation(sender, instance, created, **kwargs): if created: dt = datetime.now().strftime('%Y-%m-%d … -
i can't make django to show pictures in my django project project is there any solution for it?
i can't make django to show pictures in my blog project hello, i am currently workin on a django blog project i have a really different problem i want to store each blogs post on a .pdf file and store it on a file in server the problem i have is that when i add the .pdf file and when django reads the file it just read the text and display the text as i want but it is unable to show pictures in the page. if there is a solution for this problem could you please share it and for that thank you a million times. -
Manager isn't accessible via class instance
I've recently faced Manager isn't accessible via model instance this error. By reading the Django doc I was able to resolve it. https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-objects This reason mentioned in the Django documentation is: Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations. I can't seem to understand the above statement. Can anyone explain it in simple words -
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
i'm making a django ecommerce site from a this youtube ecommerce tutorial.i have created a function for the delete from cart but when i press the delete button, i get this message TypeError at /cart/delete/ int() argument must be a string, a bytes-like object or a real number, not 'NoneType' here is the function def cart_delete(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) cart.delete(product=product_id) response = JsonResponse({'success':True}) return response > TypeError at /cart/delete/ int() argument must be a string, a > bytes-like object or a real number, not 'NoneType' Request > Method: POST Request URL: http://127.0.0.1:8000/cart/delete/ Django > Version: 3.2.8 Exception Type: TypeError Exception Value: int() > argument must be a string, a bytes-like object or a real number, not > 'NoneType' Exception > Location: C:\Users\DELL\Desktop\ecommerce\cart\views.py, line 30, in > cart_delete Python > Executable: C:\Users\DELL\Desktop\ecommerce\venv\scripts\python.exe > Python Version: 3.10.0 delete function def delete(self, product): product_id = str(product) if product_id in self.cart: del self.cart[product_id] self.session.modified = True my ajax script <script> $(document).on('click', '#delete-button', function(e){ e.preventDefault(); console.log($('#select option:selected').text()) $.ajax({ type:'POST', url:'{% url "cart:cart_delete" %}', data:{ productid: $('#add-button').val(), csrfmiddlewaretoken:"{{csrf_token}}", productqty: $('#select option:selected').text(), action: 'post' }, success: function (json){ }, error: function (xhr, errmsg, err){} }) }) </script> some please help.