Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The most efficient way to store (retrieve and use) requests data
I'm building a Django app that should be able to able to deliver content based on requests. Essentially, some of the contents are limited. After being delivered an X amount of times, we should stop delivering them for good. It's also expected to receive several requests per second. Basically, every time a limited content is delivered, we should update the inventory for that item. Also, we should store every content delivery to generate a report for which users each content was delivered, and when. My first idea is to create a model that should store every request made, and which content was delivered. That way, I could generate a report based on that. To deal with the inventory part, just updating the field times_delivered or something like that should do the trick. If times_delivered==max_deliveries, we should stop delivering it. This seems to be very straightforward way to deal with it. My concern is about performance. We are expecting to be quite intensive in terms of delivery. This method would work in scale? There would be a better option to deal with it somehow? -
POSTing to a Django form much later than it was generated with Service Worker background sync: CSRF issues
I have a Django form which I make available offline via service worker. If the user completes the form while offline, the data to submit is stored in IndexedDB and then a background-sync is registered; when the browser comes back online, the sync event is fired in the service worker which can then read the data from IndexedDB and submit the form to the back end via fetch(). However, I have Django's CSRF protection turned on. This requires that I submit the form with a legitimate CSRF token, stored in a cookie, but also in the body of the form (or better in an X-CSRFToken header) as well as part of the fetch() request. Unfortunately, because this is happening in a service worker, I can't read the cookie to get the CSRF token. There was a proposal to allow service workers to read cookies but it's not completed and is currently paused, so is not available. I thought about using postMessage from the service worker to the main page to ask that main page to read the cookie and send it back, but background-sync might run at a time at which there is no main page to postMessage to. It … -
On django admin side Get field data from Api
On my application on front client side I am getting City field data from a Api using this "http://gd.geobytes.com/GetCityDetails?callback=?&fqcn="+cityfqcn in ajax call . Full code is like function getcitydetails(form) { fqcn = jQuery("#f_elem_city").val(); cityfqcn = fqcn; if (cityfqcn) { jQuery.getJSON( "http://gd.geobytes.com/GetCityDetails?callback=?&fqcn="+cityfqcn, function (data) { jQuery("#f_elem_city_city").val(data.geobytescity); } ); } {#document.searchForm.submit();#} } jQuery(function () { jQuery("#f_elem_city").autocomplete({ source: function (request, response) { jQuery.getJSON( "http://gd.geobytes.com/AutoCompleteCity?callback=?&q="+request.term, function (data) { response(data); } ); }, minLength: 3, select: function (event, ui) { var selectedObj = ui.item; jQuery("#f_elem_city").val(selectedObj.value); getcitydetails(selectedObj.value); return false; }, open: function () { jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top"); }, close: function () { jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all"); } }); jQuery("#f_elem_city").autocomplete("option", "delay", 100); }); Now I want to do same thing in this field on admin side ? As far I tried to field I didn't get any helpful thing. your any help would be highly appreciated . thanks in advance. -
How make sessions in Django without username/password system?
I`m building Django app that should work in local net, the app should allow people to vote for some topics but only one vote per person. How can I control that without logging in with username/password? I think that it should be something about cookies but I`m not sure is there some tools inbuilt in Django. Thanks! -
unable to load static css file in the dash app
I have built a single page dash app which runs as expected when run as a single file, but when I am trying to run it as a whole app, the CSS does not load correctly. Below is my folder structure While I load the whole app by manage.py below is the error that I get Internal Server Error: /assets/internal.css Traceback (most recent call last): File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\my_project\analyser_tool\views.py", line 32, in dash_index return HttpResponse(dispatcher(request)) File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\my_project\analyser_tool\views.py", line 27, in dispatcher return response.get_data() File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\werkzeug\wrappers.py", line 986, in get_data self._ensure_sequence() File "C:\Users\Tushar\Documents\serato_video_analyser\video_analyser\lib\site-packages\werkzeug\wrappers.py", line 1035, in _ensure_sequence raise RuntimeError('Attempted implicit sequence conversion ' RuntimeError: Attempted implicit sequence conversion but the response object is in direct passthrough mode. This is my only second dash app that I am working and unfortunately does not have much experience in it. I am really hopping if some could please help me fix this issue. I have been struggling with it for couple of days now. Thanks a lot in advance !! -
Django no longer parses POST data correctly
We recently upgraded to Django 1.9.13 (from Django 1.4) and now when I send an HTTP POST request, where my POST data is urlencoded like this: task_id=qkjwdkqhoiqobbkl the data shows up only in request.body and does not get parsed into request.POST. Any idea why that is happening? NOTE: I am sending this HTTP POST request from a mobile device to a vanilla Django server (not DRF). What exactly must I do (add some headers?) to force Django 1.9.13 to understand that when I send a simple "variable=value" string as my post data that it should set request.POST["variable"]=value? -
How to store javascript objects in a database
I'm a complete newbie to django/react and am trying to learn by creating a battleships game. I've written some of the frontend using React, but I want to store the game state, which I currently have as a javascript object, in my database through django so it can be shared by both players. My state object has two properties: an array array objects which represent the board state and history, and an array of Ship objects as shown below. class Game extends React.Component { constructor(props) { super(props); this.state = { history: [{ squares: Array(9).fill(null) }], ships: [new Ship(14, "N"), new Ship(37, "E"), new Ship(84, "S")] }; } //... } I'm thinking I might have to serialize the state object to do that, but not sure how to go about it. Most of the questions/answers I've seen talk about serialising a model, but I don't think that's what I need. I want to serialise a custom object, store it in the database, and then deserialize it when it is sent to the players' browsers. -
Django validation questions
For Django validation, I've seen a lot of people suggest putting it in the model layer, which makes sense to me (to keep business logic consistent and in one place). However, I saw 2 ways of doing this: by writing a custom clean() method for every model, which can validate and clean the data, or by defining validators on model fields (called when the ModelForm cleans). Can someone more familiar with Django please discuss the pros and cons of each of these approaches? I wrote a sample code, where my Model has a field zip_code, which has a validator (makes sure the zip code is exactly 5 numeric digits). If it's not, the validator raises a ValidationError. In my view that adds this model, I have a try block looking for this ValidationError, to pass an appropriate error message to the template. However, when submitting a 4 digit zip code, a ValueError is thrown instead, and displayed in the browser. It does say validation failed, so I am guessing the validator is kicking in, but I must be missing something in how the error is handled. If a validation error is caught in the view, how should I come back … -
unable to connect to mssql database from Django app from a docker container
I am new to docker containers and I have been struggling to connect to mssql database from Django app and successfully launch docker container for my rest API. Please bear with me for long question. Here is my docker file FROM ubuntu:19.04 ENV PYTHONUNBUFFERED 1 ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -y curl apt-transport-https python3 python3-pip python-dev locales RUN apt-get -y update && apt-get install -y sudo apt-utils gnupg ca-certificates RUN apt-get update && apt-get install -y git RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/ubuntu/19.04/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN apt-get update --fix-missing && ACCEPT_EULA=Y apt-get install -y msodbcsql17 # optional: for bcp and sqlcmd RUN ACCEPT_EULA=Y apt-get install mssql-tools RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile RUN echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc RUN /bin/bash -c "source ~/.bashrc" # optional: for unixODBC development headers RUN apt-get -y update && apt-get install -y unixodbc-dev #RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen #RUN locale-gen RUN git clone https://github.com/mushfiq/djmsc.git o ms_demo WORKDIR ms_demo RUN mkdir -p logs RUN pip3 install -U pip #RUN apt-get update && apt-get install -y uwsgi-plugin-python #RUN apt-get update && apt-get install -y uwsgi ENV PATH="/usr/local/lib/python3.7:/usr/local/lib/python3.7/dist-packages:${PATH}" RUN pip3 install -r requirements.txt --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org … -
Use of radio button with Django and Bootstrap
I'm trying to use a radio button based on inline Bootstrap radio but I don't understand why I can't select a choice; it seems that they are disabled. In my form I've the gender choice: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = forms.ChoiceField( widget=forms.RadioSelect( attrs={ 'type': 'radio', 'id': 'id_gender', 'name': 'id_gender', 'class': 'custom-control-input', } ), choices=GENDER_CHOICES, label='Gender', required=True, ) I've used this for render the radio buttons: <div class="form-group mb-4"> <div class=""><h4>{{ form.gender.label }}</h4></div> {% for choice in form.gender %} <div class="custom-control custom-radio custom-control-inline"> <label class="custom-control-label" for="{{ choice.id_for_label }}"> {{ choice.tag }} {{ choice.choice_label }} </label> </div> {% endfor %} </div> What I've wrong? -
Function based view giving me TemplateDoesNotExist error in Django
I am trying to get arguments in my function based view to show up on my web page. I have tried many things and can't figure it out. I keep getting a 'TemplateDoesNotExist at...' but I know it does exist. I figured I'd try here before I scrap it and start again. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '##########################' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'frontpage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', ] AUTH_USER_MODEL = 'users.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'donmuh.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'donmuh.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('frontpage/', include('frontpage.urls')), ] frontpage/urls.py from django.urls import path from … -
New django docker container logs everybody out
Whenever we build and put in a new Docker container, the django application logs everybody out. This is despite our sessions being backed in the database. >>> settings.SESSION_ENGINE 'django.contrib.sessions.backends.db' I'm not sure what is causing this and how to fix it. -
IF statement is not working properly inside the FOR loop of a Django project
I am learning Django for the last couple of months. Now I am working on a demo project which is about teachers those who will be available to teach preferred subject. But after working some days I can't move ahead of some limitations of my programming knowledge. I want to show a button on some selected posts. I used FOR loop to create the post model, and inside it I also used an IF statement. But it is not working the way I wanted. I want the button will only be shown when a teacher available. Buut Can you guys please help me to get rid of this problem? Thanks in advance! In the Post model I have included some Boolean fields and set their default values as False. And in the blog view I have created some querysets for those Boolean fields to call them when they are needed. When I use them inside the HTML I don't get any error. Please look the code bellow. Here is the Teacher model for teacher app from django.db import models from django.utils import timezone from PIL import Image class Teacher(models.Model): name = models.CharField(max_length = 100) teacher_photo = models.ImageField(upload_to = 'photos/%Y/%m/%d/') description … -
Django Wagtail: Do we have any option to edit list_display of any Page model?
I would like to ask you If there is any option how to edit "list_display" of any Wagtail page model. I would assume that there must be something because we can add custom model into sidebar using wagtail.contrib.modeladmin.options.ModelAdmin For example I can add my Email model into admin.py or hooks.py like this class EmailAdmin(ModelAdmin): model = Email menu_label = "Emails" menu_icon = "mail" menu_order = 200 add_to_settings_menu = False exclude_from_explorer = False empty_value_display = 'N/A' list_per_page = 10 list_display = ('subject', 'name_surname', 'phone', 'email', 'text_', 'date', 'sent', 'change_seen') def name_surname(self,obj): return "{0} {1}".format(obj.name, obj.surname) In that class EmailAdmin I can build custom list_display. Can we adjust wagtail Page models by similar way? Thank you very much in advance. -
Dynamically Adding Forms to Formet in Django
I have created a formset for users to add and remove forms as necessary using Django's empty_form and jQuery. However, my jQuery script is not properly incrementing form-TOTAL_FORMS and only the data from the first form in the formset is being saved. If I hard code the form-TOTAL_FORMS value, I am able to return more than one form, but the data is still being duplicated. Any help would be greatly appreciated. views.py def presales(request): my_opportunities = cwObj.get_opportunities() PresalesFormSet = formset_factory(PresalesForm, extra=1, can_delete=True) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-title': '', 'form-0-pub_date': '', } if request.method == 'POST': presales_formset = PresalesFormSet(data) if presales_formset.is_valid(): selected_opportunity = request.POST.get('select_opportunity') for presales_form in presales_formset: task_description = request.POST.get('task_description') hours = request.POST.get('hours') select_engineer_level = request.POST.get('select_engineer_level') obj = Presales() obj.opportunity = selected_opportunity obj.taskDescription = task_description obj.hours = hours obj.engineerLevel = select_engineer_level obj.save() else: presales_formset = PresalesFormSet() context = {'presales_formset': presales_formset, 'my_opportunities': my_opportunities} return render(request, 'website/presales.html', context) template.html <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> {{ presales_formset.management_form }} <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {% for presales_form in presales_formset.forms %} {{ presales_form.field_errors }} {{ presales_form.errors }} {% endfor %} </form> {% endfor %} <div … -
Making query from within a class method in Django
I have a Friend class: class Friend(models.Model): # static variables for friend_status attribute FRIENDS = 1 A_REQUESTS_B = 2 friend_A = models.ForeignKey(User, related_name='friend_A', on_delete=models.SET_NULL, null=True) friend_B = models.ForeignKey(User, related_name='friend_B', on_delete=models.SET_NULL, null=True) friend_status = models.IntegerField() class Meta: unique_together = (('friend_A', 'friend_B')) And I also have a class method that finds all the friends of one user, and returns those friendships: @classmethod def show_friends(cls, username): current_user = User.objects.get(username=username) fa = Friend.objects.filter(friend_A=current_user).filter(friend_status=1) fb = Friend.objects.filter(friend_B=current_user).filter(friend_status=1) all_friends = fa | fb return all_friends My question is, how do I access the manager to do a query from within the class method? User.objects is fine, but Friend.objects doesn't work, from within this method. Should I be using a custom manager method for this or approaching this from some other way? What is the best way for me to query my friend model from within a Friend model method? Originally, I don't think I was using django correctly, and I had this show_friends logic in a view. But I think this is really bad, and doesn't keep all the parts of my app decoupled, so I'm trying to move all the friend-functionality into methods of the Friend model, which vies can then call to get the … -
Introspection endpoint is not getting called
I am looking to create an API using the Django REST Framework which will authenticate using a separate authentication server by means of its introspection endpoint. The authorization flow should look something like the following. The client provides either user credentials or a refresh token to the token endpoint on our authentication server. If the provided credentials or refresh token are valid, the authentication server responds with an access token and a refresh token. The client then sends the access token to the API when requesting a resource. The API verifies the provided access token using the introspection endpoint on our authentication server. The authentication server responds letting the API know if the access token is valid. If the access token is valid, the API responds to the client with the requested resources. Step 4 is the part I'm after, and the Django OAuth Toolkit looks like it provides an option for exactly this. In the section about setting up a separate resource server it states that it allows the application to verify access tokens by use of an introspection endpoint. So I followed the setup for the Django OAuth Toolkit, and pointed the RESOURCE_SERVER_INTROSPECTION_URL toward the introspection endpoint on … -
Django Form not saving to database?
I am using CreateView to create entries on my frontend and then save to the database/backend. But each time i click save or submit the form redirect successfully as expected but will not save to the back end. I have tried adding success_url to my views.py and also added get_absolute_url(self) to my models.py but still it hasn't worked. Views.py class Dashboard (LoginRequiredMixin, CreateView): model = PostedJob template_name ='accounts/dashboard.html' fields = ['firstname', 'lastname', 'job_title', 'email', 'budget', 'country', 'state', 'address', 'job_category', 'description', 'photo'] success_message = "Redirect successfully created!" login_url= 'login' models.py Type = ( ('building inspection', 'Building Inspection'), ('agriculture', 'Agriculture'), ('construction', 'Construction'), ('maintenance & training', 'Maintenance & Training'), ('surveying & mapping', 'Surveying & Mapping'), ('events coverage', 'Events Coverage'), ) class PostedJob(models.Model): firstname=models.CharField(max_length=200) lastname=models.CharField(max_length =150) email=models.EmailField(max_length =150) job_title= models.CharField(max_length =150) budget=models.PositiveIntegerField() country=models.CharField(max_length = 150) state=models.CharField(max_length = 150) address=models.CharField(max_length = 150) job_category=models.CharField(choices=Type, default ='agriculture', max_length=50 ) photo= models.ImageField(upload_to='/%Y/%m/%d/', blank=False, null=False) description=models.TextField(max_length = 1500) post_date=models.DateTimeField(default = datetime.now, blank=True) publish=models.BooleanField(default =False) def __str__(self): return self.job_title def get_absolute_url(self): return reverse('home') urls.py urlpatterns =[ path('accounts/dashboard', Dashboard.as_view(), name='dashboard'), ] index.html <form action="" method="post"> {% csrf_token %} {{form.as_p}} <div> <input type="submit" id="submit" value="Submit" class="btn waves- effect waves-grey green"> </div> </form> Also the form displays not error message. I will indeed … -
How to solve attirbute error with profile
I need to create profiles in my project. I'm certain that my code is okay but still receiving the error: AttributeError at /admin/login/ 'User' object has no attribute 'UserProfile' and it drives me crazy.. I have checked the whole google and couldn/t find the solution. models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) output = (300,300) img.thumbnail(output) img.save(self.image.path) signals @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.UserProfile.save() apps class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals html <div class="container"> <div class="mt-5"> <div class="media"> <img class="rounded-circle account-img" src="{{user.userprofile.image.url}}" style="max-height: 100px; max-width: 100px;"> </div> <div class="media-body mt-3"> <h2 class="account-heading">User: {{user.username}}</h2> <p class="text-secondary">Email: {{user.email}}</p> </div> <form method="POST" enctype="multipart/form-data"> {%csrf_token%} <fieldset class='form-group'> <legend class='border-bottom mb-4'>Update your details</legend> {{user_form|crispy}} </fieldset> <div class='form-group'> <button class='btn btn-outline-info' type="submit">Update</button> </div> </form> </div> </div> -
How to implement CMS in django?
I am building an E-commerce site. Now I am working on the product detail pages, how can I achieve the function that admin can write formated content (just like write something in MS word), then the front-end is able to display that content in its original format (paragraphs,fonts,maybe some pictures among it). Which library can do this? Thank you. I am using django for back-end and react for front-end. -
Loading .js files in html
I wanted to know how loading static .js files looks like Use <script src="{% static 'js/base.js' %}" /> Propably need .js because i will try use this NavBar like here: https://www.youtube.com/watch?v=LOWjWRy_Kks I tried Load from bootstrap: CSS <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> JS <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> I don't have a red frame like in the movie https://zapodaj.net/images/46600ed652872.jpg -
How to save foreign key values from a form to a django database?
I'm trying to save a django from a form into a database. The problem is in foreign key. As a result, entries in the database are all available except foreign key. django 2.2, python3. models.py: first_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Имя') last_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Фамилия') middle_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Отчество') gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Пол') age = models.ForeignKey(Age_category, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Возраст. кат-ия') tournament = models.ForeignKey(Tournament, null=True, blank=True, on_delete=models.CASCADE, verbose_name='Турнир') division = models.ForeignKey(Division, blank=True, null=True, on_delete=models.CASCADE, verbose_name='Дивизион') discipline = models.ForeignKey(Discipline, blank=True, null=True, default=True, on_delete=models.CASCADE, verbose_name='Дисциплина') views.py: def sportsman(request): documents = Document.objects.filter(is_active=True) form = SportsmenForm(request.POST or None) if request.method == "POST" and form.is_valid(): print(request.POST) print(form.cleaned_data) data = form.cleaned_data print(form.cleaned_data['email']) form.save(commit=True) new_form = form.save() return render(request, 'sportsman/sportsman.html', locals()) forms.py: class SportsmenForm(forms.ModelForm): class Meta: model = Sportsman exclude = ['created', 'updated'] -
Is it possible to load a dictionary with template tag values and load context for those tags?
I'm essentially trying to load context twice so that on the second time I want to inject context into my template, it would be for template tags that would be injected on the first time I'm loading in context. Does anyone know the best way to go for this problem? I've tried using an inclusion_tag for this and it's still not working. I've also tried using a json file but I would like to avoid parsing the entire json file all the time and I would like to do it with a python dictionary. Ideally, I want to load this dictionary into the template first, LAYOUT = { LAYOUT_ONE: { "header": "Hello, {{ user.name }} />", "description": "This is the description of {{ obj.note }}" } } template.html: {% load tags %} {% get_data label %} <h1>{{ header }}</h1> <p>{{ description }}</p> Then load this additional context: { "user": { "name": "John" }, "obj": { "note": "test test" } } I've tried using an inclusion_tag two ways as suggested on the Django docs: tags.py def get_data(label): return LAYOUT[label] register.inclusion_tag("template.html")(get_data) as well as: def get_html_template(label): register = template.Library() template = loader.get_template("template.html") register.inclusion_tag(template)(get_data) return email_template I would then call it this way: … -
Raise error in create method django rest framework
I throw ValidationError while checking for validation in my clean method in models.py . How can I catch this error in create method so that it throws a json object containing the error detail in this way { "detail":"input is not valid" } -
How to save two related entries in a single form
I am new to Django and I am creating a simple 2 page messageboard app (submit page and messageboard page) I am struggling with the form for my submit page. As I am learning my way around Django I decided not to use the standard user model and opted to rather create a model (Poster) which has a one to one relationship with the message model. Basically in one form I would like to add a message and a poster(foreign key) which has multiple fields. Is it possible to achieve what I am trying to do? Thanks in advance for the help. I don't really know what to try or what to look for. I have included some code below. Models class Poster(models.Model): full_name = models.CharField(max_length = 50) phone_number = models.CharField(max_length = 15) email = models.EmailField() class Message(models.Model): message_text = models.CharField(max_length=10000) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Poster, on_delete=models.CASCADE) class MessageForm(forms.ModelForm): class Meta: model = Message fields = ['full_name', 'phone_number', 'email', 'message_text']