Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Working with checkboxes and querying the database in Django
My goal is to create a page that lists all the courses available in the database and have the user select which courses they would like to be a tutor for. I have a CustomUser model, a courses model, and finally a TutorTeachesCourse model that takes user and courses as foreign keys. # model.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_tutee = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) class Courses(models.Model): course_name = models.CharField(max_length=100, null = False) course_number = models.CharField(max_length=100, null = False) department = models.ForeignKey(Department, on_delete=models.CASCADE) course_description = models.CharField(max_length=1000, blank=True) objects = models.Manager() class TutorTeachesCourse(models.Model): tutor = models.ForeignKey( CustomUser, on_delete=models.CASCADE, limit_choices_to=models.Q(is_status=True)) course = models.ForeignKey(Courses, on_delete=models.CASCADE) objects = models.Manager() class Courses(models.Model): course_name = models.CharField(max_length=100, null = False) course_number = models.CharField(max_length=100, null = False) department = models.ForeignKey(Department, on_delete=models.CASCADE) course_description = models.CharField(max_length=1000, blank=True) objects = models.Manager() # forms.py class EditTutoredCourses(ModelForm): class Meta: model = TutorTeachesCourse fields = [] # not sure what to do here... # views.py def edit_tutored_courses(request): user = request.user if request.method == 'POST': #something about forms? form = EditTutoredCoursesForm(request.POST, instance=user) if form.is_valid(): user = form.save() messages.success(request, 'Success!') return redirect(reverse('view_profile')) else: form = EditTutoredCoursesForm(instance=user) course_list = Courses.objects.all() self_courses = TutorTeachesCourse.objects.filter(tutor=user) context = { 'form' : form, 'course_list': course_list, 'self_courses' : self_courses, } return … -
Get form field class in template
I want to check in my template if any of my form fields have certain values in their class. EG: *My form field: alcohol_percentage = DecimalField(max_digits=4, decimal_places=2, required=False, label='Alcohol', widget=(NumberInput(attrs={'class': 'form-control percentage'}))) *And then in my template: {% for field in form %} {{ field.label }} {{ field }} {% if 'percentage' in field.widget %} <!-- doing something --> {% endif %} {% endfor %} Any way to achieve this? -
Laravel route:list a like functionality in Python Django
am looking for Laravel route:list a like functionality in Python Django, i need to get a list of all urlsPatterns in my Django Project -
Can't import my compiled cython module in docker
I can successfully compile my cython module on windows (visual studio) and run python code that uses the cython module. I can successfully compile my cython module on linux (gcc/Docker container), but I get a ModuleNotFoundError when I run the same python code that works on windows. Here is my project structure on linux. When I compile it puts the .so file at /engine for some reason (doesn't do this on windows). So this is the structure after I move it to the proper spot in bbmajors_compute/compute_engine/engine: +-- bbmajors_compute | +-- compute_engine | | +-- engine | | | +-- __init__.py | | | +-- compute_cpp.pyx | | | +-- compute_cpp.pxd | | | +-- compute_cpp.cpp | | | +-- compute_cpp.cpython-37m-x86_64-linux-gnu.so | | +-- __init__.py | | +-- views.py +-- __init__.py +-- setup.py Here is my setup.py: from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize("bbmajors_compute/compute_engine/engine/compute_cpp.pyx")) Here is the build command: python ./setup.py build_ext --inplace Here is the code trying to import the cython module (last line is one that gives error): from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponseRedirect from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .forms import TeamForm from .engine.player_costs_handler import create_costs_dict … -
Django how to make internationalization without url language prefix?
As topic says I would like to get rid of language prefixes in my urls, example: mypage.com/en - english version, mypage.com/de - german version, etc and store my website language info only in users sessions. Is there any way I can do that? -
Render django.forms.fields.ChoiceField object
In my Django Project I have the following Problem: I would like to have a dynamic Django form. In the first step the user is asked something by the first form. When I get the postmethod the variables should be used for genereating a new form my views.py def calc(request): if request.method =="POST": get_form = CalculationForm(request.POST) if get_form.is_valid(): op = get_form.cleaned_data['op'] ab = get_form.cleaned_data['ab'] alternative = AlternativForm(optype = op, wsgroup = ab) return render(request, 'calculated_lensar.html', {"alternativ" : alternativ}) else: form = CalculationForm() return render(request, 'calc.html', {'form': form}) The secondform (postmethod) looks like class AlternativForm(forms.Form): praep_button = ((3, 'hallo'), (4, 'tschüss')) def __init__(self, optype, wsgroup, *args, **kwargs): super(AlternativForm, self).__init__(*args, **kwargs) #dont know for what this is standing self.optype = optype self.wsgroup = wsgroup self.values = self.read_db() self.praep_button = self.buttons() self.felder = self.blub() self.neu2 = self.myfield_choices() def read_db(self): import sqlite3 .... return result #tuple with 15x5 elements def buttons(self): praep_button = [] for i in self.values: praep_button.append((i[4], i[1])) return praep_button #Just formating result from read_db in tuple(15x2) def blub(self): return forms.ChoiceField(widget=forms.RadioSelect, choices=self.praep_button) myfield = forms.ChoiceField(widget=forms.RadioSelect, choices=praep_button) #print --><django.forms.fields.ChoiceField object at 0x751f9b90> def myfield_choices(self): field = self['myfield'] """i think here is the problem. Above 'myfield' is a django.forms.fields.ChoiceField object, but here it is … -
When i press on button from django form nothing happens
I am learning django forms and i am trying to create a form which will create a tag and here i got a problem i was trying figure out the problem of it, but i failed. When i press on button "Create Tag", nothing happends, also without method post in views.py it will not raise an error, just nothing. forms.py: from django import forms from blog.models import Tag, Post from django.core.exceptions import ValidationError class TagForm(forms.ModelForm): class Meta: model = Tag fields = ['title', 'slug'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'slug': forms.TextInput(attrs={'class': 'form-control'}), } def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug must not be created') if Tag.objects.filter(slug__iexact=new_slug).count(): raise ValidationError('Slug must be unique. We have "{}" slug already'.format(new_slug)) return new_slug urls.py: from django.urls import path from .views import * # some-article urlpatterns = [ path('', posts_list, name='posts_list_url'), path('post/create/', PostCreate.as_view(), name='post_create_url'), path('post/<str:slug>/', PostDetail.as_view(), name='post_detail_url'), path('tags/', tag_list, name='tag_list_url'), path('tag/create', TagCreate.as_view(), name='tag_create_url'), path('tag/<str:slug>', TagDetail.as_view(), name='tag_detail_url'), ] my html pattern: {% extends 'blog/base_blog.html' %} {% block title %} Tag Create - {{ block.super }} {% endblock %} {% block content %} <form action="{% url 'tag_create_url' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {% if field.errors … -
Django Rest Framework objects referenced using multiple keyword objects
I have a model that has a unique constraint on two fields together: class Document(models.Model): filename = models.CharField(max_length=255) publication = models.CharField(max_length=8) class Meta: constraints = [ models.UniqueConstraint( fields=['filename', 'publication'], name='document_key') As per the docsting in the DRF GenericAPIView get_object method: """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ Referencing with multiple keyword arguments is exactly what I want to do. I've gotten started on overriding the get_object method class DocumentViewset(viewsets.ModelViewSet): serializer_class = serializers.ActSerializer lookup_fields = ('filename', 'publication') def get_object(self): """As per the example in the DRF docstring itself, objects are referenced using multiple keyword arguments in the URL conf. Therefore, we need to override. """ queryset = self.filter_queryset(self.get_queryset()) lookup_url_kwargs = self.lookup_fields print(lookup_url_kwargs) print(self.kwargs) Which gives me: ('filename', 'publication') {'pk': '17'} You can see the prolem is that my lookup_url_kwargs will not be in self.kwargs (which is validated on the next line). If 'lookup_url_kwarg' is set then self.kwargs will be that. But without it, self.kwargs defaults to 'pk'. How do I override this behaviour so that two fields are expected in the URL?? … -
Django filter within model field and return new model with filtered queryset
I have these two models: class Task(models.Model): pass class Result(models.Model) task = models.ForeignKey('tasks.Task', related_name='results') enabled = models.BooleanField('enabled', default=False) And I want to get task with filtered results for my temporary calculations: task = Task.objects.first() results = task.results.filter(enabled=True) task.results.set(results) This is the working code, but task results will be broken after the first usage. How to get the new task with filtered results without task.results destroying? -
Djnago Generic View Data validation
I have a model Item with a foreing key in Row model. models.py from django.db import models from django.urls import reverse from django.utils import timezone class Item(models.Model): item_name = models.CharField(max_length=100, unique=True, validators=[validate_test]) number_of_questions = models.IntegerField(default=0) number_of_read_questions = models.IntegerField(default=0) def get_absolute_url(self): return reverse('uni_checker:main_editor') class Row(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) row_name = models.CharField(max_length=100, validators=[validate_test]) is_completed = models.BooleanField(default=False) deadline = models.DateField(default=timezone.now()) I'm looking for solution that will allow me to create something like that on one page: Item1_name: Row1_name; Row2_name; Row3_name; Item2_name: Row4_name; Row5_name; Row6_name; screenshot Problem For creating objects I use CreateView with form_class = Item, and context variable formset with Row forms. Problem is that I don't know how to validate data not only in form, but also in formset. If I input invalid data in row_name field, it just saves Item object, without saving Row object or showing errors. I know that something is wrong in view class or in form creation, but i couldn't find how to do it right way. Code views.py from django.views.generic import ListView from .models import Item from django.urls import reverse from .forms import ExampleFormSetHelper, CreateRowFormSet, ItemForm from crispy_forms.layout import Submit class ItemCreateView(CreateView): model = Item template_name = "uni_checker/item_create.html" form_class = ItemForm def get_context_data(self, **kwargs): … -
getting “no such table: accounts_user” after migrating and creating super user
I am creating a rest API using Django-rest-auth, and I have a custom user model in an app named accounts. the problem is after making migrations when I try creating a superuser in the console after I input the email in the email field, I get a bunch of errors telling me "no such table: accounts_user" my settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'accounts', ] # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True # UNSURE ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='api/accounts/rest-auth/login/' LOGIN_REDIRECT_URL = 'api/accounts/rest-auth/user/' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'opeyemiodedeyi@gmail.com' EMAIL_HOST_PASSWORD = '9j@4lifE' DEFAULT_FROM_EMAIL = 'opeyemiodedeyi@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.api.serializers.CustomUserDetailsSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer", } models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not … -
why am I not getting the tokens created when I tell django to do it?
I am trying to create a password reset in Django, but once the input finds the email in the database then send an email with their token similar to http://localhost:8000/account/account-recovery/process-reset/7d498a893edc45aa921a48f81f4826d3. it works amazingly until here, but after checking in Django shell the function that checks tokens. I have another problem it returns False that means no token was generated in the database. >>> verify_password_token('7d498a893edc45aa921a48f81f4826d3') False models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(pre_save, sender='account.User') def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') helper.py def generate_password_reset_token(request, email): try: user = get_user_model().objects.get(email=email) except get_user_model().DoesNotExist: return False get_user_model().objects.filter(email=user).delete() created = get_user_model().objects.create(email=user, token=user.token) email_subject = 'account recovery code' current_site = get_current_site(request) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': user.token }) mail = EmailMessage(email_subject, html_message, to=[email]) mail.content_subtype = "html" created = mail.send() if not created: return False return True def verify_password_token(token): try: token = get_user_model().objects.get(token=token) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): return False if token is not None: return True else: return False my view only contains, if an email was found then send the email form = RequestRestoreCodeForm(request.POST) if form.is_valid(): if generate_password_reset_token(request, form.cleaned_data.get('email')): -
Get request parameter not triggering if statement in Django
Django newbie. I'm trying to pass 'id_numb' as a get request, here's the URL: mysite/?id_numb=1. However, it does not make it to the second if statement. if request.GET['id_numb']: id_numb = request.GET['id_numb'] if id_numb == 1: # doesn't make it here - never get to this code, even when 1 is passed ....different code else: ....some code else: .... some other code -
Unable to save null to ForeignKey in an intermediate model - Django
My use case is, there is a Workshop and there are multiple positions (Workshop_Position) in it. For any position there will be multiple applications. The workshop owner has to approve an application for the user to be a team_member in the workshop. I am using a ManyToMany relationship for this, see below my models. class Workshop(models.Model): ... team_members = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='member_in_workshops', through='Membership') ... class Workshop_Position(models.Model): position_heading = models.CharField(max_length=100, null=False, blank=False) ... class Membership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='membership', blank=True, null=True, on_delete=models.CASCADE) position = models.ForeignKey('Workshop_Position', related_name='membership', on_delete=models.CASCADE) workshop = models.ForeignKey('Workshop', related_name='membership', on_delete=models.CASCADE) date_joined = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ("position", "user") So when a new position is created, I am saving the position to the Workshop_Position table and attempting to save the workshop the position belongs to with a null user into the Membership. I need to save this with a null user because there are going to be multiple applications to a Workshop_Position and the owner selects which user gets into the position. I am doing the below, { "user": " ", "position": "3", "workshop": "1" } But I get an error when I try to save the above to the Membership model. "user": [ "This field may not be null." … -
Why use @apiDefine together with @apiPermission in apiDocjs?
I am using apiDocjs in order to document my API. I have to define some Permissions, but when I simply use @apiPermission, this line just appears as plain text. When I add @apiDefine (https://apidocjs.com/#param-api-define) prior to that - I get no error, but it does not seem to change anything. I thought it would at least make it appear as a text with heading in HTML. So, what is the sense in using @apiDefine prior to @apiPermission? I am a beginner, and I cannot see any difference with or without @apiDefine - both HTMLs look the same to me. Here is a part of the code: class ArticleList(generics.ListAPIView): """ @apiDefine Authenticated user Only logged in users can use this functionality """ """ @api {get} / Retrieve all articles @apiName GetArticles @apiGroup Articles @apiPermission Authenticated user @apiSuccess {Object[]} articles List of articles. @apiSuccess {Number} id ID of the article @apiSuccess {String} author Name of the author @apiSuccess {String} title Title of the article @apiSuccess {String} body Text of the article @apiSuccess {Date} created_at Date when the article was published And the image below shows how the HTML looks like. Thank you! -
How to create APIs for UserProfile with rest framework?
I have created a UserProfile model with OneToOne relationship with User model. The UserProfile model is shown below. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.IntegerField(blank=True, unique=True, null=True) profile_image = models.ImageField(upload_to="media", blank=True ) current_location= models.CharField(max_length=300, unique=False, blank=True) created_at = models.DateTimeField("created at", auto_now_add=True) university = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) The serializer class is shown below. from rest_framework import serializers from .models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ( 'mobile_number', 'current_location' ,'university','profile_image') Iam using token authentication. How can I use the ListCreateViewand other classes to implement the post, put ,get and delete method in the best way possible. I also need to validate these data before saving(like mobile_number length should be 10 and mandatory) -
how can I improve my helpers / models to give me true / false instead of returning me invalid token view?
I am trying to fix this error which works as expected, but however at the moment to send the link confirmation link. I notice it never changes, and my update password view it doesn't seem to be created, and it always will display the form I have if not token Invalid. I am not sure a decent way to fix these errors especially the ### helpers from django.contrib.auth import authenticate, login, get_user_model from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.core.mail import EmailMessage def generate_password_reset_token(request, email): try: user = get_user_model().objects.get(email=email) except get_user_model().DoesNotExist: return False get_user_model().objects.filter(email=user).delete() created = get_user_model().objects.create(email=user, token=user.token) email_subject = 'account recovery code' current_site = get_current_site(request) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': user.token }) mail = EmailMessage(email_subject, html_message, to=[email]) mail.content_subtype = "html" created = mail.send() if not created: return False return True def verify_password_token(token): try: token = get_user_model().objects.get(token=token) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): token = None if token is not None: return True else: return False views class ResetPassword(View): def get(self, request): return render(request, 'account/forgot-password.html', { 'form': AuthenticationForm }) def post(self, request): form = RequestRestoreCodeForm(request.POST) if form.is_valid(): if generate_password_reset_token(request, form.cleaned_data.get('email')): return JsonResponse({'message': "Please check your registered email for instructions on recovering your account."}) # valid else: return … -
Methods from a single view to different endpoints: keep APIs for HTML and for JSON separated (Django Rest Framework)
Could you help suggesting how to keep coding style organised to keep endpoints from HTML and JSON separated, in Django Rest Framework ? In Flask I am used to keeps endpoints for serving Json, and ones for serving HTML, separated, like: @application.route('/api/') def api_root(): #... return jsonify({'data' : data}) and @application.route('/home/<string:page>/', endpoint='page_template') #... return render_template(template, page) And so I could serve the APIs like: /api/page => serve the json for the page, say for AJAX etc. /page => serve the corresponding html page In Django RF, I read that a ModelViewSet can serve both. So I could keep everything in one place. However, when I come to map views on the router, I would have all the endpoint served respect the path related my model, they would be all sub-path of /api Could you help in advising a good coding practice to make use of ModelViewSet, and route endpoints for html separated from APIs ? This is the example Im working on, my doubts are in comments: from rest_framework import viewsets from rest_framework import generics from rest_framework.decorators import action from rest_framework.response import Response from .serializers import PersonSerializer from .models import Person class PersonViewSet( viewsets.ModelViewSet): queryset = Person.objects.all().order_by('name') serializer_class = PersonSerializer … -
how to execute a user supplied python script on button click django
I have set up a template in django app. It has two inputs (i.e absolute path of python script and argument) and a button. On button click, I want python script supplied by user in input 1 to be executed with input 2 as argument. Output of that script should then be printed to same html page. -
Django receive a signal when a model value gets changed from a different application or when manually edited in database
I'm currently in a peculiar situation where I am not allowed to use a new database even though the product owner wants a new and improved application. This means that my new application will have to work with the old database. This database doesn't use foreign key constraints, which makes the usage of modules such as Django tables 2 nearly impossible. The solution I thought up is the following: Add in an extra foreign key field to required tables Users in the old app change an id of sorts, let's say team id of a news article Django app sees this change, finds the correct team model and links that team model to the foreign key field What I've tried so far to achieve this: Add in a custom save method to my model. This does work when I change the model with a view or CLI, but doesn't do anything when I manually change a value in the database or use a different application to change any values. class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) intra = models.ForeignKey(Intra, on_delete=models.DO_NOTHING) def save(self, force_insert=False, force_update=False): print("test") The next solution I tried is using a receiver. This again works in CLI … -
my profile object is not getting serialized in the user serializer
I am using Django rest auth to authenticate my users, that works well. how my model is set up is that I have the custom user model for authentication and I also have a profile model that gets created with a signal. I want that when the users are fetched in its URL, the profile for that user is also called an object in user. my models.py (I didnt include some models like the user managers, skill, e.t.c as i felt they werent relevant) class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() class Profile(models.Model): ''' Note: profile photo is expecting photos link gotten from cloudnairy from the frontend - The height is calculated in feets and inches - Need to sort out location (lives in) - Need to add an age function - Need to add achievemnet as a foreign field - Need to add education also as a foreign field - Add follow functionality ''' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True) bio = models.TextField(max_length=500, blank=True, null=True) … -
Authorization Vk, output a list of friends?
Made authorization Vk with the help django allauth, until that perhaps simply start pressing hard on authorization he will go, but not will display outcome As after authorization see displaying the name of authorized user and 5 any friends user. Also, when Perezhogin to the site authorization does not fly. examples of prompt. -
How to disable 'required' attribute of model's fields only for one form? Django
I have Post model which has such tables as title, body and etc. I want to create form in which this fields won't be required. At the moment, my form looks like this: class CreateUpdatePostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "body"] -
How can I create new 'draft' object with class based UpdateView before form filling?
I have a product model that has a lot of field. When user click to "Create New Product" I want create new object (just create object that it has id, seller, draft status), and show blank form. Because I want to use Ajax asyncronous upload to this object. User fills the object's other fields (like upload images) and save. Also user should be able to edit own draft products on own dashboard. First problem: I used UpdateView, but If I override get_object method and I click "Create New Product", django calls twice this method and create two object?! I want call just one time. Second problem: When users wants to edit draft items, they go to dashboard and edit someone. Should I create new class-based view for this or can I use same view for both operation? Maybe I can add get_or_create method to my get_object method, is It possible? my model: class Product(models.Model): seller = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Seller", default=None) category = models.ForeignKey("Category", on_delete=models.CASCADE, verbose_name="Category Name", blank=True, null=True) title = models.CharField(max_length=50, verbose_name="Product Title", blank=True, null=True) status = models.IntegerField(choices=((x.value, x.name.title()) for x in Status), default=Status.TASK) images = models.ManyToManyField("ProductImages", blank=True, null=True) my class-based view: class ProductCreateViewTest(LoginRequiredMixin, UpdateView): template_name = 'product/add.html' form_class = … -
modal popup on hyperlink click in hovertext in plotly
i want to open modal dialog on click of hyperlink in hovertext in PLOTLY PYTHON. i had included hyperlink in data from backend, but when i add class or id to it the graph doesn't myPlot.on('plotly_click', function(data){ var eventid = ''; for(var i=0; i < data.points.length; i++) { ClickIndex = data.points[i].pointIndex; eventid = data.points[i].data.DID[ClickIndex]; } if(eventid) { openFormPopup(eventid) } }); i want to run same function on click of a hyperlink in graph. Show Summary is hyperlink Show summary is hyperlink i have send from backend. i want to fire same function which runs on plotly_click.