Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
open html file and add data into it with iteration
I have a html file for Invoice. and i want to display some data from my database which can be in multiple rows of a table. how can i use iteration to show the data in my Invoice. for example: In an organisation 3 people used a coupon to do a payment. and when invoice would generate all of the three people's name with date and amount i want to display. <thead> <tr> <th class="col-4 border-0"><strong>Sites</strong></th> <th class="col-4 border-0"><span><strong>Mode</strong></span></th> <th class="col-4 border-0"><span><strong>Amount</strong></span></th> </tr> </thead> <tbody> <tbody> ---for loop here--- <tr> <td class="col-4 text-1 border-0"> {var 1} </td> <td class="col-4 border-0"><span> {var 2} </span></td> <td class="col-4 border-0"><span> {var 3} </span></td> </tr> </tbody> </table> The way i am passing data from views is: my_dict=[{'var1':'my site', 'var2': 'DIY', 'var3':'111'}, {'var1':'my site2', 'var2': 'DIY', 'var3':'222'}] with open(BACKEND_TEMPLATE + 'Invoice_base.html') as inf: txt = inf.read() val = txt.format(date=today, invoice_id=str(identity), domain=FRONTEND_DOMAIN, customer_name=(obj.customer.first_name + " " + obj.customer.last_name), company=obj.customer.company_name, contact=obj.customer.phone_number, my_dict=my_dict) how can i achieve that. The html file is not supporting template tags or may be i am not using it correctly. if there is an easy solution please help me out! -
sliding key in Django how to
i am fairly new to python programing language and this year i challenged myself to build our project's app. We want the app to display certain features. To start with, this is our pseudo code : ' Inputs: Desired Max Temperature Tmax Intensity (in %) On or Off Tsurface Outputs LED0 LED1 LED2 LED3 LEDRED Relay1 Relay2 When Settings are changed If device is at 0% Power (0W) LED1, LED2, and LED3 are off If device is at 0 to 39% power (2.5 W) LED 1 is on, LED2 and LED3 are off If device is at 40 to 79% power (5 W) LED 1 and LED2 are on, LED3 is off If device is at 80 to 100% power (7.5 W) LED 1, LED2 and LED3 are on Ton = Tcycle * Intensity / 100% Continuously happen with timing signals If Tsurface >Tmax Relay1, Relay2 are off LEDRED is on Else At t=0+Ton/2 Turn Relay1 off At t=Tcycle-Ton/2 Turn Relay 1 on At t=Tcycle/2 - Ton/2 Turn Relay 2 on At t=Tcycle/2 + Ton/2 Turn Relay 2 off ' Python code ' from django.contrib import admin from django.urls import path, include from .views import (home,led_off,led_on, increase_temp,decrease_temp) urlpatterns = [ … -
Django Displaying Each User's Profile
I am building a website where there is a table at the homepage, and in that table there are people's names, numbers, their categories, the city they reside in, etc. I would like to create a link, that when a visitor clicks on any of the users' name, the visitor gets directed to that specific user's profile page. Right now, my code works partially. When I click any user, I get redirected to http://127.0.0.1:8000/profile/7/. That user ID number of "7" is the logged in user's ID. So no matter which user I click on, I get redirected to the profile page of the logged in user. Also, when I log out of the current user I am logged in to, I get this error message: "NoReverseMatch at / Reverse for 'profile_pk' with keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: ['profile/(?P[0-9]+)/$']" Here is what I have done with my code so far: views.py def ustaprofil(request, pk=None): if pk: user = get_object_or_404(User, pk=pk) else: user = request.user args = {'user': user} return render(request, 'user.html', args) urls.py path('profile/<int:pk>/', views.ustaprofil, name='profile_pk'), models.py class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) gizlilik_sozlesmesi = models.BooleanField("Gizlilik Sozlesmesini Okudum Onayliyorum*" , null=True) sartlar_sozlesmesi = models.BooleanField("Sartlar ve Kosullar … -
Best way to store heavily related values in relational database
I am trying to efficiently store heavily related data in a relational database. Table A stores the field names. Table B stores the type and Table C stores the values. I came up with the structure and the mappings as shown in this figure: Now when I want to query data from this table, we have to perform 2 hits for each relation. Also, for every insert I need to hit DB thrice(one for each table). Is there a better way to store this kind of structure? Is there a standard way to save this in Django models? -
Django path converter raises SynchronousOnlyOperation
I'm migrating an existing WSGI server to ASGI and I'm running into a problem where ORM usage in path converters raises a SynchronousOnlyOperation exception. My converter code is something like this class ModelPkConverter: regex = r'\d+' model = MyModel def to_python(self, primary_key): try: return self.model.objects.get(pk=primary_key) except self.model.DoesNotExist: raise ValueError def to_url(self, instance): return f'{instance.pk}' So when I go to a URL like /myapp/<MyModel:my_model>/ I get django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Where exactly am I supposed to put sync_to_async? If I do it in the converter like this @sync_to_async def to_python(self, primary_key): ... The converter outputs a coroutine object instead of a MyModel instance so I get AttributeError when I attempt to use it. AttributeError: 'coroutine' object has no attribute 'my_attribute' Am I supposed to await it in the view? That would defeat the purpose of using converters. I can just do get_object_or_404 instead. Is there a solution that doesn't involve setting DJANGO_ALLOW_ASYNC_UNSAFE to True? At this point, I'm considering refactoring everything away from the converters and using <int:mymodel_id> everywhere instead. Is there another way? -
how to make list of group by clickable django
i made a group by list of items based on two fields class Product(models.Model): type_of_product = models.CharField(max_length=30,default="electric) made_in = models.CharField(max_length=10,choices=countries,default="UK") product= models.CharField(max_length=30) views.py def categories(request): lists = Product.objects.values('type_of_product ', 'made_in').annotate( total=Count('pk') ).order_by('type_of_product ', 'made_in') return render(request,'shop/categories.html',{'lists':lists}) it returns something like this type_of_product : electric , made_in:UK , total:20 type_of_product : accessory , made_in:USA , total:23 and so on i want to make lists of categories clickable , when i click on one of them , it takes me to all products with the same features , for example i click on type_of_product : accessory , made_in:USA , total:23 it shows a list of products (23) item which made in from USA and type of product is accessory <div class="grid grid-cols-1 gap-6 pt-3 pt-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 "> {% for i in lists %} <a href="{% url 'the link to products list' %}" class="transition transform cursor-pointer duration-400 hover:scale-105 hover:shadow-xl"> <div class="h-32 overflow-hidden rounded-tl-2xl rounded-tr-2xl room"></div> <div class="items-center p-2 rounded-bl-xl rounded-br-xl bglightpurple"> <div class="text-center rounded-lg" style="background: #534e70;"> <p class="inline textorange "><i class="bi bi-columns-gap"></i></p> <p class="inline text-white">{{i.type_of_product}}</p> </div> <div class="flex flex-wrap items-center justify-between mt-4 text-white"> <div class="text-sm"> <p class="inline ">{{i.product}}</p> <p class="inline px-1 text-sm bg-yellow-500 rounded-lg">{{i.total}}</p> </div> <div class="text-sm"> <p class="inline px-1 text-sm … -
DRF post to model with a many-to-many field which may only accept values that already exist
I have the following models: class Tag(TimeStampModel): name = models.CharField(unique=True, max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) featured = models.BooleanField(default=False, blank=True) class Deal(VoteModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deals', on_delete=models.CASCADE) title = models.CharField(max_length=1024, blank=False, null=False) slug = models.SlugField(max_length=1024, unique=True, blank=True) description = models.TextField(blank=False, null=False) poster = models.ImageField(blank=True) tags = models.ManyToManyField( Tag, blank=True) And the following serializers: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['id', 'name', 'slug', 'featured', 'created_at'] class DealSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) tags = TagSerializer(many=True, read_only=True) tags_ids = serializers.PrimaryKeyRelatedField(many=True, write_only=True, queryset=Tag.objects.all()) class Meta: model = Deal fields = '__all__' Views class DealList(viewsets.ModelViewSet, VoteMixin): serializer_class = DealSerializer permission_classes = [IsOwnerOrAdminOrReadOnly] def get_queryset(self): return Deal.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) I am able to get the data and also post it, but because of the many-to-many field (tags), I seem to have some issues as a Deal may have tags that only exist (created beforehand, and cannot be created through a post request to the Deal). I send data as the following: { title: 'some title', all_other_fields: 'some data', tags_ids: [2, 4] } The tags are sent as an array of tag ids, but I get an error as the following: "Incorrect type. Expected pk value, received str." I only added … -
How to filter related model rows of a django model?
Currently all related objects are being returned. I want to restrict related objects in such a way if I try to get PortfolioUser's education, I only get which has the value show=True models.py from django.db import models from django.db.models import Q from django.db.models.signals import pre_save, post_save # Create your models here. class PortfolioUser(models.Model): GENDER_CHOICES = [ ("M", "Male"), ("F", "Female") ] first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=254) phone_number = models.CharField(max_length=50) gender = models.CharField(choices=GENDER_CHOICES, max_length=1, null=True, default='M') about = models.TextField(null=True, default="Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad, blanditiis optio. Quia, corporis quidem. Nam aliquam officia rerum consequatur nisi ducimus nihil saepe aut excepturi, accusantium aspernatur possimus quod error!") is_active = models.BooleanField(default=False) class Meta: verbose_name = ("PortfolioUser") verbose_name_plural = ("PortfolioUsers") def __str__(self): return self.first_name+" "+self.last_name def get_absolute_url(self): return reverse("PortfolioUser_detail", kwargs={"pk": self.pk}) class Education(models.Model): education_name = models.CharField(max_length=254) institute_name = models.CharField(max_length=254) start_year = models.DateField(auto_now=False, auto_now_add=False) end_year = models.DateField(auto_now=False, auto_now_add=False) marks = models.CharField(max_length=50) show = models.BooleanField(default=True) portfolio_user = models.ForeignKey( PortfolioUser, on_delete=models.CASCADE, related_name="educations") class Meta: verbose_name = ("Education") verbose_name_plural = ("Educations") def __str__(self): return self.education_name+" -"+self.portfolio_user.first_name def get_absolute_url(self): return reverse("Education_detail", kwargs={"pk": self.pk}) class Project(models.Model): project_name = models.CharField(max_length=50) about = models.TextField(null=False) website = models.CharField(max_length=100, null=True, blank=True) github = models.CharField(max_length=100, null=True, blank=True) thumbnail … -
How to skip dummy model from django test
I have created one django admin page which is associated with a dummy model which doesn't exists. Here is the code. The statistic model doesn't exists in database. class StatisticModel(models.Model): class Meta: verbose_name_plural = 'Statistic' class StatisticModelAdmin(admin.ModelAdmin): model = StatisticModel def get_urls(self): view_name = 'changelist' return [ path('settings/', my_custom_view, name=view_name), ] admin.site.register(StatisticModel, StatisticModelAdmin) In my git workflow I have below command, python backend/django/manage.py test ./backend/django Which is failing with error, django.db.utils.ProgrammingError: relation "monitor_statisticmodel" does not exist Please advise how can I avoid or skip this error? -
how do I rewrite the following in order to make it work with model manager?
I'm scraping some sites and loading the results into a Postgres in a management command that I will later convert to a celery task. how can I convert my pseudo function In order to create_or_update_if_diff which means it will only update if detect changes def create_or_update_if_diff(self, model, defaults=None, **lookup): """Helper function which is similar to update_or_create(), but will compare defaults to database entry and only update when there is any difference""" defaults = defaults or {} instance, created = model.objects.get_or_create(**lookup, defaults=defaults) if created: self.log_database_create(instance) return instance else: for key, value in defaults.items(): attr = getattr(instance, key) if attr != value: # If any change detected just update without checking other entries. model.objects.filter(**lookup).update(**defaults) self.log_database_update(instance) instance.refresh_from_db() return instance return instance ``` -
how to build a orm query where says if the model doesnt exist (object) add , but if exist then change the modified fields?
I am new with django framework , and I would like to know how to build the following query where I can perform insert operation when the object doesn't exist, but update modified fields if there is an object with the following id from demo.models import Person update_values = {"name": "Alice", "age": 12, "is_manager":False} new_values = {"name": "Bob", "age": 25, "is_manager":True} obj, created = Person.objects.update_or_create(identifier='id', defaults=update_values) if created: print(f"created {obj}") else: print(f"updated {obj}") note: I want to do it with a single method update_or_create than using two get_or_create + update_or_create -
how to send random get request to the API endpoint using request and time modules in python
how to send random get request to the API endpoint using request and time modules in python -
Heroku local server (django) only prints to console when I press Ctrl+C and quit the server for some reason?
So I downloaded the hello world/getting started django heroku project. It's been working fine, but I decided to experiment with webhooks. So I have this: def webhooks(request): print("here") return HttpResponse('Hello, world. This is the webhook response.') And what happens is when the webhook is visited I can see that it's getting a response and it's going through (by looking at ngrok, if that matters). But it doesn't print out "here". Once I press ctrl+c on my machine (mac) to shut down the local running of heroku, for some reason THEN it prints out "here". Even if I visit the webhook 5 times, it won't print anything until I press ctrl+c and start shutting down. Then, and only then, it prints out "here" 5 times. Then it says exited successfully have to press ctrl+c again to fully quit not sure why. Here's what it prints below but I'm not sure if it helps. vv +0000] [17890] [INFO] Worker exiting (pid: 17890) 1:10:21 PM web.1 | here 1:10:21 PM web.1 | here 1:10:21 PM web.1 | here 1:10:21 PM web.1 | [2021-06-19 13:10:21 -0400] [17888] [INFO] Shutting down: Master 1:10:21 PM web.1 Exited Successfully -
User logged in using LDAP doesn't get logged out even after logging out using the default logout feature provided by django
The application is Django 2.2 based and allows users to login via Apache using Active Directory and LDAP. User is able to log in via the browser pop-up/modal (image shown below). Issue is when the user logs out, the user is actually still logged in and can access the application. The application uses the default logout functionality from django.contrib.auth. I'm working on creating a custom logout function that would delete the session data for currently logged in user. I have come out with the following, from django.contrib.sessions.models import Session from django.contrib.auth.models import User def logout_user(request): username = request.user.username logged_in_user = User.objects.get(username=username) for session in Session.objects.all(): session_data = session.get_decoded() if session_data.get('_auth_user_id') == logged_in_user.id: session.delete() I'm not sure if I'm going in the right direction or is there a better solution to this. Thanks for any help you can offer! -
How to set bounds to django leaflet map?
In my django app I have a CenterModel with a location (Point) field and a RouteModel with a geom (Linestring) field. I am using django-leaflet to represent those geometric fields in the views (UI). I can represent those fields, but in the general settings I had set the default center and zoom for every leaflet map, so when i represent the center or the route I have to zoom out amd move the map to see the marker and the line, Is there any way to set the bounding box of the map to see the point or the line without having to zoom out and move the map? The point is represented outside this area and I have to zoom out I have try with: map.setBounds(datasets.getBounds()); but it shows the error that the setBounds method does not exist Here is my code: This is how I represent the route: In the template: <div class="row"> {% leaflet_map "gis" callback="window.our_layers" %} </div> <script type="text/javascript"> function our_layers(map,options){ var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:route_locate' route.id %}" ,{}); datasets.addTo(map); // this is showing an error map.setBounds(datasets.getBounds()); } </script> #the ajax views @login_required(login_url='/login/') def route_get_location(request,pk): route=serialize('geojson',RouteModel.objects.filter(id=pk)) return HttpResponse(route,content_type='json') representing the center in other template <div … -
Django: TypeError, when i try to create new user gives auth group error
I'm still learning Django. When I try to create a new user I get this error: I use Django rest framework and Djoser. I have a simple serializer that I only define the fields, and I put it in Djoser settings. I put my model "accounts" as AUTH_USER_MODEL and is a model changed from AbstractUser. If you need me to put more things here, say it. -
Mocking a class method in Python
Say I have the following: # maincode.py from othermodule import do_something class Myclass(): @staticmethod def return_array(): array_result = do_something() return array_result @classmethod def main(): array_result = cls.return_array() # Test.py # import necessary libraries for mocking class Test: @mock.patch('maincode.Myclass.return_array', autospec=True) def test(self, mock_return_array): mock_return_array.return_value = ["value1"] Myclass.main() However, I am getting TypeError: 'NonCallableMagicMock' object is not callable My mock.patch argument points to the correct place, however when I do print(cls.return_array) in main() I'm getting: <NonCallableMagicMock name='get_exposed_commands' spec='classmethod' id='________'> Any suggestions on how to fix this? Thanks -
Another user is not adding in the Banned Members
I am building a Blog Group App, In which users can make group about blogs and only one admin. Admin ban the members. BUT when i try to ban a user then it is saving some other user. Like there are 2 users and when i try to ban user_1 then user_2 is saving. AND sometimes it says Page Not Found(404). AND then i reset my database. Sometimes it says Group object query doesn't exist. I have no idea what is wrong in the code, I have tried many times but failed. models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) class GroupPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') views.py def bans(request,pk): group = get_object_or_404(Group,pk=pk) post = get_object_or_404(GroupPost,pk=pk) group.banned_members.add(post.user) return redirect('home') def GroupDetailView(request,pk): data = get_object_or_404(Group,pk=pk) posts = data.grouppost_set.order_by('-date_added') context = {'data':data,'posts':posts} return render(request, 'detail_group.html',context) urls.py path('bans/<int:pk>/', views.bans, name='bans'), detail_group.html {% for pos in posts %} <a href="{{ pos.get_absolute_url }}">{{ pos.post_title }}</a> <b>User :</b>{{ pos.user }}<a href="{% url 'bans' user.id %}">BAN</a> {% endfor %} I am trying to ban user I have no idea what i am doing wrong. Any help would really be Appreciated. Thank You in Advance. -
Module "whitenoise.storage" does not define a "CompressedMainfestStaticFilesStorage" attribute/class
I'm using whitenoise to serve static files in my Django project. Here is the settings.py STATIC_URL = 'data/static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'data/static/'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have my static files in data/static folder. When I try to run python manage.py collectstatic after commenting this line: STATICFILES_STORAGE = 'whitenoise.storage.CompressedMainfestStaticFilesStorage' It runs fine. But when I try to run collectstatic after uncommenting this, it gives the above error. Anyone has any idea as to why is this an error? Here are the apps and middleware: INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And I have tried setting Debug to True and False but it doesn't work in either cases with compression on. -
how to make a query based on another existing query which made with group by in django
i trying to make a query based on selected category , for example i have a hotel website , i made a query to display category of rooms family = 'family' single = 'single' room_types = ( (family , 'family'), (single , 'single'), ) class Room(models.Model): room_no = models.IntegerField(unique=True) beds = models.IntegerField(default=2) balcon = models.BooleanField(default=False) room_type = models.CharField(max_length=15,choices=room_types,default=single) i made this query for displaying room categories , and i want to make each unique value a link and clickable , to go to that category room lists def categories(request): lists = Room.objects.values('room_type', 'beds', 'balcon').annotate( total=Count('pk') ).order_by('room_type', 'beds', 'balcon') return render(request,'rooms/categories.html',{'lists':lists}) <div class="grid grid-cols-1 gap-6 pt-3 pt-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 "> {% for i in lists %} <a href="{% url to go to list of rooms based on that category %}" class="transition transform cursor-pointer duration-400 hover:scale-105 hover:shadow-xl"> <div class="h-32 overflow-hidden rounded-tl-2xl rounded-tr-2xl room"></div> <div class="items-center p-2 rounded-bl-xl rounded-br-xl bglightpurple"> <div class="text-center rounded-lg" style="background: #534e70;"> <p class="inline textorange "><i class="bi bi-columns-gap"></i></p> <p class="inline text-white">{{i.room_type}}</p> </div> <div class="flex flex-wrap items-center justify-between mt-4 text-white"> <div class="text-sm"> <p class="inline ">{{i.beds}} beds</p> <p class="inline px-1 text-sm bg-yellow-500 rounded-lg">{{i.total}}</p> </div> <div class="text-sm"> <p class="inline px-1 text-sm bg-green-500 rounded-lg">{{i.balcon}}</p> </div> </div> </div> </a> {% endfor %} </div> i'm … -
django url pattern "The empty path didn't match any of these."
I am trying to configure static files for django v2.2.1 following this https://docs.djangoproject.com/en/2.2/howto/static-files/ In settings.py: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In urls.py: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project directory: But I'm getting this error when running localhost:8000 I've been scratching my head for too long. What am I missing here? -
Issue in display media preview in sharing the link in Javascript code for Django project
I am using below code snippet in my media gallery project : {% block head %} <meta property="og:title" content="{{image.title}}"> <meta property="og:image" content="{{ image.file.url }}"> <meta property="og:description" content="{{ image.description }}"> {% endblock %} But, when i am sharing the link on social media, i am only seeing the description of image and not the image preview . Attached is the screenshot. Screenshot of image link share to facebook Please help. -
Djnago QuerySet: distinct() work for one field, but don't work for enother
I have QuerySet with two fields: ```Python print(products_mtm) <QuerySet [ {'fk_products': 2653, 'fk_classes': 20}, {'fk_products': 2653, 'fk_classes': 23}, {'fk_products': 2653, 'fk_classes': 29}, {'fk_products': 2654, 'fk_classes': 20}, {'fk_products': 2654, 'fk_classes': 21}, {'fk_products': 2654, 'fk_classes': 24}, {'fk_products': 2655, 'fk_classes': 20}, {'fk_products': 2655, 'fk_classes': 25}, ....] print(products_mtm.values_list('fk_products').distinct()) <QuerySet [(2653,), (2654,), (2655,),...] # It's OK! print(products_mtm.values_list('fk_classes').distinct()) <QuerySet [(20,), (23,), (29,), (20,), (21,), (24,), (20,) (25,)...] #It does't DISTINCT it is full values_list of the 'fk_classes' ``` -
Django forms with classbased view
I am using class-based views for my forms but I'm not using Crispy forms instead I'm using these to submit my form- views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = post fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and post-form.html: {% extends "blog/base.html" %} {% block content %} <main> <div class="container"> <div class="row"> <div class="col-md-8 my-5"> <div class="content-section" style="padding:10px 20px"> <form method="POST" enctype='multipart/form-data'> <fieldset class="form-group"> {% csrf_token %} <fieldset> <label for="content">Name:</label> <input type="text" id="content" name="content"> </fieldset> <button type="submit">Sign Up</button> </form> </div> </div> </div> </main> Now my question is is it safe to use in this way. Can it handle multiple requests for a production environment? -
Django oscar - customizing StockRecordForm form
I am trying to customize StockRecordForm in django-oscar administration. What I have: Forked dashboard app, also catalogue_dashboard Included new StockRecord attribute in models.py Updated forms.py like this: class StockRecordForm(base_forms.StockRecordForm): class Meta(base_forms.StockRecordForm.Meta): fields = [ 'partner', 'partner_sku', 'price_currency', 'price', 'num_in_stock', 'low_stock_threshold', 'new_attribute', ] from oscar.apps.dashboard.catalogue.forms import * Part of my INSTALLED_APPS looks like this: #'oscar.apps.dashboard.apps.DashboardConfig', #'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'mikeapps.dashboard.apps.DashboardConfig', 'mikeapps.dashboard.catalogue.apps.CatalogueDashboardConfig', But modification is not showing up. Is there anything else I should modify?