Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get a list of related objects in model's __str__
I have two models with One-to-Many relationship; Listing, and Bids. Is it possible to retrieve and display a list of Bid objects' bid_price in Listing's str method? The code provided below crashes the server and I am not sure of the correct keywords to search for. I understand how listing.bid_set works in the Shell or view, but I am not sure how to make it work here. class Listing(models.Model): title = models.CharField(max_length=64) def __str__(self): bid_objects = Bid.objects.all().filter(listing__id=self.id) price_list = [] for bid_object in bid_objects: price_list.append(bid_object.bid_price) return f"{self.title}, {price_list}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids") bid_price = models.DecimalField(max_digits=6, decimal_places=2) Thanks for your help. -
Django - Add Nearest Monday to Queryset
I have an Order model like so: class Order(models.Model): created_at = models.DateTimeField(...) An order can be created at any time, but all orders get shipped out on the following Monday. How can I add an extra field to my orders queryset called assembly_date that reflects the next Monday (date the order should be shipped)? I tried creating a custom OrderManager like so, but am not sure how to correctly set the assembly_date: class OrderManager(models.Manager): def get_queryset(): return self.super().get_queryset().annotate( assembly_date = ... # need help with logic here ) Keep in mind, I want to be able to filter all orders based on their assembly_date. -
Can't install mysqlclient in CentOS 7
First of all... not, it's not a repeated thread. Believe me, I read all similar threads and tested all answers before post this. I just have a new CentOS 7 server installation, with basic configuration (the same I used several times before, but magically, this time does not work) yum -y update yum -y groupinstall development yum -y install gcc yum -y install zlib-devel yum -y install openssl-devel rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm yum -y install mariadb-devel Python3.6 yum -y install python36 yum -y install python36-devel However, once I create my virtual environment with: python3 -m venv test and try to install mysqlclient using pip... Simply doesn't work. The error I have is: ERROR: Command errored out with exit status 1: command: /var/www/test/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pn9v4w46/mysqlclient_d62f41676e4049d6a292a9525c56d5c9/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pn9v4w46/mysqlclient_d62f41676e4049d6a292a9525c56d5c9/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-7ethj5wf/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/test/include/site/python3.6/mysqlclient cwd: /tmp/pip-install-pn9v4w46/mysqlclient_d62f41676e4049d6a292a9525c56d5c9/ Complete output (31 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying … -
how to render response in parent window instead of popup
I have a template that shows a list of items. When you click to edit one of the items, it will be opened in a popup window. However, if there is an error when processing in the view to display that popup, I am returning the result used to create the parent 'list' page but with an error message. That displays the parent page again in the popup window with the error, so I know that part works. In this case though, I would like to close the popup window, before it displays anything, and have the response displayed on the parent tab. Is this possible? -
Can you use a regular expression in a Django template conditional?
Is it possible to determine if a template variable in a Django template satisfies a regular expression? In the following template, I want to set the CSS class for the paragraph tag that contains the help text based on whether or not the help text for that field satisfies a regular expression. Here is the template with some pseudocode thrown in: {% for field in form.visible_fields %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} {% if field.help_text|lower (BEGINS WITH SOME STRING) %} # Pseudocode <p class="select-help-text">{{ field.help_text|safe }}</p> {% else %} <p class="help-text">{{ field.help_text|safe }}</p> {% endif %} {% endif %} </div> {% endfor %} For example, if the help_text as defined in the associated form starts with the text string "Hold down Ctrl", then the CSS class should be set to select-help-text, otherwise it should just be set to help-text. I understand that Django regular expressions are based on Python regexes, but Python regex evaluations always seems to be done using the re module which isn't accessible in a Django template. I also looked through the Django documentation but couldn't find a way to do this. -
I want to filter the def 'getAmountRating(self):' function
I built the class Restaurant where you can find the 'def getAmountRating(self):' function. This function should be used as a keyword in my django_filter. class Restaurant(models.Model): restaurant_picture = models.ImageField(null=True, default='dashboard-BG.jpg') name = models.CharField(max_length=200, null=True) address = models.CharField(max_length=128, blank=True) houseNumber = models.IntegerField(default=1) city = models.CharField(max_length=64, default="") state = models.CharField(max_length=64, default="") zip_code = models.CharField(max_length=5, default="86444") tags = models.ManyToManyField(Tag) affordability = models.FloatField(validators=[MaxValueValidator(3), MinValueValidator(1)], null=True) objects = models.Manager() def getAverageRating(self): comments = Comment.objects.all() avg = 0 count = 0 for i in comments: if i.restaurant == self: avg += i.ratings if count is 0: count += 1 else: avg = avg / 2 if avg is not 0: avg = round(avg) return avg In the filter class RestaurantFilter(django_filters.FilterSet): rating = NumberFilter(field_name="getAverageRating", lookup_expr="gte") class Meta: model = Restaurant fields = '__all__' exclude = ['location', 'restaurant_picture', 'address', 'houseNumber', 'state'] I already had to accept that this is not working as I'd like to. As a fix I looked up some solutions but those solutions did not work. For example I built an other class containing the def getAverageRating function and referenced this class in Restaurant as a - averageRating = RestaurantRating() - which did not work. I don't think its relevant but here is the views.py … -
Why am I getting a Django NoReverseMatch error?
I am trying to send an activation email to users when signing up, but I keep getting a NoReverseMatch error when trying to render the URL in the template. The error I get is: Reverse for 'user_activation' with keyword arguments '{'uidb64': 'MiC', 'token': 'aeue9g-3a31bdff969c41c0bb1d3775a1fa98ac'}' not found. 1 pattern(s) tried: ['account/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] urls.py from .views import * from django.urls import re_path urlpatterns = [ re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', user_activation_view, name='user_activation'), # user activation view ] template.txt {% autoescape off %} To activate your account ({{ user.email }}), please click the link below: {{ protocol }}://{{ domain }}{% url 'user_activation' uidb64=uid token=token %} If clicking the link above doesn't work, you can copy and paste the URL in a new browser window instead. If you did not make this request, please ignore this email. {% endautoescape %} -
Django: How do I print values from a checkbox to a new template?
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button on the bottom of the page to purchase those items. The problem I am struggling with is how to take the selected values from the checkboxes and print them onto a different page. """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=products) a.quantity = a.quantity -1 a.save() print(products) return redirect('list') urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'inventory' %}" method="POST" id="menuForm"> {% csrf_token %} {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title … -
Django ORM - Aggregate by Decorator
I am trying to use the Django ORM to aggregate by a field and SUM up the value returned by a decorator. I'm new to the Django ORM so forgive me if I'm missing something. Here is my class: class Payroll(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) ClockIn = models.DateTimeField() ClockOut = models.DateTimeField(null=True, blank=True) @property def time_worked(self): return self.ClockOut - self.ClockIn I want to aggregate by user, and sum up the time_worked decorator. If I were writing the SQL myself it would be: SELECT user, SUM(time_worked) FROM payroll GROUP BY user When I try users_time_worked = Payroll.objects.aggregate(Sum('time_worked')) the page crashes and the Django debug screen says: "Cannot resolve keyword 'time_worked' into field." Is it possible to sum a timdelta field created by a decorator using the Django ORM? Is this something I should calculate within the view? -
Is it intensive to get a model instance's property in Django
I am new to Django and have the following model: Person: - height - weight - name In one of my functions, I get person.height 5 times. Would it be better (from a computation perspective) to just store height = person.height and reference that? -
Django logging errors occuring in admin page [closed]
I face the following issue: I want to add a new instance of a model in the django admin page, but I do get an 500 error. I works for all other models, but not that specific one. Therefore I want to log errors occuring in the djnago admin page. I do know how to log for all non admin views. I could not find any documentation on how to get the logs of the admin page. Is there a way to get the logs of all errors in the admin page ? Thanks for any advice! -
Static files are not loading after deployment on digitelocean
I have deploye my django application on digitel ocean by following this blog:alocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 this is the url as an error i am getting in console for static files (index):5913 GET http://67.205.160.21/static/js/dashkit.min.js net::ERR_ABORTED 403 (Forbidden) (index):5913 GET http://67.205.160.21/static/js/style.js net::ERR_ABORTED 403 (Forbidden) every thing is fine except static file, settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') after running the python3 manage.py collect static it gives this /home/podstatsclub/webapp/Podcast_stats/static which i have put into default.config file which look something like this Alias /static /home/podstatsclub/webapp/Podcast_stats/static <Directory /home/podstatsclub/webapp/Podcast_stats/static> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/podstatsclub/webapp/Podcast_stats/podcast> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Podcast_stats python-home=/home/podstatsclub/webapp/Podcast_stats/env pytho> WSGIProcessGroup Podcast_stats WSGIScriptAlias / /home/podstatsclub/webapp/Podcast_stats/podcast/wsgi.py -
Django framework list all products and sum all sales for each
Models.py class Entity(models.Model): entity = models.CharField(max_length=40) class Period(models.Model): period = models.CharField(max_length=10) class Product(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, default=None, blank=True, null=True) period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True) sku = models.CharField(max_length=12) class Sale(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None, blank=True, null=True) price = models.DecimalField(max_digits=11, decimal_places=2) Views.py if request.method == 'POST': if form.is_valid(): entityquery = form.cleaned_data['entity'] periodquery = form.cleaned_data['period'] entities = Entity.objects.get(entity=entityquery) periods = Period.objects.get(period=periodquery) products = Product.objects.filter(entity=entityquery, period=periodquery).values('id', 'period', 'entity', 'sku') for sales in products.iterator(): sales = Sale.objects.filter(product__sku=product.sku, product__entity=entityquery, product__period=periodquery).aggregate(Sum('price')) return sales args = {'form': form, 'products': products, 'periods': periods, 'entities': entities, 'sales': sales} return render(request, "products_list.html", args) Expected Result So far I am able to list all the SKU items that were sold based on the criteria (Period and Entity). Lets assume SKU 12 has two sales $10 and $30 and SKU 23 has three sales $5, $5 and $6 and I need to show the total sales for each of those products. Input Entity: Company XZY Period: November Output SKU Total Sales 12 40.00 23 16.00 -
How to insert product data in all related table in django using serializers
I'm using Django REST framework, I'm stuck in Inserting related product data in multiple table. Please refer the scenario below: In AddProductSerializer, I want to pop again inside variations for loop in else part in nested django serializer so that i can save all the data related to product table. Json Data { "category": 15, "images": [ {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": true}, {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": false} ], "keywords": "related keywords", "long_description": "<p>l</p>", "mrp_price": "120", "selling_price": "908", "short_description": "<p>k</p>", "sku": "Sam-009", "stock": "7", "title": "Samsung", "have_variations": true, "variant": "Size-Color", "slug": "samsung-phone", "variations": [ { "image_url": "https://images/607679417554_0f32f124a14b3e20db88e50da69ad686.jpg", "mrp_price": 68, "selling_price": 86786, "sku": "iuy", "stock": 68768, "title": "hkj", "color": { "name": "red" }, "size": { "name": 9 } }, { "image_url": "https://images/607679434082_0392bab5c6a3ec64552ea57aa69852a5.jpg", "mrp_price": 67, "selling_price": 6876, "sku": "hkjh", "stock": 868, "title": "yiui", "color": { "name": "blue" }, "size": { "name": 9 } } ] } Serializer.py # List images class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('image_url', 'main_image',) # List variations class VariationSerializer(serializers.ModelSerializer): class Meta: model = Variation fields = ('title', 'stock', 'mrp_price', 'selling_price',) # List sizes class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = ('name',) # List sizes class ColorSerializer(serializers.ModelSerializer): class Meta: model = Color fields = ('name',) # Add … -
Django group manager getting each member roles
I have installed django_group_manager and I defined some members then allocated some roles from django admin panel. Now I want to print all member roles but can't: >>> from groups_manager.models import Group, GroupType, Member >>> member = Member.objects.get(username='myuser') >>> member <Member: test user> How can I print each member roles? -
Django model, saving objects
I'm developing a small exchange system and I want to give everyone who joins this app a random amount (1-10) of btc. When someone compiles the register form succesfully, recives a random amount of Btc in the wallet. That is my code but doesn't work models.py class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) wallet = models.FloatField() class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) price = models.FloatField() quantity = models.FloatField() views.py def registerPage(request): bonus = randint(1,10) form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.wallet = bonus form.save() return redirect('login') contex = {'form':form} return render(request, 'app/register.html', contex) forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] I don't know if is't important but I'm working with Mongodb. Thanks -
Django, admin page
I have a problem with achieving this functionality: An administrator must be able to view data for a specific user group in the administration page, how could I do this in my django project? Thank you in advance for your answers -
New client on Django Channels chat reloads data for other user as well
I am trying to implement a chat application using Django Channels via WebSockets. However, every time a client (One user from a private chat refreshes or joins the chat, the data for the other user gets updated again. Below is my connect method for my websockets: def connect(self): self.user = self.scope['user'] self.room_id = self.scope['url_route']['kwargs']['room_id'] user1 = Profile.objects.get(username = self.user.username) if PrivateChat.objects.filter( Q(user1 = user1, guid=self.room_id) | Q(user2=user1, guid=self.room_id) ).exists(): self.room = PrivateChat.objects.filter( Q(user1 = user1, guid=self.room_id) | Q(user2=user1, guid=self.room_id) )[0] self.room_group_name = 'chat_%s' % str(self.room.guid) self.messages_pre_connect_count = self.room.get_messages_count() async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() Now I have a fetch messages method: def fetch_messages(self, data): if data['username'] == self.user.username: room = PrivateChat.objects.get(guid=data['room_id']) messages, has_messages = room.get_messages() self.messages_all_loaded = not has_messages result = [] if len(messages) > 0: for message in messages: json_message = { 'id':message.id, 'author':message.author.username, 'content':message.content, 'timestamp':message.get_time_sent(), 'is_fetching':True, } result.append(json_message) content = { 'command':'messages', 'messages': result } if self.messages_all_loaded and len(messages) > 0: content['first_message_time'] = room.get_first_message_time() self.send_chat_message(content) Which is called via javascript using: chatSocket.onopen = function(e) { fetchMessages(); } function fetchMessages() { chatSocket.send(JSON.stringify({ 'command':'fetch_messages', 'room_id':roomName, 'username': username }) ); } How can I avoid this issue. I currently have one user on Safari and one user on Chrome and when either … -
Django keeps making old db schema
I have deleted one column from my model. Then I deleted database, migration files, venv direcotry, and pycache. But after executing makemigrations the old db schema is generating ( it still contains this column). What is the problem. How django knows about this column. It's no longer present in data model. -
Python Django - Issue w/ View Request
I am building a test application using Django framework written in Python. I am trying to ask a question, have the user answer the question, then get the results of the User's selected answer. I am having an issue with the retrieving what the User has selected. models.py class Question(models.Model): passage = models.ForeignKey(Passage, on_delete=models.CASCADE) questions_text = models.CharField(max_length=400) def __str__(self): return self.questions_text class Choice(models.Model): correct_choices = ( ("Correct", "Correct"), ("Incorrect", "Incorrect"), ) question = models.ForeignKey(Question, on_delete=models.CASCADE) explain = models.ForeignKey(Explanation, on_delete=models.CASCADE, default="") choice_text = models.CharField(max_length=200) correct = models.CharField(max_length=10, choices=correct_choices, default='Incorrect') answer = models.CharField(max_length=500, default='') def __str__(self): return self.choice_text def check_answer(self, choice): return self.choices_set.filter(id=choice.id, is_answer=True).exists() def get_answer(self): return self.choices_set.filter(is_answer=True)''' views.py def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Sorry, Question does not exist") return render(request, 'index/details.html', {'question': question}) def result(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'index/results.html', {'question': question}) def answer(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_answer = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'index/details.html', { 'question': question, 'error_message': "Please make a Valid Selection.", }) else: selected_answer.save() return HttpResponseRedirect(reverse('results', args=(question.id,)))''' results.html <h1>Passage / Equation:</h1> <p>{{ question.passage }}</p> </div> <div class="column" style="background-color:#bbb;"> <h1>Answer for Question: </h1> <h1>{{ question.questions_text }}</h1> <p>Your Choice was: **{{ choice.selected_answer … -
How to know if you are connecting two sockets to same group of channel-layer in django channels
I am actually trying to build a system wherein two entities(being doctor and patient) can share the same data over websockets using django. The way I have setup my channels is sending the auth-token through query_string in the websocket protocol The models are configured in the following fashion the patient model also has an attribute called "grp_id" grp_id = models.UUIDField(default=uuid.uuid4, editable=False) The consumers.py file is • Working for patient make a connection request by sending auth token through query-string which will authenticate the user since the user is patient, the grp_id of the patient is fetched A channel is created using the grp_id value The patient triggers the start_sepsis function which would receive a set of sepsis-attribute, then serialize it and store it it in DB The same serialize data is broadcasted over the channel • Working for doctor authentication like above the doctor fetches patients associated to them using _get_patient_of_doctor helper function doctor will try to connect all the patient's grp_id associated to it Once connected broadcast a message called "doc is connected" class SepsisDynamicConsumer(AsyncJsonWebsocketConsumer): groups = ['test'] @database_sync_to_async def _get_user_group(self, user): return user.user_type @database_sync_to_async def _get_user_grp_id(self, user): #************** THE grp function initiated ************** print("THE USER obj", user)#output below … -
An overview of using Tailwind CSS with Django?
I was looking for some overview information on using Tailwind CSS with Django. I found this excellent thread, and I followed the first answer to install Tailwind ready for use with Django: How to use TailwindCSS with Django? I understand that Tailwind is a CSS framework, that will help you manage your CSS/rendering and related resources. But I am confused as to how Tailwind and Django can fit together. For example: What is the purpose of the PyPi project django-tailwind, and is it necessary? How does Tailwind fit in with Django forms and the render as "p" or render as "table", i.e. is there an alternative way to style Django forms, or will Tailwind work well with these? Any other "overview" information on this topic? -
Django / Ajax : How to filter a form field's queryset asynchronously?
In a given Django form view, I'd like to filter a field's queryset by an option a user has selected while viewing the form. And I'd like that to happen asynchronously. I've read that AJAX might be what I should use, but I know very little of JS, and I can't make much sense of the information I've read. The way I see it, I'd like a user to be able to click on one or more checkboxes that would filter 'loot.item_name' by 'item.in_itemlist' or 'item.item_type' (automatically, using onChange or onUpdate or smth?). Would someone kindly give me some pointers? Cheers, Here are my models: ***models.py*** class Itemlist(models.Model): name = models.CharField([...]) class Item(models.Model): name = models.CharField([...]) item_type = models.CharField([...]) in_itemlist = models.ForeignKey(Itemlist, [...]) class Loot(models.Model): item_name = models.ForeignKey(Item, [...]) quantity = [...] my view, ***views.py*** def create_loot(request): # LootForm is a simple ModelForm, with some crispy layout stuff. form = LootForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() [...] return render(request, 'loot_form.html', context={'form': form} and the template, ***loot_form.html*** {% extends "base_generic.html" %} {% block leftsidebar %} /* for each unique itemlist referenced in the items, */ /* make a checkbox that once clicked, filters 'loot.item_name' by the selected … -
Django views.py : unable to use vriable outside function
I want a new page to open when a django form is filled- by hitting enter/by clicking on the 'Search' input and display results in that page using the data entered in the form. forms.py: class SearchBar(forms.Form): Search = forms.CharField(label='', max_length=100, widget=forms.TextInput) The HTML page with the form looks like: index.html <form class="" action="result" method="post"> {% csrf_token %} {{ form1.as_table }} <input class="Search" type="submit" name="" value="Search"> </form> I want the submission of this form to open a new page: result.html I have set the url of 'result' to the said HTML page: urls.py urlpatterns=[ path('result', views.result, name='result'), ] I have extracted the data entered in the from by form1.cleaned_data['Search']. form_input=form1.cleaned_data['Search'] However, once the result page is opened, it shows that the data (form_input) is not defined. The following error is shown: name 'form_input' is not defined I am unable to use this data (form_input) in any other function of the views.py file. views.py def index(request): form1 = forms.SearchBar() if request.method == "POST": form1 = forms.SearchBar(request.POST) if form1.is_valid(): global form_input form_input= (form1.cleaned_data['Search']) def result(request): print(form_input) I don't understand why this is happening. I have even declared the variable form_input as a global variable. -
Local variable x referenced before assignment - Django
I must get data value from POST request and write it to Word document. But I'm getting error. How can I fix the problem ? def military_document(request): if request.method == 'POST': form = CreateMilitaryDocumentForm(request.POST, request.FILES, use_required_attribute=False) if form.is_valid(): group_degree = request.POST.get('group_degree') print(group_degree) form.save() messages.success(request, 'Added successfully !') return HttpResponseRedirect('military_document') else: form = CreateMilitaryDocumentForm(use_required_attribute=False) doc = DocxTemplate("../document.docx") context = { 'form': form, 'group_degree': group_degree, } doc.render(context) doc.save("generated_doc.docx") return render(request, 'military_document.html', context)