Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unit testing for Django login page
I'm currently trying to write unit tests for the built-in django login page, and I keep getting this error. ERROR: test_login_success (User.tests.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\---------------\User\tests.py", line 74, in test_login_success self.assertTrue(response.data['authenticated']) AttributeError: 'TemplateResponse' object has no attribute 'data' Codes: no view function because I used the Django built-in login page test.py def test_login_success(self): testuser = User.objects.create_user(username = 'howdycowboy', password= 'Testing123' ) response=self.client.post(self.login_url,{'username':'howdycowboy', 'password': 'Testing123'},format='text/html') #self.assertEqual(response.status_code ,302) self.assertTrue(response.data['authenticated']) #HTML code {% extends 'User/base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} I've also tried self.assertEqual(response.status_code ,302) it redirects once it logs in, but for some reason the response.statuscode is 200. % (response.status_code, status_code) AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) -
How to take data from model and display on the product page?
I am developing an ecommerce website with django, I can not show on the product page (product_detail.html) the dates from Product_details model, from other models I can display dates, for example, from the Product_image model and from Category model I already take dates and display without any problems. It seems that I did all steps right, but I can not display the dates. Please help me. urls.py: from django.urls import path from . import views from .views import ProductListView from django.conf.urls.static import static urlpatterns = [ # path('', views.home, name='amd-home'), path('', ProductListView.as_view(), name='amd-home'), # path('', views.home_page, name='amd-home'), # path('product/<int:pk>/', ProductDetailView.as_view(), name='product-detail'), path('product/<int:id>/', views.product_detail, name='product-detail'), path('about/', views.about, name='amd-about'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=200) parent_id = models.IntegerField(default=0) description = models.TextField() image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Brand(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Product(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='uploads/', blank=True, null=True) sku = models.CharField(max_length=200) price = models.IntegerField(default=0) price_old = models.IntegerField(default=0) description = models.TextField() status = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f'{self.title}, {self.description}' class … -
Django Admin Inline & TabularInline – Appending ordered text fields with a sql database structure
I have read and have tried some of the examples in https://docs.djangoproject.com/en/3.1/ref/contrib/admin/ in regard to appending additional objects. Essentially what I want is a Question to have multiple Answers and within the Admin Question area with the ability to get a [+] button to add additional questions. I want to get that working first; but down the road I also want to do the following: Ordered list of Answers: that is, ranked ordering to the questions. Ability to repeat Answers in the ordered list In models.py file from django.db import models class Question(models.Model): name = models.CharField(max_length=50) question = models.CharField(max_length=50) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) class Answer(models.Model): answer = models.CharField(max_length=50) In admin.py file: From .models import ( Question, Answer, ) class AnswerTabularinline(admin.TabularInline): model=Answer class QuestinAdmin(admin.ModelAdmin): inlines = [AnswerTabularinline] class Meta: model = Question admin.site.register(Question, QuestinAdmin) admin.site.register(Answer) This is a fairly standard implementation of tabular inline; however, I am linking it to a SQL database and I have added the following tables: CREATE TABLE "ModME_question" ( "id" INTEGER NOT NULL UNIQUE, "name" TEXT, "text" TEXT, "answer" INTEGER, FOREIGN KEY("answer") REFERENCES "ModMe_Answer"("id"), PRIMARY KEY("id" AUTOINCREMENT) ); CREATE TABLE "ModMe_Answer" ( "id" INTEGER NOT NULL UNIQUE, "text" TEXT, PRIMARY KEY("id" AUTOINCREMENT) ); -
How i can use a CreateView with the same model Post to create a Post(Parent) with comments Post(Children)?
Im trying to create a view to use it in two cases: Create a Post Create a Post with comment. Using the same model and view (Im open to use two views, but im looking for the Pythonic/Django way to do it). I dont know to do it with CBV -> CreateView Model: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=500) image = models.ImageField(upload_to="user/post", blank=True) video = models.URLField(blank=True) comment = models.ForeignKey("self", on_delete=models.CASCADE, default=None, blank=True, null=True, related_name='comments') date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) featured = models.BooleanField(default=False) View: class PostCreateView(LoginRequiredMixin, CreateView): form_class = PostForm template_name = "core/post_create.html" def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.date_created = timezone.now() obj.save() return redirect("feed") Source code on Github -
converting ERD to django models
Is there any tool which can convert an ERD to django models ? NOT the other way round. I mean If I drew an ERD. is it possible to generate django models from it ? -
While appending a UUID field in to a list it also storig the type of the filed
I am having a model and it having a uuid field public_id = models.UUIDField( unique=True, editable=False, default=uuid.uuid4) I am getting an issue while filtering I am getting a query set like this <obj1,obj2, obj3...> I am looping through it and saving the public_id in a single list like this associated_elements = list() for i in query_set: associated_elements.append(i.public_id) print(associated_elements) I am getting output like this [UUID('a3d69af6-9678-4c1a-8adf-3b9f3600c3b5'), UUID('c0cc4cbd-9b79-4e04-bbc2-dcfb52a9e3de'), UUID('86cd21a5-0833-4b46-8dd8-bf730a3014ee'), UUID('70596f50-2e00-44e9-9795-fce13d33fdbb'), UUID('e60c88b3-1066-4ddd-bab6-7a33a84dd998')] But I need an output in this format ['7e254d14-488a-45ed-8712-fe1a339d6c28', '40949d78-8252-4087-b69e-2143915b2317'] Is there any way for that ? -
get Django model all related generic records
I have a Django model with a GenericForeignKey, and several other models pointing to it through GenericRelation: class InventoryAction(CustomModel): action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale', 'inventorysalecancellation', 'inventorystockinit')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción")) action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción")) action_object = GenericForeignKey('action_content_type', 'action_object_id') timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora")) class InventoryStockInit(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='stock_init', verbose_name=_("Almacén")) timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora")) comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios")) inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id') class InventoryInput(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén")) reference = models.ForeignKey(InventoryAction, null=True, blank=True, on_delete=models.PROTECT, limit_choices_to=Q(action_content_type__model__in=['inventorytransfer', ]), related_name='referenced_by', verbose_name=_("Referencia")) inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id') And I have a Django Rest Framework viewset that attempts to get all related records from the GenericForeignKey: class InventoryActionForListViewSet(viewsets.ViewSet): permission_classes = (permissions.IsAuthenticated,) def list(self, request): self.repository = request.query_params['repository'] inventory_actions = models.InventoryAction.objects.filter(inventory_action__repository_id=self.repository).order_by('-timestamp') inventory_actions_to_return = serializers.InventoryActionForListSerializer(inventory_actions, many=True) return Response(inventory_actions_to_return) The problem is that the view raises the following exception: django.core.exceptions.FieldError: Cannot resolve keyword 'inventory_action' into field. Choices are: action_content_type, action_content_type_id, action_object, action_object_id, batch, id, products, referenced_by, referenced_by_input_or_output, referenced_by_output, timestamp I can see that the GenericRelation is not being recognized. how can I execute the query I want, using generic relationships? -
How do I process in Django a text submit with "Post" or "GET" method from HTML?
I have a project to build a Wiki page in Django and I require to process a word sent from a search field and display its information on screen in case the word matches the stored information. For this I want to send a parameter with "POST" method from the following html template. <form action="{% url 'wiki:index' %}" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit"> </form> The idea is for the parameter to be received by the following functions of my file views.py written in Django. def index(request): if request.method == "POST": title = request.POST["q"] return redirect("wiki:languages") else: return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def languages(request, title): return render(request, "encyclopedia/definitions.html", { "title": util.get_entry(title) }) This file has the next header sentences: from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.http import HttpResponse from django.urls import reverse from . import util The "Languages" function in turn processes the get_entry(title) function of the "util.py" code def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None I have the following paths … -
Seeder insert bunch of data in database Django
I'm been trying to seed my data using python manage.py seed but it gives me an error below, All I want is to insert : Admin,Super admin etc. I been searching and reading documentation but its not working. Is there any expert can help me?It's almost three days Im been searching. Settings.py INSTALLED_APPS = [ 'app.apps.appconfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_seed', 'data_seeder', ] I also want to seed bunch of data, so I created a file seed.py under app folder: Reference link from django.core.management.base import BaseCommand import random MODE_CLEAR = 'clear' class Command(BaseCommand): help = "seed database for testing and development." def add_arguments(self, parser): parser.add_argument('--mode', type=str, help="Mode") def handle(self, *args, **options): self.stdout.write('seeding data...') run_seed(self, options['mode']) self.stdout.write('done.') def clear_data(): """Deletes all the table data""" logger.info("Delete Address instances") auth_permission.objects.all().delete() def create_usertype(): """Creates an address object combining different elements from the list""" logger.info("Creating address") usertype = ["Admin", "Super Admin", "MRB", "Customer", "Users"] //this is what I want to insert street_localities = ["Bakers Street", "Rajori Gardens", "Park Street", "MG Road", "Indiranagar"] pincodes = ["101234", "101232", "101231", "101236", "101239"] address = usertypes_tbl( user_type=random.choice(usertype), description=random.choice(street_localities), status=random.choice(pincodes), ) address.save() logger.info("{} address created.".format(address)) return address def run_seed(self, mode): """ Seed database based on mode :param mode: … -
Django read data from an sync_to_async db call
I'm trying to read some data that I need to get from the database in an async function. So i'm wrapping it with channels sync_to_async function. Now the issue is how do I access the actual data that I retrieved from the database? Currently it just outputs as this: <channels.db.DatabaseSyncToAsync object at 0x7f7b672ea6d0> Code: from ...models import admin_list from channels.db import database_sync_to_async def get_admins(): return admin_list.objects.values('name') @bot.event async def on_message(message): admin_names = database_sync_to_async(get_admins) print(admin_names) -
Django Rest Framework serializer field incorrectly named
When I run api request I get a following error: AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'email'. New user gets inserted in database anyway, email field is filleld properly. View: class Register(APIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(serializer.data, status=status.HTTP_201_CREATED) Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', 'username', 'name', 'password'] def create(self, validated_data): user = User.objects.create_user(**validated_data), return user Model: class User(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True) username = models.CharField(max_length=30, unique=True) name = models.CharField(max_length=60) date_of_birth = models.DateField(blank=True, null=True) bio = models.CharField(default='', max_length=10000) photo = models.ImageField(max_length=255, null=True, blank=True) email_verified_at = models.DateTimeField(null=True, blank=True) email_token_time = models.DateTimeField(null=True, blank=True) email_token = models.CharField(default='', max_length=64) password_token_time = models.DateTimeField(null=True, blank=True) password_token = models.CharField(default='', max_length=64) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) last_seen = models.DateTimeField(null=True, blank=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username', 'name'] objects = UserManager() class Meta: db_table = "User" def __str__(self): return self.username I also have custom user manager, but that is probably irrelevant, and works as user … -
What would be the most optimal/logical way to store answers to pre-determined yes or no questions to the database
I've been thinking: What would be the most optimal/logical way to store user answers to pre-determined 'yes or no' questions to the database. Note: the question model is in a one-to-one relationship with the user model. No. of Questions: 25 A: Store the questions as straight boolean variable/column to the database. Per user x 25 columns B: Store the questions as 'question' and boolean 'answer' to the database. Per user x 25 question rows, 1 user x 25 answer rows Which is faster? Please share your thoughts. -
Can't apply retrieved form data to multiple objects
I'm trying to use a form with one field (shown as a dropdown in rendered template.html) to change an attribute of multiple objects of the same model. However, for some reason I can't apply the retrieved form data to the objects. models.py: class Player(models.Model): class Race(models.TextChoices): HUMAN = "Human" UNDEAD = "Undead" race = models.CharField(choices=Race.choices) forms.py: class PlayerRaceForm(ModelForm): class Meta: model = Player fields = [ 'race' ] views.py: def index(request): players = Player.objects.all() player_race_form = PlayerRaceForm() if request.method == 'POST': print(player_race_form.errors) # nothing here print(player_race_form.non_field_errors) # see next code block if player_race_form.is_valid(): # it aint for some reason :/ for player in players: player.race = player_race_form.cleaned_data['race'] player.save() context = {'player_race_form': player_race_form,} return render(request, 'template.html', context) On print(player_race_form.non_field_errors): <bound method BaseForm.non_field_errors of <PlayerRaceForm bound=False, valid=False, fields=(race)>> I tried to bypass the is_valid and cleaned_data and made it work somehow, but it saved a noticeably wrong value not in the Race class. def index(request): players = Player.objects.all() player_race_form = PlayerRaceForm() if request.method == 'POST': print(player_race_form.errors) # nothing here print(player_race_form.non_field_errors) # see next code block for player in players: player.race = player_race_form['race'].value() # player.race = player_race_form.data['race'] #MultiValueDictKeyError player.save() context = {'player_race_form': player_race_form,} return render(request, 'template.html', context) Also tried to modify one object … -
How to achieve multiple output representations in Django Rest Framework Serializer
I am trying to use the Django Rest Framework(DRF)'s serializer with Djnago models with some PostgreSQL fields. I understand that by overriding to_representation() method of the serializer, the outgoing (serialized) data format can be changed. Is there any way to have multiple outgoing representations in DRF serializers? For example, what I am trying to achieve is something like this. from rest_framework import serializers class MySerializer(serializers.Serializer): first_name = serializers.CharField(max_length=20) last_name = serializers.CharField(max_length=20) def to_representation_1(self, instance): return { 'first_name': instance.first_name, 'last_name': instance.last_name } def to_representation_2(self, instance): return { 'firstName': instance.first_name, 'lastName': instance.last_name } def to_representation_2(self, instance): return { 'name': f'{instance.first_name} {instance.last_name}', } Is there such support in DRF? If no, what is the recommended way to achieve this keeping the possibility of nested serializers in mind? -
For validation, when to use Modelform clean or Model clean in django?
I found there are many posts related to validation. But I wasn't sure when to use one of them over the other. Can you clarify the difference between the two and when to use them? -
Django REST API: Deduplicating authorization checks in test code
In a chat app I'm making, I have this (similar) copied and pasted at the top of each API test I've written to check against unauthorized access. def test_message(self): # Unauthorized - 401 client = APIClient() url = reverse("chat-messages-list", host="api", kwargs={"pk": self.chatroom.id},) response = client.post(url, {"text": "this is a test message"}) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # Blocked - 403 client.force_authenticate(user=self.user1) response = client.post(url, {"text": "this is a test message"}) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) Is there a more composable way to structure this so I don't need to copy and paste it at the top of every API test? -
django webhook 301 Moved Permanently error
I am implementing a webhook receiver in the website I am developing to receive POST requests. I am having an issue receiving the POST requests. To test if it is working, I tested sending POST data using curl. It is working fine on local development server but I am receiving 301 Moved Permanently error while testing on the server. If I am testing on local development server like below curl --data "event="CASHGRAM_REDEEMED"&cashgramid="cashgramid"&referenceId="referenceId"&eventTime="now"&utr="utr_1"&signature="GHxFF2JHuFVRg0zSJ4L82ju0QtQx3DAEAy9hF4eLzEs="" http://127.0.0.1:8000/cashfree_cashgram_webhook/ It is working fine. But when I do this to test when the code is on the server curl --data "event="CASHGRAM_REDEEMED"&cashgramid="cashgramid"&referenceId="referenceId"&eventTime="now"&utr="utr_1"&signature="BHvFF2JDuFVTh0zSJ4L82ju0QtQx3DAEAy9hF4eLzEs="" https://mywebsite.com/cashfree_cashgram_webhook/ then I am getting below error. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>301 Moved Permanently</title> </head><body> <h1>Moved Permanently</h1> <p>The document has moved <a href="https://www.mywebsite.com/cashfree_cashgram_webhook/">here</a>.</p> </body></html> Just for privacy I replaced real webiste address with mywesite.com Below is the view method in the backend to receive POST requests. In this method I am verifying signature and saving the received information. @csrf_exempt def cashfree_cashgram_webhook(request): if request.method == "POST": data = "" for key in sorted(request.POST.keys()): print(request.POST[key]) if key != 'signature': data = data+key+request.POST[key] secretKey = settings.CLIENT_SECRET secretKey = bytes(secretKey, 'utf-8') data = bytes(data, 'utf-8') dig = hmac.new(key=secretKey, msg=data, digestmod=hashlib.sha256) generated_signature = base64.b64encode(dig.digest()) generated_signature = generated_signature.decode('utf-8') # … -
Django cant find CSS for the admin page
this just started today I tried to reset css [27/Oct/2020 22:56:44] "GET /static/admin/css/base.css HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 179 [27/Oct/2020 22:56:44] "GET /static/admin/css/dashboard.css HTTP/1.1" 404 179 -
Django makemigrations and migrate
I am having trouble with the py manage.py makemigrations [project_name] and py manage.py migrate command. Every time I try these two commands in the right order, I get the following error: Traceback (most recent call last): File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\manage.py", line 20, in <module> main() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\core\management\base.py", line 301, in run_from_argv connections.close_all() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\utils.py", line 225, in close_all connection.close() File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 190, in close if not self.is_in_memory_db(): File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 287, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Gilbert\PycharmProjects\GGprojects\django\ll_env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 13, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable Looking at the error, I would tell maybe my Python PATH isn't correct. The current path for it is C:\Users\Gilbert\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.9. Is that the reason there is an error? And will it affect my Django project? Also, how can I solve this problem? -
How to implement json_object_agg() in a Django queryset?
How can I implement the json_object_agg() function from PostgreSQL in a Django queryset within a view? As an example, I'd like to translate a query similar to the one below into a Django queryset (taken from https://postgresql.verite.pro/blog/2018/06/19/crosstab-pivot.html) SELECT city, json_object_agg(year,total ORDER BY year) FROM ( SELECT city, year, SUM(raindays) AS total FROM rainfall GROUP BY city,year ) s GROUP BY city ORDER BY city; with expected output like city | json_object_agg -----------+---------------------------------------------------------------------------------------- Ajaccio | { "2012" : 69, "2013" : 91, "2014" : 78, "2015" : 48, "2016" : 81, "2017" : 51 } Bordeaux | { "2012" : 116, "2013" : 138, "2014" : 137, "2015" : 101, "2016" : 117, "2017" : 110 } Brest | { "2012" : 178, "2013" : 161, "2014" : 180, "2015" : 160, "2016" : 165, "2017" : 144 } Dijon | { "2012" : 114, "2013" : 124, "2014" : 116, "2015" : 93, "2016" : 116, "2017" : 103 } Lille | { "2012" : 153, "2013" : 120, "2014" : 136, "2015" : 128, "2016" : 138, "2017" : 113 } Lyon | { "2012" : 112, "2013" : 116, "2014" : 111, "2015" : 80, "2016" : 110, … -
Copying model instances from one model to another
I'm using django and struggling with model to model inheritance. I have two models model A and B. I want to press a button in the html, which will copy a unique onbect instance from model A and create that same instance in model B, I then delete want to delete the single object instance in model A. Model A is Customer quotes and Model B is Customermarketplacequote, please see views.py below. The below code is not actioning the request? is there a smarter way to do this, or a way to modify the code, below. Appreciate any help or guidance. Views.py def cust_create_marketplace_quote(request, id): if request.method == "POST": quote = Customerquote.objects.get(pk=pk) context = { 'quote': quote, 'values': quote, } quote = Customermarketplacequote(request.POST) if quote.is_valid(): quote.save() return redirect('manage-quotes') else: return render(request,'sub/customer_marketplace_quotes.html') Best, Serick -
Djangon 2.2 filtering a single data set across pages
In my django app I have a main page which shows the numbers of books for each genre in a table and it also has a search bar that allows filtering of the books by Genre, title or author which then posts the data to a search page and allows viewing of the book entries in a table. On the search results page I want to then be able to additionally filter the same set of data further using an extended set of search bars - including the original filters, plus filters such as publish date and rating. In the extended search I would not want to lose the original search - so for example if I search for horror genre on the main page and then wish to filter that further to only include highly rated books on the sesrch page I dont want to lose the horror filter if I don't add the filter again. Is this possible? Essentially I'm wondering if you can apply different filters to a single view? Thank you in advance -
How to programatically post to Django Rest Framework endpoint?
I've got an endpoint built with Django Rest Framework. I now want to separate the ingress and the parsing. So I created an endpoint which basically writes the received string of data to a textfield in. I now create a management command which continuously loops over that table and parses the contents. So I get the I raw string from the ingress table, and I now want to post this to the DRF endpoint programmatically. I've done this many times in my unit tests. But I'm unsure how I can do this from the management command. I can use the same code as I do for test requests, but it seems weird to use testing code in production. People might suggest to manually use the serializer, but there's also things happening in the viewset which I need. Does anybody have a good idea how I would be able to do this? -
Vscode with beautify does not indent django html templates
I am looking to format my django templates in the same manner as HTML. Beautify ends up treating my templates like text, and not indenting their contents. For example, after formatting my code looks like this: <head> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> Instead of <head> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> I currently have Beautify & Django extensions installed, running on VSCode and WSL. settings.json VSCode: "files.associations": { "**/*.html": "html", "**/templates/*/*.html": "django-html", "**/templates/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "emmet.includeLanguages": { "django-html": "html" }, "beautify.language": { "html": [ "htm", "html", "django-html" ] }, "[django-html]": { "editor.defaultFormatter": "HookyQR.beautify" } Why isn't beautify correctly formatting / indenting my templates? How can I resolve this behavior? -
How to handle management command exception in django app?
I'm working on a django app which is based on consuming an external ZeroMQ message queue - it listens to the queue all the time, processing the messages and saving the outcome in the database. The data will be in the future made accessible to the users by API. Currently I'm running it by a custom management command listen, which runs an infinite loop and it works fine. However, whenever some kind of error appears (and they will sometimes appear, it's an external data source) the command dies. What's the best approach to handle such errors? Things I'm considering: Bash script which will restart the command on failure Big Try... except Exception in the main command function (but this seems extremely wrong) Some custom exception handler - the problem is that the recommended handlers only handle errors in views/requests, and my command is not a view/request, it just runs. Any advice would be useful, maybe it's a misuse of the management command?