Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python requests not recognizing params
I am requesting to mindbodyapi to get token with the following code using requests library def get_staff_token(request): URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue" payload = { 'Api-Key': API_KEY, 'SiteId': "1111111", 'Username': 'user@xyz.com', 'Password': 'xxxxxxxx', } r = requests.post(url=URL, params=payload) print(r.text) return HttpResponse('Done') gives a response as follows {"Error":{"Message":"Missing API key","Code":"DeniedAccess"}} But if I request the following way it works, what I am doing wrong with requests library conn = http.client.HTTPSConnection("api.mindbodyonline.com") payload = "{\r\n\t\"Username\": \"username\",\r\n\t\"Password\": \"xxxxx\"\r\n}" headers = { 'Content-Type': "application/json", 'Api-Key': API_KEY, 'SiteId': site_id, } conn.request("POST", "/public/v6/usertoken/issue", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -
How can I display Error Messages for the logging funtion in Django?
I am a new Django Developer, and I have some trouble with the login function. My problem is that my system does not show error messages even though it is invalid. I try to enter the wrong username and password, and I expect there are some error messages displayed. However, it does not work. Here is my code: login_register.html <div class="login-form"> <form action="" method="POST"> {% csrf_token %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} {% endif %} <h2 class="text-center">Sign in</h2> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <span class="fa fa-user"></span> </span> </div> <input type="text" class="form-control" name="username" placeholder="Username" required="required" /> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-lock"></i> </span> </div> <input type="password" class="form-control" name="password" placeholder="Password" required="required" /> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary login-btn btn-block"> Sign in </button> </div> <div class="clearfix"> <a href="{% url 'reset_password' %}" class="text-center" >Forgot Password?</a > </div> </form> <p class="text-center text-muted small"> Don't have an account? <a href="{% url 'register' %}">Register here!</a> </p> </div> view.py def loginUser(request): page = 'login' if request.user.is_authenticated: return redirect('starting-page') if request.method == 'POST': username … -
XOR showing same value after 17 characters in python
Am trying to encrypt a integer for hiding primary keys in URLs of Django. So after research I found that encrypting "int" can be done using XOR! So I thought of trying those for example: id = 1 masked_id = id ^ 0xABCDEFAB unmasked_id = masked_id ^ 0xABCDEFAB print(masked_id) //2882400170 print(unmasked_id) //1 The above works well until the id character count reaches to 10. For example check below Output: When id character count is greater than 10, id = 11111111111 masked_id = 1032582764 unmasked_id = 2521176519 Its weird that, the output is not as expected when it crosses 10 count. So how this works and how to fix this ? Is there any way to encrypt int (pk) form database ? -
How to request existing files from a form in django
i'm trying to add a feature for users to update thier profile, but i want to be able to get thier existing informations so they don't have to fill all the form again. I have tried request.POST on the form but it doesn't work, it does not update the form with the existing user informations. views.py def profile_update(request): info = Announcements.objects.all() categories = Category.objects.all() Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('userauths:profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) # profile update function def profile_update(request): info = Announcements.objects.all() categories = Category.objects.all() Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('userauths:profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) -
Django AttributeError: 'int' object has no attribute 'pk'
I am stuck :(. I have an API that I can't seem to get working with the DRF. I am forming my queryset in my view and the result that I want is coming out in the console: web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 5, 'periodic_sell_period': 10, 'month': datetime.datetime(2021, 11, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('1.2300000000')} web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 2, 'periodic_sell_period': 14, 'month': datetime.datetime(2021, 12, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('7.4200000000')} web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 13, 'periodic_sell_period': 11, 'month': datetime.datetime(2021, 12, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('100.9600000000')} I can see that the obj gets passed into my serializer, but for the life of me I can not understand where I am going wrong. Here is my view.py class TopHistoricalGainViewSet(viewsets.ModelViewSet): queryset = TopHistoricalGains.objects.all() twelve_months_ago = datetime.datetime.now()+relativedelta(months=-12) serializer_class = TopHistoricalGainsSerializer def get_queryset(self): ids = self.queryset\ .values('id')\ .order_by('company_exchange__id') twelve_months_ago = datetime.datetime.now()+relativedelta(months=-12) hg_list = TopHistoricalGains.objects.filter(id__in=ids, periodic_date_time__gte=twelve_months_ago) hg_list = hg_list\ .annotate(month=TruncMonth('periodic_date_time')) \ .values('month') \ .annotate(periodic_sum=Sum('periodic_gain_max')) \ .values('company_exchange', 'company_exchange__company__name', 'company_exchange__stock_symbol', 'month', 'periodic_sum', 'strategy', 'periodic_buy_period', 'periodic_sell_period') \ #.order_by('company_exchange', '-periodic_sum', 'strategy', 'periodic_buy_period', 'periodic_sell_period')[:10] for hg in hg_list: print(hg) return hg_list class Meta: ordering = ['periodic_sum', … -
How to get the user id of the currently connected account in models.py
I want to give a condition by distinguishing when the user.id of the Leave object and the user id of the current access account are the same and when they are not. The original get_html_url function only had a 'self' argument. If 'request' is added to the argument to get the user id of the currently connected account, the error get_html_url() missing 1 required positional argument: 'request' occurs. It seems that I need to add request to utils.py to fix the error. But I don't know which function to add. Help. [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self, request -----> dAre there any errors?): url = reverse('leave:leave_edit', args=(self.id,)) user = request.user.id -----> Are there any errors? if self.kind == 'Annual' and self.user.id == user: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name}</a></div>' elif self.kind == 'Half' and self.user.id == user: return f'<div class="Half-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Holiday' and self.user.id == user: return f'<div class="Holiday-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id … -
how i create box like recent action admin menu django
how can I create the recent actions box in Django admin? pic -
How to pass and interpret a complex render context in Django?
I'm pretty new to Django and am not sure if I'm approaching this problem correctly. My view code generates a many to many map. So something like {'penguin' : ("bird", "black", "flightless", "arctic")}, {'axolotl' : ("reptile", "green")} {'rhino' : ("mammal", "horn", "heavy")} and so on... for a lot of different procedurally generated animals Out of this I'm trying to render page that would just have the animal's name and underneath it a few bullet points with the characteristics, like this Penguin bird black flightless and so on for every animal. The number of these animals and the descriptions are unknown and are parsed at runtime from an xml file I thought I could just pass this structure into the template and use the template language to iterate over it and render it out, but so far I feel like I'm having to jump through hoops, so I'm not sure if I'm doing something wrong or if this is just outside the scope of Django and I should be using a different framework for this kind project. The problems I'm running into: I'm having issues figuring out how to even pass this structure into the context and have it available for … -
Setting up simple Django ViewSet APIs from multiple apps
I’m still learning django and assume this may be easy for some. I’m trying to figure out the best way of simply setting up the API URLs (and so that they all display in the api root and can actually be used in the project - in my case at /api/). I’m using django rest framework, and can’t seem to set up more than one API - it works for just one, but the problem occurs when trying to set up another. So I have an app called pages and accounts (and core - the default where the main urls.py is). I’ve created another urls.py inside the pages app and another inside the accounts app. accounts/urls.py: from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r"accounts", views.AccountsViewSet, basename="accounts") urlpatterns = router.urls pages/urls.py: from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r"pages", views.PagesViewSet, basename="pages") urlpatterns = router.urls And the core urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from rest_framework.routers import DefaultRouter router = routers.DefaultRouter() urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("pages.urls")), # works but root only shows pages API # path("api/", include("pages.urls", "accounts.urls")), # fails with error: “django.core.exceptions.ImproperlyConfigured: Specifying … -
Django display form based off boolean
I am trying to use django-formtools. I have pip installed it and it's in my settings.py as well as requirements.text. Currently my /signup page works for signing up users but now I want to add another user type at the start of the form. It has this flow to it. I just want to make sure the forms display currently. 1. Displays different form based off first form's boolean. is False: display normal signup form(done) is True: display form with an added file field 2. Handles the form differently as well is False: saves the form as an abstractuser(done) is True: sends to db for an admin to add to. modals.py class PickUserType(forms.Form): is_doctor = forms.BooleanField() class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) urls.py from django.urls import path from pages.views import index, signup urlpatterns = [ … -
How to load Django template javascript when using request.get?
is my first time asking here but I'll try to explain my problem as clear as possible. I have a Django template with a few scripts on it, one of them will generate two graphs with voting results through Vue (a classmate has to do that part and isn't yet fully implemented, that is why Im using two dummy canvas elements). After generating those canvas I take them with the external script called 'get_graphs.js' and inside that script I made an AJAX POST request which stores those canvas and show them in another Django template on the same server. This works fine when I have visited the first django template using the browser at least one time but when I use another method like requests.get, urllib.request.urlopen or even Postman to visit it from outside, those scripts are not called and so the second template doesn't have the canvas. Here is the code of the first Django template: {% extends "base.html" %} {% load i18n static %} {% block extrahead %} <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" /> <link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" /> <link type="text/css" rel="stylesheet" href="{% static "booth/style.css" %}" /> <link type="text/css" rel="stylesheet" href="{% static "/visualizer.css" %}" /> {% endblock %} {% … -
Field 'last_login' expected a number but got datetime
hello I face this probleme when trying to connect to Django Admin here is my source code i do not want to change my legacy user table last_login field in date time it is an integer field that stop date time in unix timestamp . here is my source code from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from .helper import get_current_unix_timestamp from django.contrib.auth.signals import user_logged_in class MyUserManager(BaseUserManager): def create_user(self, username,password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not username: raise ValueError('user must have a username') user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( username, password=password, ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class Account(AbstractBaseUser): id = models.AutoField(primary_key=True,verbose_name='ID',) username = models.CharField(max_length=50, blank=True, null=True,unique=True) password = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) ip = models.CharField(max_length=255,null=True,blank=True) date_registered = models.IntegerField(default=get_current_unix_timestamp()) last_login = models.IntegerField(null=True,blank=True) member_group_id = models.IntegerField(blank=True, null=True) credits = models.FloatField(blank=True, null=True) notes = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) reseller_dns = models.TextField(blank=True, null=True) owner_id = models.IntegerField(blank=True, null=True) override_packages = models.TextField(blank=True, null=True) … -
Django python3 manage.py runserver won't run via VSC terminal (Mac)
Trying to run this command: python3 manage.py runserver via VSC terminal and get this error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? But! when I run it via the Mac terminal, it works well. I have verified and: Virtual env is running (via Anaconda) Django is installed (as it is running on the Mac terminal) is it something with VCS setting I need to tweak? Thanks in advance! -
Fitlering errors in Sentry
I'm running sentry.io for my django project. I'd like to prevent some errors from being reported so as to not consume my quota. Unfortunately, I'm not able to find any code samples on how to do this. Sentry's documentation doesn't clearly outline how or where to do this. I was wondering if you'd be able to provide a simple example or point me in the right direction. I'm on the Developer plan, so I need to filter these errors server side before sending to Sentry in order to prevent my quota from being hit. Thanks! -
Displaying Panda Table from other python project in Django App
So I am looking to display a Pandas table on a Django website through a django app. I have found this thread: display django-pandas dataframe in a django template. This explains how to use bootstrap and JS to create the table and display it in Django. However where I am lost is how I import the panda table to the object in the django. Basically, I have python project that creates pandas based on information queried data from elsewhere. Now I am trying to display those pandas on my web app. So, where I am lost is how I can run that python code (from my python pandas project) to get most recent data in sync with running the website and thus assign the pandas to the product model object. Any information regarding this would be huge. Thanks in advance! I am trying to use bootstrap-tables, because it is interactive and can create many different tables, but if someone has an easier less complicated idea please let me know. -
Showing the line numbers in <pre> in Django project using Pygments
I'm using the Pygments package in my Django project. When I try to render the code snippet in my template, it renders the whole data as follows: Template: ... {% pygmentify %} <pre class="{{snippet.lang}}">{{snippet.body}}</pre> {% endpygmentify %} ... Final rendered HTML: <pre lang="python"> ... <span class="kn">import</span> <span class="nn">hello</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'hey'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">test</span><span class="p">():</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'in the function'</span><span class="p">)</span> ... </pre> It actually works with no pain. The entire code block is being highlighted properly. The thing is that I want to show the line number as well. Should I style them or there is only a simple Pygments configuration needed? Thanks. -
AssertionError:'token' not found in{'non_field_errors':[ErrorDetail(string='Unable to authenticate with provided credentials.',code='authorization')]}
I've been made a django rest api app and i have this error in my test: image I'm going to leave the code here The test: def test_create_user_token(self): payload = { 'email': 'test@gmail.com', 'password': 'test123', 'name': 'Test' } create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) The serializer class: class AuthTokenSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) if not user: msg = _('Unable to authenticate with provided email and password.') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs From already thank you very much -
Is every API created with Django Rest Framework an REST API?
I just wonder if the fact that the API is created with DRF means it is really an Rest Api? Or is there something important to remember in order to make it truly REST? When I communicate with endpoints, I send JWT in requests, so I believe it makes it Stateless. Naming conventions for rest endpoints are probably important too. But is there anything else to remember so I could call my Api a Rest Api? -
Django: Where to store a main object and reference it from views.py + run repeating code?
I am building an app with Django to automate a reservation which I need to make every day. Django is used to provide a web interface to monitor and control this. However, I cannot figure out where to put my code within the Django files. Before trying Django I just had a while True loop that made the reservation as soon as a condition was true. To do this in Django, I need to create a main object on startup and reference this from different views in the views.py file. And I need to run some kind of schedule that checks the condition if the reservation is to be made. All of this in parallel to the actual website code. Using celery seems complicated and overkill for this. Is there a main Django object that is created on startup and can be accessed from other files (such as views.py)? Then I could create a parent class of this class that holds my main code and allows for starting and managing parallel jobs. E.g., I looked at AppConfig, but don't know how to reference this object from other files... class ReservationAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'reservation_app' driver = None def … -
On which tablet from the following can I code on?
I understand tablets are not a good choice for developers, but out of the following which one can be used for coding? (I'm pretty new at coding, so just some basic languages working should be fine.): SAMSUNG GALAXY TAB A7, Lenevo M10, or Lenevo Tab 4 tablet. Does any of these support mostly used languages and software? -
Django updating One-To-One Relationship is causing UNIQUE Constraint Failure
I cannot wrap my head around why I'm getting an error here - when the update query is run with this django ORM save() code, I get a UNIQUE Constraint Error: django.db.utils.IntegrityError: UNIQUE constraint failed: tasks_recurringtask.id From my understanding, update is executed immediately and only called on the same scheduler job that has the ID referencing the given RecurringTask. Maybe I'm missing something or there is a safe way to do this? Any explanations would be helpful, thanks! class RecurringTask(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='tasks') start_time = models.DateTimeField(default=now) scheduler_job = models.OneToOneField( Schedule, on_delete=models.CASCADE, blank=True, null=True, default=None ) def save(self, *args, **kwargs): # set all other dependencies for Task # update Scheduler Job if self.scheduler_job is None: self.scheduler_job = Schedule.objects.create(func='tasks.jobs.do_task', args=f'{self.pk}', next_run=self.start_time ) else: Schedule.objects.filter(id=self.scheduler_job_id).update( next_run=self.start_time ) super(RecurringTask, self).save(self) -
How to return last post?
I have probably a small problem. Namely how can i extract a last post when i use 'post.comments.all' class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.content1) Views tag = request.GET.get('tag') if tag == None: my_tag = Posty.objects.all print(my_tag) else: my_tag = Posty.objects.filter(created_tags__tag=tag) print(my_tag) If i tried use '[:1]' or last, this dont work. -
How can I get and display ForeignKey data in a Django template
I'm attempting to only display cards based on their category_name. for eg. I have 2 simple models, Product and Category: class Category(models.Model): category_name = models.CharField(max_length=254, blank=False, null=False) url_name = models.SlugField(max_length=254, unique=True) category_image = models.ImageField( null=False, blank=False, default='', upload_to='category_images', help_text='This will be the category image') category_description = RichTextField(default='') class Meta: verbose_name = 'Categories' def __str__(self): return self.category_name def get_category_name(self): return self.category_name class Product(models.Model): main_product_image = models.ImageField( null=False, blank=False, default='', upload_to='product_images', help_text='This will be the main image in the carousel.') alternative_image_1 = models.ImageField( null=True, blank=True, upload_to='product_images', help_text='This will be the first image in the carousel.') alternative_image_2 = models.ImageField( null=True, blank=True, upload_to='product_images', help_text='This will be the second image in the carousel.') category = models.ForeignKey( 'Category', null=True, blank=True, help_text='Assign product to category', on_delete=models.CASCADE) created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='product_creator', null=True) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) product_display_description = RichTextField(default='') spice_rating = models.CharField(max_length=1, null=True, blank=True) has_sizes = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, default='0') add_to_carousel = models.BooleanField(default=False) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.name I would like to then display these product cards on the frontend based on their category names. Using something simple like … -
Make Column in Pandas Dataframe Clickable and pass text value to Django view
I have a column in a dataframe called State. I want it to be clickable and when clicked, go to a URL and pass the state name to a Django view. So far I have tried it this way: smalldf['state'] = smalldf['state'].apply(lambda x: f'<a href=".\?q={x}">{x}</a>') It creates a url like this: http://127.0.0.1:8000/mysite/?q=TN but I am unable to extract the value TN from inside the view. The Django code looks like this: print('state is : ') print(parm_state) search_form = DateRangeForm(request.POST or None) # if this is a POST request we need to process the form data if request.method == 'POST': date_from = request.POST.get('startDate') date_to = request.POST.get('endDate') I can find the TN state value at the top and can print it. But when I come back from the DateRangeForm the value is gone. I cannot find a way to access it from inside the if request.method == 'POST' code. Would appreciate some help. Thanks -
Created information box inside form, based on model fields
Greetings and Happy Christmas everyone! I'm trying to implement a simple information text based on my model field because it retains some data like: MyModel.information: { start_date: imaginary_date, end_date: imaginary_date, store_name: 'Foo bar' } Now I want to display inside my admin form that information as a text, like: 'Store Foo bar, start at imaginary_date and close at imaginary_date. That implementation is just to the client who is editing some information at the form, can see easily the information about the store.