Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the simplest way to handle M2M through fields in wagtail FieldPanel?
I recently added a "through" model to allow sorting connected objects. In the example below, a Stage has an ordered list of Blocks linked through StageBlock (with the StageBlock.order field) @register_snippet class Block(index.Indexed, models.Model): title = models.CharField(max_length=100, verbose_name=_("Block Name")) @register_snippet class Stage(index.Indexed, models.Model): title = models.CharField(max_length=100, verbose_name=_("Stage Name")) blocks = models.ManyToManyField( to="app.Block", blank=True, help_text=_("Blocks associated to this stage"), related_name="stages", verbose_name=_("Blocks"), through="StageBlock", ) panels = [ FieldPanel("title", classname="title full"), FieldPanel( "blocks", widget=autocomplete.ModelSelect2Multiple( url="block-autocomplete", attrs={"data-maximum-selection-length": 3}, ), ), class StageBlock(models.Model): block = models.ForeignKey("app.Block", on_delete=models.CASCADE) stage = models.ForeignKey("app.Stage", on_delete=models.CASCADE) order = models.PositiveSmallIntegerField() The problem is that the related Wagtail admin form breaks, since it tries to associate Block objects to Stage, without providing the "through" model "order" field value. I'm wondering what is the cleanest/least effort solution to allow an ordered selection of elements in the admin panel, then to properly save the Stage instance with its blocks and related stageblocks. For the moment, I will add a custom form to the snippet, and auto-assign the order from the position of blocks in the form data (hoping that it always matches the order of blocks as selected in the fieldpanel). It feels like this use-case could be auto-handled, either by the wagtail-autocomplete plugin, … -
Migrating data from SQLite3 to Postgresql using DBeaver
My project use an SQLite3 DB but now I need to do a migration from SQLite3 to PostgreSQL. I've used DBeaver for do this using the "Import Data" option. At the end of the importation of all the tables from SQLite3 to PostgreSQL I noticed this error when I try to add a new content: IntegrityError at /engine/kernel/keyconcept/add/ duplicate key value violates unique constraint "kernel_keyconcept_pkey" DETAIL: Key (id)=(4) already exists. If I add a new model, into this project, that use the new DB(PostgreSQL) there aren't problems to add contents, but if I use the old models I see the IntegrityError above. I've do a test with a model that have only two rows: with the first attempt I received a same error but for key id 1, with the second attempt I received a same error but for key id 2. When I've tried for the third time I was be able to add the content and the same think happens for the next attempts. So I think that the row counter of the every tables after the migrations never start from the last content but from zero. It strange because previous I've do the same migrations but from … -
Using Django rest framework, How can i get only changed data from table from last API call?
I want to get only those data which is changes in table scene last API call. -
How to store pdf file from the view.py to database
i'm created a html file where i am getting the pdf file using input tag i can't store the pdf file which was post to the view.py from the view.py i need to store the file to the database def home(request): if request.method == 'POST': link_pdf = request.POST.get('pdf_link') file_pdf = request.FILES.getlist('document') I expect to store the pdf file from the view.py to database -
Direct assignment to the reverse side of a related set is prohibited. Use addresses.set() instead
I am going to create and update nested relationships but it is not working as expected I have a three models User, Profile and Address. Profile model is a FK in Address model profiles/models.py class Address(models.Model): profile = models.ForeignKey(Profile, related_name='addresses', on_delete=models.CASCADE) country = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=100) zip_code = models.CharField(max_length=50) address = models.CharField(max_length=1000) profiels/serializers.py class ProfileSerializer(serializers.ModelSerializer): addresses = AddressSerializer(many=True) class Meta: model = Profile fields = ['gender', 'date_of_birth', 'hometown', 'phone', 'addresses'] def create(self, validated_data): addresses_data = validated_data.pop('addresses') profile = Profile.objects.create(**validated_data) for address_data in addresses_data: Address.objects.create(profile=profile, **address_data) return profile users/serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ['id', 'url', 'first_name', 'last_name', 'email', 'password', 'profile'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() Profile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.save() profile.gender = profile_data.get('gender', profile.gender) profile.date_of_birth = profile_data.get('date_of_birth', profile.date_of_birth) profile.hometown = profile_data.get('hometown', profile.hometown) profile.phone = profile_data.get('phone', profile.phone) profile.addresses = profile_data.get('addresses', profile.addresses) profile.save() It is working very well with user and profile I can create and update but when I add addresses it gives me … -
is there any plugin for implement drag and drop image upload?
I wish to implement image upload using drag and drop, may somebody already implemented it. $echo -
Can't load second Highcharts diagram from my Django View
Can't seem the load my second chart diagram on my another carousel page. I'm doing it via response/request from views.py. I was able to display my first diagram but not the second. No errors were displayed when loaded Looked at "How to integrate Django and Highcharts" doc but i don't know how to implement two charts on one page class dashboard_view(View): template_name = 'accounts/dashboard.html' def get(self, request, *args, **kwargs): dataset = Profile.objects \ .values('is_active') \ .annotate(is_active_count=Count('is_active', filter=Q(is_active=True)), not_is_active_count=Count('is_active', filter=Q(is_active=False))) \ .order_by('is_active') categories = list() is_active_series_data = list() not_is_active_series_data = list() for entry in dataset: categories.append('%s Active' % entry['is_active']) is_active_series_data.append(entry['is_active_count']) not_is_active_series_data.append(entry['not_is_active_count']) is_active_series = { 'name': 'Active user', 'data': is_active_series_data, 'color': 'green' } not_is_active_series = { 'name': 'Inactive user', 'data': not_is_active_series_data, 'color': 'red' } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Active user on Current Platform'}, 'xAxis': {'categories': categories}, 'yAxis': { 'title': { 'text': 'No.of users'}, 'tickInterval': 1 }, 'plotOptions': { 'column': { 'pointPadding': 0.2, 'borderWidth': 0 } }, 'series': [is_active_series, not_is_active_series] } dump = json.dumps(chart) return render(request, self.template_name, {'chart': dump}) def post(self, request, *args, **kwargs): dataset = Department.objects \ .values('department') \ .annotate(IT_count=Count('department', filter=Q(department="IT")), Sales_count=Count('department', filter=Q(department="Sales")), Admin_count=Count('department', filter=Q(department="Admin")), HR_count=Count('department', filter=Q(department="HR"))) \ .order_by('department') categories = list() IT_series_data = list() Sales_series_data = list() … -
Django how to implement pagination if I have data only for a page and total pages num
In my app I have data only for current page and total pages num. I can request data from any page but only for one. How to implement Django pagination in that case? -
Django : IndexError: list index out of range
Getting exception : IndexError django.db.models.sql.compiler in apply_converters IndexError: list index out of range in djagno queryset I am doing this object =Info.objects.get(is_active=False,device_id=device_id) here device_id is long text type in database schema and it is indexed object =Info.objects.get(is_active=False,device_id=device_id) -
My download function saves a file with fixed name
I'm using Django 1.8 with Python 3.6. When I use my download function below, it saves the file with a name fixed to local download directory. But I really want to keep the original name. I can change the browser to open a download manager, but I want to know how to fix this filename to the original one. def download(request): path = "test.jpg" # Original filename that I intend to give. file_path = os.path.join(settings.MEDIA_ROOT,path) print("file_path :", file_path) if os.path.exists(file_path): readFile = open(file_path,"rb") response = HttpResponse(readFile.read()) response['Content-Disposition'] ='attachment; filename'+os.path.basename(file_path) response['Content-type'] = 'image/jpg' return response When I download the file, it is autosaved with a name 'Download.jpg', which is the browser's default directory name. -
Reverse for 'add-subject' with arguments '('',)' not found. 1 pattern(s) tried: ['result\\/add\\-subject$']
i try to show book list of a register class, but i found error. views.py files def subject_list(request): form = ClassSelectForm(request.GET or None) select_class = request.GET.get('select_class', None) if select_class: cls = ClassRegistration.objects.get(id=select_class) subjects = SubjectRegistration.objects.filter(select_class=cls) print('subjects=', subjects) context = {'subjects': subjects} return render(request, 'result/subject-list.html', context) context = {'form': form} return render(request, 'result/subject-list.html', context) models.py files class SubjectRegistration(models.Model): select_class = models.ForeignKey(ClassRegistration, on_delete=models.CASCADE, null=True) subject_name = models.CharField(max_length=45) subject_code = models.IntegerField(unique=True) marks = models.IntegerField() pass_mark = models.IntegerField() add_date = models.DateField(auto_now_add=True) def __str__(self): return self.subject_name -
Django-m2m-using through filter only existing objects
I have two model, Route, Point. between these models I have many-to-many relationship and also for sequencing points on route, I have also another model RoutePointSequence then I could have a m2m with "through". I want restricte this "through" available items to that points, which already exists on a route Second question: Also I need to describe some information about a single part of a route between two point, e.g. distance-btn-points; I made another model for that, but any chance to mix these two "trough" models? -
How to migrate existing django database model(SQLite3) to MYSQL?
How can I migrate my existing database data from default django db - SQLite3 to MYSQL. I'm currently using SQLyog and I want to display all my current data in it. I tried following this solution from What's the best way to migrate a Django DB from SQLite to MySQL?: 1) python manage.py dumpdata > datadump.json 2) Change settings.py to your mysql 3) Make sure you can connect on your mysql (permissions,etc) 4) python manage.py migrate --run-syncdb 5) Exclude contentype data with this snippet in shell python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() 6) python manage.py loaddata datadump.json ....but this doesnt seem to work. Any suggestions? Im getting this error as well: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") -
Docker/Python/Django astimezone seems to be using DST from past year
I'm converting UTC datetimes to America/Santiago tz using dt.astimezone(my_tz) through a Django manage.py command, but it seems to be using DST from past year. This code shows that DST changes at 12/08/2019, from -4 to -3, but this year this should be happening at 08/09/2019 (https://www.timeanddate.com/time/zone/chile/santiago) import pytz import datetime tz = pytz.timezone("America/Santiago") dt4offset = datetime.datetime.strptime(''.join('2019-08- 10T10:00:00+00:00'.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z') dt3offset = datetime.datetime.strptime(''.join('2019-08- 12T10:00:00+00:00'.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z') now = datetime.datetime.now() print('Now %s' % now) print('UTC: %s -> America/Santiago: %s' % (dt4offset, dt4offset.astimezone(tz))) print('UTC: %s -> America/Santiago: %s' % (dt3offset, dt3offset.astimezone(tz))) It prints: Now 2019-08-08 05:46:27.102422 UTC: 2019-08-10 10:00:00+00:00 -> America/Santiago: 2019-08-10 06:00:00-04:00 UTC: 2019-08-12 10:00:00+00:00 -> America/Santiago: 2019-08-12 07:00:00-03:00 Both of the tz convertions should have an offset of -4, but the second one changes acoording to the DST from 2018. I've coded this in Repl.it and it works as its supposed to: https://repl.it/@alejandrocarrasco/LightcyanHideousFlatassembler I'm running this script from docker-compose exec command. I thought my docker container was outdated but it is ok: docker-compose exec container date Prints 'Thu Aug 8 05:52:25 UTC 2019' (and now() from the code above is also ok). So, I think there is a problem with my server/django config. Both Ubuntu and Docker container have correct dates. … -
How to display username at login link in navbar after user has logged in
I want the login link in navbar to change and display the username of the logged user, Please help how would I achieve that views.py def login_request(request): if request.method == "POST": user_form = AuthenticationForm(request, data=request.POST) if user_form.is_valid(): username = user_form.cleaned_data.get("username") password = user_form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("loststuffapp:IndexView") else: messages.error(request, "Invalid username or password") user_form = AuthenticationForm() return render(request, "loststuffapp/login.html", {"user_form":user_form} ) login.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <p><button class="btn" type="submit" >Login</button></p> <p>If you don't have an account, <a href="/register <strong>register</strong></a> instead</p> {% endblock %} -
Error with "input file" in Django. Does not recognize the file
I have problems working with django images, when selecting an image in the django manager everything works correctly, but when creating my own form it does not work. That is, filling the entire form correctly, selecting the file normally, at the time of submitting the form, does not send it and deselects the file you select, and tells me that said field is required. It makes no sense, I select the image, send the form and tell me that the field is required, and the image I chose is deselected. Here my model: class Course(models.Model): instructor = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200) image = models.ImageField(upload_to = 'course') description = models.TextField() users = models.ManyToManyField(User, related_name = 'get_users') created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['title', 'created'] Here my view: class CourseCreateView(CreateView): model = Course fields = '__all__' template_name = 'courses/course_form.html' success_url = reverse_lazy('home') More explicit example of the problem: Fill in the form correctly: I click on the "Crear"/Create button, and the following happens: It tells me that the field is required and appears in the "I don't choose the file" input, what is happening? -
how to fix ajax call so i can hide my token?
i'm calling a ajax function in html file in which i have integrated python django URL in which i have to pass token for get something so the problem which i am facing is my token is showing while i do inspect page source in html page. i want to hide it using java-script or ajax how can i do that please look at my code below. $.ajax({ url : url, headers: {'Authorization': 'Token {{token}}'}, data : card_data, enctype : 'multipart/form-data', cache : false, contentType : false, processData : false, type : type, success : function(data, textStatus, jqXHR){ console.log(data); // Callback code if(data['status'] == 'error') { $("#lightbox").css({ 'display': "none" }); alert('error : ' + data['msg']); } else { $('#lightbox').find('h1').text('Saved, redirecting you to products page'); setTimeout(function(){ window.location.href = 'https://'+window.location.hostname+'/dashboard/destination/cards';}, 100); } } }); }); -
How to determine which button is pressed
I have a table in which I populate with data from the database. Some of this I have an extra feature of the delete button. But I can't understand how I get that what delete button is pressed in django <tbody> {% for i in list %} <tr> <td>{{i.id}}</td> <td>{{i.reason}}</td> <td>{{i.starting_date}}</td> <td>{{i.ending_date}}</td> <td>{{i.accept_or_not}}</td> {% if i.accept_or_not == 'pending'%} <td><input type="button" name="data_delete_{{i.id}}" value="delete"> </td> {%endif%} </tr> {% endfor%} </tbody> def profile_view(request): if 'data_delete_id' in request.POST: # i don't know how to determine the id in the button -
how to fix the error local variable 'ListQuery' referenced before assignment
i have a function in views.py that list all records and allow user to search for specific record where if filter the class "suspect" the problem that i got is once i tried to search the system crash and display the below error : local variable 'ListQuery' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/blog/list/ Django Version: 2.1.3 Exception Type: UnboundLocalError Exception Value: local variable 'ListQuery' referenced before assignment Exception Location: C:\Users\LT GM\Desktop\ABenvironment\myABenv\blog\views.py in listANDsearch, line 186 Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1 Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/list/ Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'widget_tweaks', 'import_export'] Installed 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'] Traceback: File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LT GM\Desktop\ABenvironment\myABenv\blog\views.py" in listANDsearch 186. elif ListQuery == []: Exception Type: UnboundLocalError at /blog/list/ Exception Value: local variable 'ListQuery' referenced before assignment views.py def listANDsearch(request): #deny anonymouse user to enter the list page if not request.user.is_authenticated: return redirect("login") else: queryset = suspect.objects.all() # return render(request,"blog/list.html", {"object_list":queryset}) #search query=request.GET.get("q") print("search … -
How to show successful message after edit and redirect to list view in django class based view?
I am having a list of 50 items showed in 5 pages(pagination), if i click edit button on an item in 3rd page. i will open a view to edit this item. After editing i need to go back to the same page(3rd one i this case) and show a success message there. Like update success. I have tired to show success message after the edit. But redirection is not possible. When i redirect success message is not possible. This is the way i redirect without having a success message list.html <td><a href="{% url 'test-app:edit-client-details' i.id %}?redirect_page={{ request.GET.page }}"><i class="fa fa-edit (alias) fa-fw" aria-hidden="true"></i></a></td> view.py def get_success_url(self): return '{0}?page={1}'.format(reverse_lazy('tayseer-admin:view-client-testimonials'),self.request.GET.get('redirect_page')) for showing success message in update view i used: def get_success_url(self): messages.add_message(self.request, messages.INFO, 'form updated success') return reverse("tayseer-admin:edit-client-testimonials", kwargs={'pk': self.kwargs['pk']}) in template i used. {% if messages %} <ul class="alert alert-success" id="msgclose"> {% for message in messages %} <ul{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }}</ul> {% endfor %} </ul> {% endif %} What i want is after editing the record, redirect to the exact page and show update was successful. Please help me get a solution for this. -
ConnectionRefusedError at /accounts/register/
When user enter email for password reset then error arise connection failure which is related to server failure error . raceback: File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\views.py" in dispatch 53. return super(RegistrationView, self).dispatch(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\generic\edit.py" in post 142. return self.form_valid(form) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\views.py" in form_valid 56. new_user = self.register(form) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\backends\default\views.py" in register 100. request=self.request, File "C:\ProgramData\Anaconda3\lib\site-packages\registration\models.py" in create_inactive_user 193. lambda: registration_profile.send_activation_email( File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\db\transaction.py" in exit 284. connection.set_autocommit(True) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\db\backends\base\base.py" in set_autocommit 409. self.run_and_clear_commit_hooks() File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\db\backends\base\base.py" in run_and_clear_commit_hooks 624. func() File "C:\ProgramData\Anaconda3\lib\site-packages\registration\models.py" in 194. site, request) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\models.py" in send_activation_email 451. email_message.send() File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\mail\message.py" in send 291. return self.get_connection(fail_silently).send_messages([self]) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\mail\backends\smtp.py" in send_messages 103. new_conn_created = self.open() File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\mail\backends\smtp.py" in open 63. self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\ProgramData\Anaconda3\lib\smtplib.py" in init 251. (code, msg) = self.connect(host, port) File "C:\ProgramData\Anaconda3\lib\smtplib.py" in connect 336. self.sock = self._get_socket(host, port, self.timeout) File "C:\ProgramData\Anaconda3\lib\smtplib.py" in _get_socket … -
Django Models - how to pull data from 2 models and render
I'm building a survey-like app using Django. I have 3 models (Survey, Question, Answer). I need to query the Questions model and pull back the Questions PLUS the possible Answers for each question. Then, i need to display it on the html page as a single question, with the possible answers in a list or other element. Django==2.2.1 / Pillow==6.1.0/ pytz==2019.1/ sqlparse==0.3.0/ Python 3.7 I tried going from the Answers model but I end up with duplicate data and uncertain how to render. MODELS.PY class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question_sequence = models.IntegerField() question_to_ask = models.CharField(max_length=4000, unique=True) def __str__(self): return self.question_to_ask class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) possibleAnswer = models.CharField(max_length=4000) possibleAnswer_image = models.ImageField(blank=True, null=True) def __str__(self): return self.possibleAnswer VIEWS.PY def survey(request): q = [x for x in Question.objects.all().values()] questions_dict = {'questions': q} # a = [x for x in Answer.objects.select_related().all()] # answers_dict = {'answers': a} return render(request, 'survey_app/survey.html', context=questions_dict) .HTML <body> <div class=questions> {% if questions %} <h1> {% for q in questions %}</h1> <p> {{ q.question_to_ask }}</p> <p> {% for a in answers %}</p> <p> {{ a.question.question_to_ask }}</p> {% endfor %} {% endfor %} {% else %} <p> NO RECORDS SHOWN</p> {% endif %} </div> </body> My goals is … -
Access a form method from generic.UpdateView in Django
I have a view which is a generic.UpdateView, and I need to access a form method - get_hidden_fields(). How do I access it? I currently used self.form_class().get_hidden_fields() but I'm not sure if this is correct. I think it creates a new instance of the form and I want to use the current instance. def get_context_data(self, **kwargs): cd = super().get_context_data(**kwargs) cd.update({ 'matches_list': self.page.object_list, 'form_hidden_fields': list(self.form_class().get_hidden_fields()), }) return cd https://github.com/speedy-net/speedy-net/blob/staging/speedy/match/matches/views.py#L54 -
How to redirect after a success message in Django
I am creating a newsletter app and having issues with the redirect function working after a success message is displayed to the user. I have already tried various approaches to refactoring - [How to pass a message from HttpResponseRedirect in Django? [https://github.com/zsiciarz/django-envelope/issues/28] from django.conf import settings from django.contrib import messages from django.shortcuts import render, redirect, reverse from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import get_template """ Create views """ from .forms import CustomerSubscriptionForm from .models import CustomerSubscriptionUser def customer_subscribe(request): form = CustomerSubscriptionForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if CustomerSubscriptionUser.objects.filter(email=instance.email).exists(): messages.warning(request, "So you've already subscribe to us, so visit your email to see what we have in store for you!") return redirect('/experiment/subscribe') - **This is where the problem is** else: instance.save() messages.success(request, "We are excited that you're interested in being in our local dance community! We sent some more information to your email") subject = "Thank you for joining our community" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] subscription_message = "Hi, LET'S DANCE. If you want to unsubscribe got to http://127.0.0.1:8000/experiment/unsubscribe/ " send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=subscription_message, fail_silently=False) context = {'form': form} template = "experiment/subscribe.html" return render(request, template, context) Expected result - user is redirected to the form view after submitting … -
Django-admin how to disble change data on foriengkey. I want to be button for view only
How to add view button replace change button. in the Image below. How to view only not change. My code model class1 class Return_data(models.Model): request_product = ( ('select', 'Select'), ('TN', 'TN'), ('TX', 'TX'), ('MT', 'MT'), ) invoice_no = models.CharField(max_length=25, verbose_name='Invoice No.') etd_atg = models.DateField(verbose_name='ETD ATG') eta_amgt = models.DateField(verbose_name='ETA AMGT') product = models.CharField( max_length=20, choices=request_product, default='select') q_ty = models.IntegerField(verbose_name="Q'ty (pcs)") listemail = ( ('select', 'Select'), ('chanaphon.chommongkhon@agc.com', 'chanaphon'), ('jeerawan.pongkankham@agc.com', 'jeerawan'), ) liststatus = ( ('select', 'Select'), ('pending', 'Pending'), ('finish', 'Finish'), ) attached = models.FileField(upload_to='file',verbose_name='Attached file') emailto = models.CharField(max_length=30, choices=listemail, default='select',verbose_name='Email Send To') emailcc = models.CharField(max_length=30, choices=listemail, default='select',verbose_name='Email CC') pc_status = models.CharField(max_length=20, choices=liststatus, default='select',verbose_name='PC Status') How to view only in foreign key detail : #model class2 class Return_QA(models.Model): liststatus = ( ('select', 'Select'), ('pending', 'Pending'), ('finish', 'Finish'), ) invoice_noqa = models.ForeignKey(Return_data, on_delete=models.CASCADE,verbose_name='Invoice No') object_lot = models.CharField(max_length=20,verbose_name='Objectlot') qa_status = models.CharField(max_length=10, choices=liststatus,default='select',verbose_name='QA Status')