Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden (CSRF cookie not set) csrf_exempt
I'm returning with a 403 Forbidden (CSRF Cookie not set) error on a CBV with csrf_exempt being called on dispatch either via the csrf_exempt decorator or using CsrfExemptMixin from django-braces. Not quite sure why as other views using CsrfExemptMixin works fine class CaseDeletedView(CsrfExemptMixin, View): def post(self, request, *args, **kwargs): ... return HttpResponse(status=204) With decorator class CaseDeletedView(CsrfExemptMixin, View): def post(self, request, *args, **kwargs): ... return HttpResponse(status=204) @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
Django widget that depends on model
I am pretty new to django and have a question. I got a ModelForm using Widgets. Since I have a field called discount which I only want to be editable if the displayed model fullfills some requirements, I make it read-only using a widget entry: class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': True})} Now I want to make it possible to write to this field again, iff the Model (here called Order) has its field type set to integer value 0. I tried to do so in the html template but failed. So my next idea is to make the widget somehow dependent to the model it displays, so in kinda pseudocode: class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': currentModel.type == 0})} Is there a proper way to do something like this? Thanks in advance -
django emoji with mysql, charset settings
First: DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': '<DB_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<DB_host>', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', 'use_unicode': True, }, } } Second: DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': '<DB_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<DB_host>', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } I found a website that explain First one to use emoji on django application. But I also found that Second one is also working well through using emoji. Which one is correct or good enough for production django application? Which is considerable for production? My database: AWS RDS MySQL 5.7.19 -
Django template translation not working as expected
I am using django 2.1 , here is all the settings related to translation: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', _('English')), ('bn', _('Bengali')) ) LOCALE_PATH = ( os.path.join(BASE_DIR, 'locale') ) TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = False Template tag that I want to translate: {% load i18n %} <div class="widget widget-about"> <h4 class="widget-title">{% trans "About Us" %}</h4> </div I run both ./manage.py makemessages --all ./manage.py compilemessages commands , also added translation in .po file after makemessages command: # locale/bn/LC_MESSAGES/django.po #: templates/partials/footer.html:8 msgid "About Us" msgstr "আমাদের সম্পর্কে" When I changed the language code from en to bn, template string still rendering the default english "About Us". Here are all the codes that I am using for changing language: <div class="header-dropdown"> {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'en' %} <a href="#"><img src="{% static 'image/flag/en.png' %}" alt="flag">ENGLISH</a> {% else %} <a href="#"><img src="{% static 'image/flag/bn.png' %}" alt="flag">বাংলা</a> {% endif %} <div class="header-menu"> <ul> <li><a href="{% url 'change_language' %}?lan=en"><img src="{% static 'image/flag/en.png' %}" alt="USA Flag">ENGLISH</a></li> <li><a href="{% url 'change_language' %}?lan=bn"><img src="{% static 'image/flag/bn.png' %}" alt="Bangladesh Flag">বাংলা</a></li> </ul> </div><!-- End .header-menu … -
How to sort django queryset with two fields while creating duplicates
I have a Deadline model which have two fields, start_date and end_date. I want to sort the queryset with both the fields but have a copy of deadline for each date I tried creating annotated common fields and ordering through that. class Deadline(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField dl_start = deadline_queryset.annotate(date=F('start_date')) dl_end = deadlien_queryset.annotate(date=F('end_date')) dl_all = dl_start.union(dl_end).order_by('date') I need a timeline of events. If I've 2 deadline objects: D1(12-dec, 24-jan) and D2(15-dec, 21-jan), I need a list of deadlines like D1, D2, D2, D1 -
Using date filter in Django template raises TemplateSyntaxError
I'm trying to format a datetime using Django built-in date filter. When I use {{ thread.added_at|date }}, it works as expected and the date printed is similar to "Dec. 21, 2018". But since I also want to format the date, I use the filter like this: <span>{{ thread.added_at|date:"d m y" }}</span> When I try to load the page, I get a TemplateSyntaxError: TemplateSyntaxError at /questions/ expected token 'end of print statement', got ':' The website runs on Django 1.8.19. In Django 1.8 documentation, date filter appears to be able to be used like that. What is the problem in my template? -
Django ORM Issue With Column Not Existing
I am attempting to debug an employee's work and I am kind of hitting a wall. For context: we have a models package called objects_client, in this package we have a model called UnitApplication. There is not a visible column in the UnitApplication model. And there are no references elsewhere in code that we have actually written that calls for the column objects_client_unitapplication.visible. All I am trying to do is gather the object using the usual Django ORM, in my mind this should not provide me with any errors, I am just grabbing a row from a database based on an id. Also a note: the variable db_connection is correct and it references a client database, as this is where I am grabbing the data from. What is going on? I get the same error when I attempt to gather all objects using UnitApplication.objects.using(db_connection).all() try: print('before gathering property_unit_application_obj') # THE ERROR HAPPENS HERE --------- # column objects_client_unitapplication.visible does not exist property_unit_applications_obj = UnitApplication.objects.using(db_connection).get(property_id=int(property_id_param)) print('prop_unit_app_obj: {}'.format(property_unit_applications_obj)) except Exception as ex: print('Exception: {}'.format(ex)) Here is the full traceback without the exception clause: Traceback (most recent call last): File "C:\Users\mhosk\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column objects_client_unitapplication.visible does not exist … -
How is the zip function used in Python3?--A movie recommendation system project
Syntax error displayed when I try to run. The zip function should have been misused, but I don't know how to fix it. This is a movie recommendation system project in machine learning Web applications. I try the following method movies, moviesindxs = zip(*literal_eval(data.get("movies"))) This is part of the code # since def rate_movie(request): data = request.GET rate = data.get("vote") print(request.user.is_authenticated) movies, moviesindxs = zip(*literal_eval(data.get("movies"))) movie = data.get("movie") movieindx = int(data.get("movieindx")) # save movie rate userprofile = None if request.user.is_superuser: return render(request,'books_recsys_app/superusersignin.html') #return render_to_response( #'books_recsys_app/superusersignin.html', request) elif request.user.is_authenticated: userprofile = UserProfile.objects.get(user=request.user) else: return render(request,'books_recsys_app/pleasesignin.html') #return render_to_response( #'books_recsys_app/pleasesignin.html', request) This is the content of the error report SyntaxError at /rate_movie/ invalid syntax (<unknown>, line 1) Request Method: GET Request URL: http://127.0.0.1:8000/rate_movie/?vote=4&movies=%3Czip%20object%20at%200x112a0ce08%3E&movie=Some%20Kind%20of%20Wonderful%20(1987)&movieindx=602 Django Version: 2.1.4 Exception Type: SyntaxError Exception Value: invalid syntax (<unknown>, line 1) Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py in parse, line 35 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.0 Python Path: ['/Users/changxuan/PycharmProjects/reconmendationSystem/ReconSystem', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] Server time: 星期四, 10 一月 2019 11:04:41 +0000 -
Replace a char in django template before final rendering
I want to make all of my asterisks (*) in a template in red color in a Django Template. (E.g. in form labels that * symbol points the field is required. But when putting * in label of a form field it is rendered as black color as usual. How can I accomplish this by for example registering a filter or tag? Note that I use some libraries (e.g. bootstrap4 form) and the page is full of {{ }} tags. BUT I want to find&replace all ;black *' with 'red *' in final rendered html page. -
Rewrite Django Checkbox widget to use record fields
I have a model with a field that is has ManyToMany relationship with another model. When displaying this relationship in a form for selection I'm color coding the checkbox based on field contents within the related table. So my checkboxes are generated as follows: {% for addon in addons %} <div class="col-xl-12"> <div class="{% if addon.css_class == 'featured' %}checkbox-terms {% endif %}{{ addon.css_class }} extra"> <input type="checkbox" id="{{ addon.css_class }}" name="addons" value="{{ addon.id }}" id="id_addons_{{ forloop.counter0 }}"> <label for="{{ addon.css_class }}"><span class="{% if addon.css_class == 'featured' %}checkbox-terms{% else %}{{ addon.css_class }}{% endif %}-icon"></span> <div class="{{ addon.css_class }}-title">{{ addon.name }}</div> <div class="{{ addon.css_class }}-description">{{ addon.description }}</div> </label> </div> </div> {% endfor %} I would like to turn this into a widget subclass of forms.CheckboxSelectMultiple. So I've subclassed using: class AddOnCheckboxSelectMultiple(forms.CheckboxSelectMultiple): template_name = 'django/forms/widgets/addon_checkbox_select.html' option_template_name = 'django/forms/widgets/addon_checkbox_option.html' But in order for this to work I need to access field values within each record when rendering the checkboxes through the widget. Is this possible, and if so, how do I do it? Thanks -
unexpected keyword argument thrown when passing values to task using *args
I am new to celery, and have run into the following: I have a task that is part of a django application, and it takes in the following: def run_tests_report(correlation_id, workers, *args) The value(s) that gets passed to *args is a string defined in our django data model as test_name_or_mark = models.CharField as part of a function in base.py run_tests_report() gets called by tasks.append( task.si(correlation_id=request.correlation_id, workers=request.workers, test_name_or_mark=request.test_name_or_mark) when I attempt to use this task with a our request the following error is thrown: TypeError: run_tests_report() got an unexpected keyword argument 'test_name_or_mark' I have been able to assert that the value of test_name_or_mark is a string that contains the value I expect. I have also been able to validate that this works when I make a direct call to the task: with workers: In [4]: run_tests_report('alwaysbetesting9_no_workers_multiple_marks', '2', 'smoke', 'fix', 'regression') MORE THAN ONE smoke or fix or regression workers multiple marks without workers: In [2]: run_tests_report('alwaysbetesting8_no_workers_multiple_marks', 0, 'smoke', 'fix', 'regression') MORE THAN ONE smoke or fix or regression no workers multiple marks I am confused as to why this is not working now that I am calling the task with django. Do I need to update the data model? -
Django: How do I perform a CreateView redirect properly?
To perform a redirect I do return redirect([...]). However, that only works, if I additionally do def get_success_url(self):. The url in it actually doesn't matter, as it is using the redirect of my def form_valid(self, form):. Do you know how to avoid the get_success_url? I also tested to just move the return from form_valid to get_success_url. But then I receive an error that return is missing. class AdminRewardCreate(AdminPermissionRequiredMixin, SuccessMessageMixin, FormValidationMixin, AdminBaseRewardView, CreateView): form_class = RewardForm template_name = 'rewards/admin/create.html' success_message = _("Reward has been successfully created.") def form_valid(self, form): instance = form.save(commit=False) instance.event = self.request.event # when the super method is called the instance # is saved because it's a model form super().form_valid(form) return redirect( 'rewards:admin:index', self.request.organizer.slug, self.request.event.slug ) def get_success_url(self): return reverse( 'rewards:admin:index', kwargs={ 'organizer': self.request.organizer.slug, 'event': self.request.event.slug, } ) -
Model field doesn't get updated on first save
I've got this UpdateView I'm using to update my channels: class ChannelUpdate(UpdateView, ProgramContextMixin): model = ChannelCategory form_class = ChannelForm template_name = 'app/templates/channel/form.html' def dispatch(self, request, *args, **kwargs): return super(ChannelUpdate, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('channel_index', args=[self.get_program_id()]) def get_context_data(self, **kwargs): context = super(ChannelUpdate, self).get_context_data(**kwargs) context.update({ 'is_new': False, }) return context def form_valid(self, form): channel = Channel.objects.get(id=self.kwargs['pk']) channel_codes = ChannelCodes.objects.filter(channel_id=channel.pk) if 'is_channel_enabled' in form.changed_data: for channel_code in channel_codes: channel_code.is_active = channel.is_channel_enabled channel_code.save() return super(ChannelUpdate, self).form_valid(form) So when I edit a Channel, I have a checkbox, which changes my bool value for my model field is_channel_enabled to either True or False. If I do so, I trigger my if-statement in the def form_valid method which then loops through all my channel_codes and sets their bool field is_active to the same value as the bool field is_channel_enabled from my Channel. But my problem right now is: Lets say I uncheck the box and after I save my form, the bool still is True even though I've unchecked the box and it should be False, but if I then edit my Channel again and check the box, the bool changes to False, so that every time I check the box, the exact opposite happens: … -
how to upload image from the form using django with jqery and ajax
upload image beside other data when user submit the form. the form was adding the data correctly before i add the image field now it doesn't add any data to the database i added picture field to the model added picture element in the form added the input tag in the html send the data through AJAX to the view getting the data from ajax request and added to the view function models.py picture = models.ImageField(upload_to = 'pictures/%d/%m/%Y/',null=True, blank=True) form.py from django import forms from blog.models import te2chira, destination class SaveTe2chira(forms.ModelForm): class Meta: model = te2chira fields = ['title', 'description','picture' ] html <form method="POST" class="form-style-9" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <li> <input type="file" id="img" name="img"/> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="save" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() // year=$('#year').val() // date=$('#date').val() num=$('#num').val() title=$('#title').val() text=$('#text').val() issent=0 img = $('#img').prop('files')[0] $.ajax({ url:'/create/te2chira', method:'POST', data: { n:num, ti:title, te:text, s:0, img:img }, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "/creativePageSend.html" alert('success') }).fail(function(err){ alert('no success') }) }) }) </script> </li> </ul> </form> views.py def post_new(request): title = request.POST['ti'] description = request.POST['te'] num=request.POST['n'] issent=request.POST['s'] img = request.FILES['img'] n=te2chira.objects.create(title=title,te2chira_date=timezone.datetime.now(),description=description,num=num,is_sent=issent,picture = img) print(timezone.datetime.now()) n.save() id=n.te2chira_id request.session['idTe2chira']=id return render(request,'./creativePageSend.html',{'id':id}) upload the image with … -
Django fixture for extrernal translation app. How can I load the data?
I am using django-hvad to translate some fields in my models. For example: from django.db import models from hvad.models import TranslatableModel, TranslatedFields class Article(TranslatableModel): name = models.CharField(max_length=255, unique=True) translations = TranslatedFields( description=models.CharField(max_length=255), ) At the same time I would like to use django fixtures and load some sample data into the model with python manage.py loaddata articles.json: articles.json [ { "model": "posts.Article", "pk": 1, "fields": { "name": "First article" } }, I know that django-hvad creates additional tables for translations. In this case there will be posts_article_translation table. I cannot populate this table with following json, because obviously there is not Article_translation model: { "model": "posts.Article_translation", "pk": 1, "fields": { "description": "Good article", "master_id": 1 } }, What can be a better solution to populate translations fields? -
How to do jsonrpc with django?
For doing REST, we have DRF. Is there a similar framework for doing JsonRPC? The alternatives that I have found are not very inspiring. Is there a recommended approach to JsonRPC in Django? Is it possible to use DRF with JsonRPC instead of REST? -
How to send information on my email from django form? - Django 2
How to send information on my email from django form. Now I can see information only in my console output on my cmd template: {% extends 'base.html' %} {% load widget_tweaks %} {% block title %} Contact Us {% endblock %} {% block content %} <h2 class="mt-4 ml-4">Contact Me</h2> <form method="post"> <div class="container mt-4"> {% csrf_token %} <div class="col-md-4"> {{ form.subject.label }} {% render_field form.subject class+="form-control" %} </div> <div class="col-md-4"> {{ form.email.label }} {% render_field form.email type="email" class+="form-control" %} </div> <div class="col-md-4"> {{ form.message.label }} {% render_field form.message class+="form-control" rows="4" cols="6" %} </div> <div class="form-actions"> <button type="submit" class="btn btn-primary mt-2 ml-3">Send</button> </div> </div> </form> {% endblock %} forms.py: from django import forms class ContactForm(forms.Form): email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=False) views.py: from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def emailView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['yarik.nashivan@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message. <p>You will be redirected to … -
How to set up communication between two apps in Django?
I am currently trying to build a web app Todo task manager with Django as I find that the best way to learn is to get your hands dirty but I have come across a problem and I don't really know what is the Django way of doing it.. At the moment I have two apps in my project, one is 'lists' and the second is 'tasks', and my problem is that on the frontend, I need to show the different lists and associate them the tasks that are related to each list. So far I have managed to get the result visually by giving a list id to my tasks using a foreign key and importing the 'Task' model to the 'lists' views.py to then do the Querrry for tasks within the views.py of the lists app so that I can loop through them on the frontend but I feel like I'm making a frankeistein app now as they are both interdependent How would you guys handle the situation? ps: here an excerpt of my code for context from tasks.models import Task def lists_view(request): lists = List.objects.all() tasks = Task.objects.all() print("The request: ", request) context = { 'lists': lists, … -
Many to many queryset eroor
I am using ManyToManyField in my in Model. But when i am using custom queryset on field it is giving me validation error Select a valid choice. 2 is not one of the available choices. Because of this line: self.fields['user_groups'].queryset = Groups.objects.filter(group_company=self.user_company) but when i am using it without above line it is working perfectly fine. Forms.py class ManagerProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['user_company', 'user_groups'] def __init__(self, *args, **kwargs): self.user_company = kwargs.pop('user_company', None) super().__init__(*args, **kwargs) self.fields['user_groups'].queryset = Groups.objects.filter(group_company=self.user_company) Model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_groups = models.ManyToManyField(Groups,related_name='user_groups') -
django_celery_beat - "no such table: main.django_celery_beat_solarschedule__old" while updating "django_celery_beat_periodictask"
I'm using django + celery, when running django devserver I'm getting exception django.db.utils.OperationalError: no such table: main.django_celery_beat_solarschedule__old and callstack tells that it occured while doing insert into table django_celery_beat_periodictask Database is sqlite3. Calling code: `def register_task(task, interval=DEFAULT_TASK_INTERVAL): logger.info("Registering periodic task %s with interval %s", task, interval) name = "Default {}".format(task) schedule, _ = IntervalSchedule.objects.update_or_create( every=interval, period=IntervalSchedule.SECONDS) PeriodicTask.objects.update_or_create( name=name, defaults={ "interval": schedule, "task": task })` Actual traceback: File "/home/zab/Git/overview-server/overview-server/src/basis/tasks/shedule.py", line 21, in register_task "task": task File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django_celery_beat/managers.py", line 14, in update_or_create obj, created = self.get_or_create(defaults=defaults, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 489, in get_or_create return self._create_object_from_params(lookup, params) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 521, in _create_object_from_params obj = self.create(**params) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/zab/venv/overview/lib/python3.5/site-packages/django_celery_beat/models.py", line 316, in save super(PeriodicTask, self).save(*args, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/base.py", line 880, in _do_insert using=using, raw=raw) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/query.py", line 1125, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/zab/venv/overview/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1285, in execute_sql cursor.execute(sql, params) File … -
How can I add static files without using Djstatic and Whitenoise?
I was trying to use Whitenoise and Djstatic to server Django static files on Heroku to me I feel they are quite complicated does anyone have an alternative -
use base64 to upload image to nginx+uwsig+django,when image size larger than 2M,the request can't get it
I'm using base64 to upload image to django, when image size larger than 2M,the server can't get the image I set up the uwsgi and nginx conf, make the upload size 75M ,but it didn't work image1 = base64.b64encode(open(file_path, 'rb').read()) r = requests.post(url, data={"image": image1}) =============== server: result = request.POST.get("image") -
How to solve return outside function in Django
I have this code but it displays return outside function error Am I doing something wrong. How do I fix it? class vote(request,question_id): question = get_object_or_404(Question,pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesnotExist): return render(request,'polls/detail.html', { 'question':question, 'error_message':"You didn't select a choice.",}) else: selected_choice.votes +=1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args=(question.id,))) -
django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie"
After make migrations , i tried to do migrate, but i am getting the django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie" from django.db import models import date time from django.contrib import admin class Movie(models.Model): CHOICES_MOVIE_TYPE = ( ("SF", 'Short-Film'), ("P", "Promo"), ("OT", 'Other'), ); CHOICES_LANGUAGE_TYPE = ( (" ", ''), ); CHOICES_ORIGINAL_OWNER_TYPE = ( ("OT", 'Other'), ); CHOICES_REMARK_TYPE = ( ); _id = models.AutoField(primary_key=True) name = models.CharField(max_length = 50, blank = False) Movie_Type = models.CharField(max_length = 2, choices = CHOICES_MOVIE_TYPE, default = "OT", blank = False) language = models.CharField(max_length = 5, choices=CHOICES_LANGUAGE_TYPE, default = "OT", blank = False)enter code here tags = models.TextField() original_owner = models.CharField(max_length = 2, choices = CHOICES_ORIGINAL_OWNER_TYPE, default = "OT", blank = False) Partner = models.CharField(max_length = 10) acquisition_cost = models.DecimalField(max_digits = 5, decimal_places = 4, blank = True) release_date = models.DateField(("Date"), default = datetime.date.today) -
Django How to present user values on built-in EditProfileForm
My form is like at the photo . I want to show user's data like name , lastname , phone number ... https://imgur.com/a/5qgvNC1 in my forms.py i edit the EditProfileForm as CustomEditProfileForm . I am trying to give user's data in value part (value':User.Accounts.name) . I dont know how to pull the data from accounts model. class CustomEditProfileForm(EditProfileForm): name = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','value':User.Accounts.name})) middlename = forms.CharField(widget=forms.TextInput(attrs={'value':'username'})) lastname = forms.CharField(widget=forms.TextInput(attrs={'value':'username'})) highschool = forms.CharField(widget=forms.TextInput(attrs={'value':'highschool'})) college = forms.CharField(widget=forms.TextInput(attrs={'value':'college'})) citystate = forms.CharField(widget=forms.TextInput(attrs={'value':'citystate'}))