Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why single html <p> tag is being spilt into two <p> tags with a <br> tag between them?
Below is my template html tag ( django): <p class="card-text cfs-9 cfc-grey">{{i.post|safe|truncatechars:100}}</p> This tag render totally fine on local server, but on production server, this single <p> tag is being split into two <p> tags and an extra <br> tag appear out on nowhere between them. I think the issue is with 'truncatechars' but i could not figure out. Below is view source code from both local and production server. Local Server view page source: <p class="card-text cfs-9 cfc-grey">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the…</p> Production server view page source: <p class="card-text cfs-9 cfc-grey"><br><p>In this post I'll be demonstrating how we can deploy Django website on…</p> I tried {{i.post|truncatechars:10|safe}} instead of {{i.post|safe|truncatechars:100}} but the problem remains.Tried using 'truncatewords' but still same problem. -
Specifying a relation through multiple shared foreign keys
Let's say we have 4 models, lets call them Alpha, Beta, Gamma, and Delta and the first two are something like: class Alpha(models.Model): gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT) delta = models.ForeignKey(Delta, on_delete=models.RESTRICT) text = models.CharField(max_length=1024) class Meta: constraints = [ models.UniqueConstraint(fields=['gamma_id', 'delta_id']) ] class Beta(models.Model): gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT) delta = models.ForeignKey(Delta, on_delete=models.RESTRICT) value = models.IntegerField() As you can see the two foreign keys can be used to associate any number of rows from Beta with one row from Alpha. There is essentially a one to many relationship between Beta and Alpha. For various reasons it is not feasible to replace the two foreign keys in Beta with a foreign key to Alpha. Is there a way to define a relationship on Alpha that returns all the rows from Beta that have the same gamma_id and delta_id -
How to use aggregate functions count or length in django
would like to use the count or length function in template, but I don't know how to go about it. I would like to count the items separately of all categories models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Rock', 'Rock'), ('Pop', 'Pop'), ('Reggae', 'Reggae'), ('Disco', 'Disco'), ('Rap', 'Rap'), ('Electronic music', 'Electronic music'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) views.py A simple listing of all elements class ProductListView(View): def get(self, request): products = CD.objects.all() return render(request, 'products/statistics.html', {'products': products}) -
processing data from django form
I have a form with a drop down list: CATEGORY_CHOICES= [ ('sport', 'Sport'), ('mini', 'Mini'), ('economy', 'Economy'), ('electro', 'Electro'), ('business', 'Business'), ] class CategoryChoice(forms.Form): category= forms.CharField(label='Поиск по категории:', widget=forms.Select(choices=CATEGORY_CHOICES, ), required = False) I need that when choosing a category and pressing the "search" button, the user will be redirected to the page with the goods of the selected category? I have no idea how to link the html template, view.py and urls.py together. Could you please help me? I will be very grateful. -
Django: get most frequent objects in many to many relationship
class SoundItem(models.Model): name = models.CharField(max_length=200) class SoundCategory(models.Model): name = models.CharField(max_length=200) class SoundItemReview(models.Model): sound = models.ForeignKey(SoundItem, on_delete=models.CASCADE, related_name='sound_reviews') categories = models.ManyToManyField(SoundCategory, related_name="sound_reviews") For one instance of sound item (s), I can get its reviews with s.sound_reviews.all(), but how I count most frequent categories in its reviews (without having to manually iterate reviews and count categories)? Eg for s there are 2 reviews: review1: category1, category2 review2: category2, category3 then I want to get {"category2": 2, "category1": 1, "category3": 1} -
Passing a list of senders to the sender parameter of @receiver decorator
So at the moment, I'm working on my Django project and I have a signal receiver function that looks like this: @receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre_1') @receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre_2') @receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre_3') def task_handler_pre(sender, instance, **kwargs): # do some stuff In an attempt to make the code look cleaner, I was wondering whether would it be possible to do something like this: @receiver(pre_save, sender=[Task, TaskHistory, TaskUser], dispatch_uid='core.models.task_handler_pre') def task_handler_pre(sender, instance, **kwargs): # do some stuff i.e. Does the sender parameter accepts a list of senders as a valid argument ? If not, then does the value of the dispatch_uid parameter within the @receiver decorator, have to be different for each individual sender, or can it be the same i.e. As mentioned previously, my receiver function looks like this at the moment: @receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre_1') @receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre_2') @receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre_3') def task_handler_pre(sender, instance, **kwargs): # do some stuff What difference would it make if I make the following change: @receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre') @receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre') @receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre') def task_handler_pre(sender, instance, **kwargs): # do some stuff i.e. make the value of the dispatch_uid parameter the same ( core.models.task_handler_pre ) for each individual sender. Thanks! -
How to route nginx pages to different pages?
Hello I have django app let's suppose my site uri is example.com now i want to route my admin dashboard to another port like if users types abc.example.com it automatically routes to main page of my app but i want to have abc.example.com:445/admin/* is it possible the solution i tried was server { listen 443 ssl; server_name abc.example.com; client_max_body_size 500M; ssl_certificate /etc/nginx/my.crt; ssl_certificate_key /etc/nginx/server.key; location / { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://localhost:3001; } } server{ listen 445 ssl; server_name abc.example.com; client_max_body_size 500M; ssl_certificate /etc/nginx/my.crt; ssl_certificate_key /etc/nginx/server.key; location /admin { proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://localhost:3001; } } server { listen 80; server_name abc.example.com; return 301 https://$host$request_uri; } But this itself routes to port 443 and /admin page is also available there so how to avoid this any possible solutions. -
reverse accessor model clashing Django Web App
from django.db import models from django.contrib.auth.models import AbstractUser class Customer(AbstractUser): address_line = models.CharField(max_length=255) city = models.CharField(max_length=255) postal_code = models.CharField(max_length=10) phone_number = models.CharField(max_length=20) origin_country = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='customer_profile_pics', null=True, blank=True) class Chef(AbstractUser): address_line = models.CharField(max_length=255) city = models.CharField(max_length=255) postal_code = models.CharField(max_length=10) phone_number = models.CharField(max_length=20) origin_country = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='chef_profile_pics', null=True, blank=True) class Meal(models.Model): name = models.CharField(max_length=255) description = models.TextField() picture = models.ImageField(upload_to='meal_pics') country = models.CharField(max_length=255) chef = models.ForeignKey(Chef, on_delete=models.CASCADE, related_name='meals') customers = models.ManyToManyField(Customer, blank=True, related_name='meals') class Discussion(models.Model): message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True, related_name='discussions') chef = models.ForeignKey(Chef, on_delete=models.CASCADE, null=True, blank=True, related_name='discussions') This is my models.py file I get the following error while making migrations SystemCheckError: System check identified some issues: ERRORS: meals.Chef.groups: (fields.E304) Reverse accessor for 'Chef.groups' clashes with reverse accessor for 'Customer.groups'. HINT: Add or change a related_name argument to the definition for 'Chef.groups' or 'Customer.groups'. meals.Chef.user_permissions: (fields.E304) Reverse accessor for 'Chef.user_permissions' clashes with reverse accessor for 'Customer.user_permissions'. HINT: Add or change a related_name argument to the definition for 'Chef.user_permissions' or 'Customer.user_permissions'. meals.Customer.groups: (fields.E304) Reverse accessor for 'Customer.groups' clashes with reverse accessor for 'Chef.groups'. HINT: Add or change a related_name argument to the definition for 'Customer.groups' or 'Chef.groups'. meals.Customer.user_permissions: (fields.E304) Reverse accessor … -
Django API Blog-post
models.py class CommentModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(PostModel, on_delete=models.CASCADE) comment = models.TextField() created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) Serializers.py class CommentListSerializer(serializers.ModelSerializer): class Meta: model = CommentModel fields = ['id','comment','post','user','created_at'] views.py class CommentListView(generics.GenericAPIView): permission_classes = [IsAuthenticated] queryset = CommentModel.objects.all() serializer_class = CommentListSerializer can anyone help me to retrieve all the comments that are posted under a blog post. -
i need to make more than one ime entry into the supplier model how can i do that? it only allow one ime
i have an ime model like that class Imee(models.Model): ime_number = models.CharField(max_length=256,null=False) def __str__(self): return self.ime_number def get_absolute_url(self): return reverse("ghaith:detail",kwargs={'pk':self.pk}) and i have a supplier model and i need to enter more then one ime to the supplier and more than a receipt class Supplier(models.Model): supplier_name = models.CharField(max_length=256,null=False) imee = models.ForeignKey(Imee,related_name='suppliers',on_delete=models.CASCADE) receipt_number = models.IntegerField(unique=True,null=False) receipt_date = models.CharField(max_length=256,null=False) def __str__(self): return self.supplier_name def get_absolute_url(self): return reverse("ghaith:detail",kwargs={'pk':self.pk}) -
Django/DRF Pagination using paginate_queryset doesn't return key, value but only keys in result
I've added pagination handling on one of my views using PageNumberPagination from DRF, using the paginate_queryset method works only after converting the result dict to a tuple, it's structure is like the following: { "key": {"other": "dict inside"}, "key2": {"other": "dict inside"}, "key3": {"other": "dict inside"}, } Pretty simple struct, the problem is that the result does return the correct data, but only their keys, I would like the result data to be key, value as the above structure instead of just keys. Is there an easy way of doing that? For reference I also already override PageNumberPagination with a custom class like this: class CustomPagination(PageNumberPagination): def get_paginated_response(self, data): return Response({ 'controller': { 'count': self.page.paginator.count, 'previous': self.get_previous_link(), 'next': self.get_next_link(), }, 'results': data }) And in my view to paginate: class ApiView(APIView, CustomPagination): page_size = 10 def get(self, request): # [...] pagination = self.paginate_queryset(tuple(result), request, view=self) return self.get_paginated_response(pagination) Where result is the original dict mentionned above converted to a tuple. -
Django - Link to download bringing me a past file
I have a regular Django project working fine for year and links for many download Microsoft Excel templates. The thing is I've change one of them, and when I click to download it, it downloads me the older spreadsheet (I've deleted it on my server). But if I access on an incognito browser, it downloads me the newest version. What should I do to solve this, is it something related to time expiration of cookies or something like this? Thank you in advance! -
Dynamically choices for microservices in django rest (best practices)
I have a microservice A which asks microservice B about what type of products can microservice A receive as it's choices for some CharField, for example, "Type". And I have some options, where to make the actual request to microservice B: 1)Model level (CharField(choices=TYPES)) 2)Serializers level 3)View level of the microservice A. So, when I'm adding some new type to microservice B "Type" model instance, I have to restart microservice A to receive this new option to create. But as it comes to the "list" ViewSet action, I can receive new types dynamically by just refreshing this page in browser, because of GET request So the question is: how to build this kind of connection between two microservices to avoid restarting the microservice A server to receive new options. I'll be glad to get some best practices. P.S. I heard about brokers, but at start level, I'm trying to get the actual mechanism of how it all works. After that I can build up comfortness, reliability and other features that comes with brokers -
Django: Alternate input forms for models in admin?
I'm basically asking if there's an equivalent to adding data kinda like how you'd create a new instance of a class using a classmethod instead of using init. My example is a publication input form - you can either add the data manually, or you can enter a key code (a DOI in this case), make a request to a central database, which will pull the rest of the data for you. Outside of Django, I'd implement it this way: from datetime import date class Publication: title: str = "" date: date = date.today() url: str = "" doi: str = "" publication_name: str = "" authors: list[str] = [] @classmethod def add_publication_manually(cls, title, pub_date, url, pub_name, authors, optional_doi): ob = cls.__new__(cls) ob.date = pub_date ob.title = title ob.url = url ob.publication_name = pub_name ob.authors = authors ob.doi = optional_doi return ob @classmethod def add_publication_from_crossref(cls, doi): import requests ob = cls.__new__(cls) # parse output from requests return ob if __name__ == "__main__": pub_list = [] pub = Publication.add_publication_manually("...") pub_list.append(pub) pub_doi = Publication.add_publication_from_crossref("doi") pub_list.append(pub_doi) I have a similar Django model set up, and I can add entries to the database using the "manual" method in the admin, but now I want … -
How to do model data validation in django
I would like when creating and editing a product to validate the data directly in the model in adminpanel and forms and if validated return an error more or less like this: models.py class Book(Product): GENRE_CHOICES = ( ('Fantasy', 'Fantasy'), ('Sci-Fi', 'Sci-Fi'), ('Romance', 'Romance'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Criminal', 'Criminal'), ('Biography', 'Biography'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) def save(self): try: Book.objects.get(author=self.author, title=self.title, genre=self.genre) raise ValueError("Author, title and genre must not be repeated") except ObjectDoesNotExist: super().save() Author, title and genre cannot repeat as tuple. Of course, overriding the save() method throws me an error when I try to use the already created model to add to the cart, etc.... Please help me on how I should do it. Thank you all -
Not show any product after submit
#React Code function RecScreen() { const \[budget, setBudget\] = useState(products); const \[items, setParts\] = useState(\[\]); const handleInputChange = (event) =\> { setBudget(event.target.value); }; const handleSubmit = async (event) =\> { event.preventDefault(); const response = await fetch(`/api/products?price=${budget}`); const data = await response.json(); setParts(data.product); }; return ( \<div\> <h1>PC Parts Recommender</h1> \<form onSubmit={handleSubmit}\> \<label\> Enter your budget: \<input type="number" value={budget} onChange={handleInputChange} /\> \</label\> \<button className='btn btn-warning rounded ms-1' type="submit"\>Recommend Parts\</button\> \</form\> <ul> {items.map(product =\> ( <li key={product.id}>{product.name} - ${product.price}</li> ))} </ul> \</div\> ); } export default RecScreen;' In this I tried to create a recommendation where user enter budget and he will get all parts of pc with in budget. #Django Code @require_GET def get_parts(request): budget = request.GET.get('budget') parts = [ {'id': 2, 'category': 'power supply', 'price': 8000}, {'id': 3, 'category': 'gpu', 'price': 400}, {'id': 4, 'category': 'mouse', 'price': 100}, {'id': 5, 'category': 'case', 'price': 50}, {'id': 8, 'category': 'ram', 'price': 80}, {'id': 9, 'category': 'processsor', 'price': 70}, ] parts_within_budget = [part for part in parts if part['price'] <= int(budget)] sorted_parts = sorted(parts_within_budget, key=itemgetter('price')) return JsonResponse(sorted_parts, safe=False) help me in this code after submit it not show any product in screen In this I tried to create a recommendation where user enter … -
Error when updating one field only Django Update method
I have a usecase model which has two foreign keys: kpi and usecase_type I created a method to update those two fields from dropdown list, The method only updates if I update all the fields (shows an error if update one dropdown list) , any idea what could be the reason? My views.py: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) context = {"usecase_details":usecase_details[0], "usecase_types": UsecaseType.objects.all(), "usecase_kpis": Kpi.objects.all()} if request.method == "POST": usecase_type = request.POST['usecase_type'] kpi = request.POST['kpi'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.usecase_type_id=usecase_type usecase_details.kpi_id=kpi usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) return render(request, 'UpdateUsecase.html', context) except: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect(reverse('update-usecase', args=[ucid])) my template: <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <div class="mb-4"> <h4 class="h4 uc-header">Edit usecase details:</h4> </div> <!-- <li role="separator" class="dropdown-divider border-black mb-3 ml-3"></li> --> <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="project-name">Usecase Type:</label> <select name="usecase_type" class="custom-select my-1 mr-sm-2" id="usecase_type"> <option value="0" selected>{{usecase_details.usecase_type.usecase_type_name}}</option> {% for usecase_type in usecase_types %} <option value="{{ usecase_type.usecase_type_id }}">{{ usecase_type.usecase_type_name }}</option> {% endfor %} </select> … -
can you add hidden field to django orm object?
I am fairly new to django so bear with me. but is it possible to implement something similiar to laravel's hidden array: $hidden = ['password', ] in django? I intend to use it in the same manner as the laravel code, to hide the password field from being returned everytime i get a user object from the database. I searched all over the internet for a solution for this but i couldn't find anyone mentioning the topic. -
Want to get popular user
I need help with a Django app am working on, so I am trying to get popular users. I want to archive this by getting all the likes on the post a particular user has created. -
Unable to update models with File field on Django admin or through post method
I have a Django application in the production environment. It works fine when I use runserver by IP address, even in the production environment. but when I try to access it through domain it does not allow me to update the file field (Image Field) the request takes too long and I keep getting <method 'read' of 'lsapi_wsgi.InputStream' objects> returned NULL without setting an error in my error log and it does not even allow me to login to Django admin page on PC's(only Mobile). full trace error SystemError at /admin/accounts/user/1/change/ <method 'read' of 'lsapi_wsgi.InputStream' objects> returned NULL without setting an error Request Method: POST Request URL: https://dev.temarico.com/admin/accounts/user/1/change/ Django Version: 4.1.7 Exception Type: SystemError Exception Value: <method 'read' of 'lsapi_wsgi.InputStream' objects> returned NULL without setting an error Exception Location: /home/temaricocom/virtualenv/API/Backends/3.8/lib/python3.8/site-packages/django/core/handlers/wsgi.py, line 28, in _read_limited Raised during: django.contrib.admin.options.change_view Python Executable: /home/temaricocom/virtualenv/API/Backends/3.8/bin/python Python Version: 3.8.12 Python Path: ['/home/temaricocom/API/Backends', '', '/home/temaricocom/API/Backends', '/opt/alt/python38/lib64/python38.zip', '/opt/alt/python38/lib64/python3.8', '/opt/alt/python38/lib64/python3.8/lib-dynload', '/home/temaricocom/virtualenv/API/Backends/3.8/lib64/python3.8/site-packages', '/home/temaricocom/virtualenv/API/Backends/3.8/lib/python3.8/site-packages'] Server time: Sun, 19 Mar 2023 09:45:19 +0300 -
creating user based collaborative filter in Django
I want to create a User-Based collaborative filter for an e-commerce here are my steps Create an event model with foreign key relation to a product and a user first I create an event and a recommendation model class Event(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="user_event_set") product = models.ForeignKey('product.Product', models.CASCADE, related_name="product_event_list") created_at = models.DateTimeField(auto_now_add=True) class EventType(models.IntegerChoices): seen = 1, "Visited the product page" cart = 2, "Added to cart" bought = 3, "User purchased the product" searched = 4, "User searched for the product" event_type = models.IntegerField(choices=EventType.choices) class Recommendation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="user_recommended_set") product = models.ForeignKey('product.Product', models.CASCADE, related_name="product_recommended_set") created_at = models.DateTimeField(auto_now_add=True) now to get similar product here's my code: to get similar users, I get all users def get_similar_users(user, limit=5): all_users = User.objects.exclude(id=user.id).prefetch_related('user_event_set') similarities = [(other_user, calculate_similarity(user, other_user)) for other_user in all_users] similarities.sort(key=lambda x: x[2], reverse=True) return [user_similarity[0] for user_similarity in similarities[:limit]] calculate the similarity using this function: def calculate_similarity(user1, user2): user1_events = set(user1.user_event_list.values_list('product_id', flat=True)) user2_events = set(user2.user_event_list.values_list('product_id', flat=True)) intersection = user1_events & user2_events union = user1_events | user2_events similarity = len(intersection) / len(union) if len(union) > 0 else 0 weight = intersection.aggregate(weight=models.Sum('event_type')) #return by event priority return similarity, weight I'm using the weight to sort the users by it … -
django.core.serializers.base.DeserializationError: Problem installing fixture '/opt/my-api/mynetwork_common/fixtures/emoji-groups.json'
I'm running Django rest api with django 3.2 and docker on GCP Ubuntu 22.04. I'm getting an error when I run the web server container : django.core.serializers.base.DeserializationError: Problem installing fixture '/opt/my-api/mynetwork_common/fixtures/emoji-groups.json' The detailed trace is here : my-api-webserver | Traceback (most recent call last): my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/serializers/json.py", line 69, in Deserializer my-api-webserver | objects = json.loads(stream_or_string) my-api-webserver | File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads my-api-webserver | return _default_decoder.decode(s) my-api-webserver | File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode my-api-webserver | obj, end = self.raw_decode(s, idx=_w(s, 0).end()) my-api-webserver | File "/usr/local/lib/python3.8/json/decoder.py", line 355, in raw_decode my-api-webserver | raise JSONDecodeError("Expecting value", s, err.value) from None my-api-webserver | json.decoder.JSONDecodeError: Expecting value: line 11 column 28 (char 266) my-api-webserver | my-api-webserver | The above exception was the direct cause of the following exception: my-api-webserver | my-api-webserver | Traceback (most recent call last): my-api-webserver | File "manage.py", line 25, in <module> my-api-webserver | execute_from_command_line(sys.argv) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line my-api-webserver | utility.execute() my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute my-api-webserver | self.fetch_command(subcommand).run_from_argv(self.argv) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv my-api-webserver | self.execute(*args, **cmd_options) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute my-api-webserver | output = self.handle(*args, **options) my-api-webserver | File "/usr/local/lib/python3.8/site-packages/modeltranslation/management/commands/loaddata.py", … -
How can I use python django
I am sorry if the answer is obvious but I wasn't so sure and would like to get a clear answer on this, lets say I want to make a website with like chatbots in it, can I use the frontend to be html and css and than use python django to link backend with a database like AWS. If this is possible how exactly could I do this, also is there a better way to do this. I mostly want to do this as I want to learn more about backend coding, if there are better things to focus on please let me know. Thank you all. I have made a front end with html/css but now I am trying to learn django to see what I can do further. I haven't done anything with JS or AWS. -
Django CreateView ManyToManyField register error
class Categories(models.Model): name = models.CharField(max_length=125) class Companies(models.Model): name = models.CharField(max_length=125) class CompanyRights(models.Model): company = models.OneToOneField(Companies, on_delete=models.CASCADE, related_name='coms') category = models.ManyToManyField(Categories, related_name='cats') date = models.DateField(auto_created=True) class Products(models.Model): cat = models.ForeignKey(CompanyRights, on_delete=models.CASCADE) company = models.ForeignKey(Firmalar, on_delete=models.CASCADE, related_name='procom') I am using class based CreateView. I save the category rights of the company that registered the product to CompanyRights. The company shows data from this table for product Categories while registering products. When I try to save a product: Cannot assign "3": "Products.cat" must be a "CompanyRights" instance. zeq, thanks -
403 Forbidden in Xcode Simulator but works fine with Xcode Canvas Preview
I'm wrote a Login page with SwiftUI, and a backend with Django(both running in my laptop) the login api works fine no matter using Postman or in Xcode Canvas Preview but when I run the Xcode Project with Simulator, the Login func would fail the backend returns 403 forbidden Funny thing is, it works fine until yesterday, and I didn't change the code, just suddenly it won't work in the simulator Can anyone tell me what's going on here? and how can I fix it? Thanks! I tried to disable the csrf middleware in Django setting.py, and it didn't work