Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django shows names instead of objects
I have array of inputs columns = [] def set_columns(self, col): for i in range(0,col): self.columns.append(forms.ChoiceField(self.choices)) And i want to show them {% for choice in columns %} <td>{{ choice }}</td> {% endfor %} But instead of inputs I am getting names of that inputs. -
how to insert choice fields?
i have to use two choice fields from Language_list. so, i want to add or replace ------ with each choice's title in Language_list. def __init__(self, auto_id='%s', *args, **kwargs): is not woring in my forms.... i did not mean this bring error. it is still running ,but it is nothing to change. here, my model and my list in my model Language_list=( ('AFRIKAANS','Afrikaans'), ('ALBANIAN','Albanian'), ('AMHARIC','Amharic'), ('ARABIC','Arabic'), ....) class MyUser(AbstractBaseUser): ..... Mother_language = models.CharField(max_length = 30,choices= Language_list,null = False) Wish_language =models.CharField(max_length = 30,choices= Language_list,null = False) ..... this is my form class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'placeholder': 'Password confirmation'})) class Meta: model = MyUser def __init__(self, auto_id='%s', *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['Mother_language'].choices = [('', ('Mother_language '))] + models.Language_list self.fields['Wish_language'].choices = [('', ('Wish_language '))] + models.Language_list widgets = { 'email': forms.TextInput(attrs={'size':30,'placeholder': 'Email'}), 'username': forms.TextInput(attrs={'size':30,'placeholder': 'UserName'}), } fields = ('email','username','Mother_language','Nationality','Wish_language','picture') -
How to use different staticfiles location based on if it is development or production server
This is my settings.py: import os import sys SECRET_KEY = 'secrit' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver') if RUNNING_DEVSERVER: DEBUG = True else: DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'ebdjangoapp-dev.us-east-1.elasticbeanstalk.com'] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'ebdjangoapp', 'storages', ) AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'Cache-Control': 'max-age=94608000', } AWS_STORAGE_BUCKET_NAME = 'ebdjangoappstaticfiles' AWS_ACCESS_KEY_ID = 'key' AWS_SECRET_ACCESS_KEY = 'secritkey' # Tell django-storages that when coming up with the URL for an item in S3 storage, keep # it simple - just use this domain plus the path. (If this isn't set, things get complicated). # This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it. # We also use it in the next setting. AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' # This is used by the `static` template tag from `static`, if you're using that. Or if anything else # refers directly to STATIC_URL. So it's safest to always set it. if RUNNING_DEVSERVER: STATIC_URL = '/static/' else: STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) # Tell the staticfiles app to use S3Boto storage when writing the collected static files … -
Django change static folder name to assets
I want to have following structure: my_project my_app assets 1.css in my base.html I include css like this: <link rel="stylesheet" href="assets/1.css" /> I tried to change setting.py like this: STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') and like this: STATICFILES_DIRS = [ "/assets/", ] But I still get the error that 1.css not found -
Django Success Message in view using django.contrib.messages
I am working on a system which allows a user to place a booking for an event for a Player object registered to their account. Previously I had the system redirecting to home page on success but I decided to try and implement a tool tip style pop up when the booking has been successful. I've tried a couple of things for this and none have quite worked for me. First I tried adding "message = 'Booking Successful.'" in my render command, along with a script in the html template. This gave me "render() got an unexpected keyword argument 'message'". Then I tried added it to the context dictionary after my form such that the render request reads: return render(request, 'tennis/make_booking.html', {'event_form': event_form, 'message': 'Booking Successful'}) This technically works but the message is displayed on page loading which isn't quite right. Then finally I tried a call to the Django message function as shown in my below code. This code pops up an empty message box when I load the page and when I click the book button it gives me an error which I'll provide the full stack trace of. views.py @login_required def make_booking(request): form = EventForm() if request.method … -
Django use static resource
I google for a long time, no use for me, some problems boring me. I wanna to know an easiest way to load my static resource in my web. My Django version is 1.10 -
How do you construct a django template variable dynamically
How do you dynamically construct a django template variable that is {{ variable_name_number }} that will have the number in variable_name_number in a range like 1 to 10? I started with the below but but how do I add i in variable_name? Also range() will not work in the for loop. {% for i in range(10) %} {{ variable_name}} # should be {{ variable_name_i }} {% endfor %} -
Persistent Internal Server Error (Django & Ajax)
I am using Ajax to transfer my data to views.py. I already terminated all my urls and used the form action for my url but the internal server error still persists. I can't seem to find the problem pls help HTML <form action = "{% url 'create_user' %}" id="create_user" method="post"> {% csrf_token %} <p class="label" id="l1"> Name: </p> <input type="text" class="textbox" id="name"><br> <p class="label" id="l2"> Username: </p> <input type="text" class="textbox" id="username"><br> <p class="label" id="l3"> Password: </p> <input type="password" class="textbox" id="password"><br> <p class="label" id="l4"> Confirm Password: </p> <input type="password" class="textbox" id="confirm"><br> <button id="signupbutton">Sign Up</button> <div id="separator"></div> </form> jQuery $("#signupbutton").click(function () { var username = $("#username").val(); var password = $("#password").val(); var confirm = $("#confirm").val(); var name = $("#name").val(); errorval = errorCheck(); if (errorval == 0) { // transform data input to dictionary var infoset = { "name": name, "username": username, "password": password }; console.log(infoset); var csrftoken = $.cookie('csrftoken'); $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var url = $('#create_user').attr('action'); $.ajax({ url: url, type: "POST", contentType: 'application/json', data: { "name": name, "username": username, "password": password }, success: function (data) { console.log(data); }, fail: function (data) { console.log("everything went to shit"); } }); $("#errormsg").text('creation successful'); … -
NoReverseMatch at
I have this error and I do not find solution, I get the keywords of ID_pedido_ex and cod_experto but I still throw the error, student help please? Reverse for 'entregado_ex' with arguments '()' and keyword arguments '{'id_pedido_ex': 11, 'cod_experto': 'VA-0012 '}' not found. 1 pattern(s) tried: ['solicitar/entregar-extra/(?P<id_pedido_ex>\\d+)/(?P<cod_experto>\\d+)/$'] button Template html: <a href="{% url "usuario:entregado_ex" id_pedido_ex=ex.id cod_experto=ex.articulo_ex.cod_experto %}" method='GET' type="submit" class="btn btn-success pull-right"/>Entregar</a> url global: urlpatterns = [ # Examples: url(r'^solicitar/', include(urls, namespace="usuario")), ] url app: urlpatterns = [ url(r'^entregar-extra/(?P<id_pedido_ex>\d+)/(?P<cod_experto>[\w-]+)/$', Update_stockex, name="entregado_ex"), ] views.py: @login_required def Update_stockex(request, id_pedido_ex, cod_experto): if request.method == 'GET': pedido = Pedido_Extra.objects.get(id=id_pedido_ex) articulo = Articulo.objects.get(pk=cod_experto) articulo.stock -= pedido.cantidad_ex articulo.save() pedido.estado_ex = 'entregado' pedido.fecha_entrega_ex = datetime.now() pedido.save() return HttpResponseRedirect('/solicitar/pedidos-extra/') -
Enclosing For Loop in Django around bootstrap html tags
Am so new to Python on Django. I like to wrap my Bootstrap HTML Tags around Django For..Loop handles such that I have my details from the database rendered in Columns. However, it didn't happen from what I have done. The second column actually got messed up. The columns are suppose to standing side by side. Note that if its only bootstrap tags, it renders very well the way its suppose to. Here is the pictorial view of the mess Below is my Python Django code: templates/app/home.html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Mentoring Services</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Mentoring Services"> <meta name="keywords" content=""> <meta name="author" content="Myrioi Solutions"> <!-- FAVICON --> <link rel="shortcut icon" href="images/favicon.ico"> <link rel="stylesheet" href="static/css/base.css"> {# Load the tag library #} {% load bootstrap3 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} </head> <body> <div class="intro" data-stellar-background-ratio="0.55" style="background-position: 50% 50%;"> <div class="container"> <div> <h4>Get mentored and be successful</h4> </div> <div class="#"> <h1 style="transition: none; text-align: inherit; line-height: 62px; border-width: 0px; margin: 14px 0px 9px; padding: 0px; letter-spacing: 0px; font-size: 55px; color: black"> Mentoring Directory </h1> <p class="lead">The … -
MySQL now allow data to be imported by phpMyAdmin
I have just ended up creating Django website and now using phpMyAdmin I am importing large data sets in my mode. However, it appears that there is something wrong with the column values which I am trying to import via phpMyAdmin. I see the following error: #1366 - Incorrect string value: '\x93Desig...' for column 'sku_description' at row 1 If it was one or two columns I could've manually fixed it. However, as I mentioned there is tons of data in there. What would be the most practical solution for this problem? -
Django REST framework: 'WSGIRequest' object has no attribute 'query_params'
I am learning DRF, and trying to print print request.query_params. But got error: print request.query_params AttributeError: 'WSGIRequest' object has no attribute 'query_params' Codes: class CourseDetailView(generics.RetrieveAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer def dispatch(self, request, *args, **kwargs): print request.user print 'CourseDetailView dispatch:', request.META #print request.data """ print 'parsers', request.parsers print request.accepted_renderer print 'authenticators', request.authenticators """ #print 'accepted_media_type', request.accepted_media_type print request.META['HTTP_ACCEPT'] print 'method', request.method print 'content_type', request.content_type print 'query_params' print request.query_params # Here return super(CourseDetailView, self).dispatch(request, *args, **kwargs) Part of my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', ] # DJANGO REST FRAMEWORK REST_FRAMEWORK = { } 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', ] -
Django Class Based Views and Queries
I am attempting to filter for a single object, more specifically, today's entry. I then want to take that query and display the result within the template. No matter what I do I can't seem to get the filter to display anything in the template. I am not sure whether I need the query to be written within the view, the model, or both. My familiarity with Django querying is pretty light. A great resource on this topic would be extremely helpful as well. I'm semi-new to Django, so any help you can provide would be much appreciated. models.py class Entry(models.Model): date = models.DateField(blank=True, null=True,) euros = models.CharField(max_length=500, blank=True, null=True) comments = models.CharField(max_length=900, blank=True, null=True) euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) def get_absolute_url(self): return reverse('argent:detail', kwargs={'pk': self.pk}) views.py: class IndexView(generic.ListView): template_name = 'argent/index.html' context_object_name = 'object_list' queryset = Entry.objects.all() filter = Entry.objects.filter(date=today_date) print(filter) class DetailView(generic.DetailView): model = Entry template_name = 'argent/detail.html' class EntryCreate(CreateView): form_class = EntryForm template_name = 'argent/entry_form.html' def form_valid(self, form): return super(EntryCreate, self).form_valid(form) class EntryUpdate(UpdateView): model = Entry form_class = EntryForm template_name = 'argent/entry_form.html' def form_valid(self, form): return super(EntryUpdate, self).form_valid(form) … -
non-ASCII characters in column names - a bad idea?
I'm using Django to prepare a small app. One of its features is a form which labels MUST be in Polish, using non-ASCII chars. I'm not sure if the db is going to stay sqlite, postgres or mysql. Now. I am tempted to use ModelForm to create the form but I don't know about the way of overriding the default labels' texts - i.e. - the respective columns' names. And that compels me to name the columns using non-ASCII letters. Is it a very bad idea? Could it potentially create many problems? Should I give up ModelForms and turn to Forms instead? Or maybe is there any other solution to combine English (ASCII) column names in the db, ModelForm and Polish labels with non-ASCII chars? I would be grateful for your advice :) -
Functionally Testing Object Model with Admin View in Django
Perhaps I'm being a bit pedantic, but, what I believe would solve this problem is handling how the Admin View handles a post request, manually. Perhaps this can be done with AdminSite. Here's the test I'm running (with a Post object model, and the fields should be clear): class AdminTest(LiveServerTestCase): def setUp(self): self.my_admin = User(username='user', is_staff=True, is_superuser=True) self.my_admin.set_password('passphrase') self.my_admin.save() def test_create_post(self): loginresponse = self.client.login(username='user', password='passphrase') self.assertTrue(loginresponse) response = self.client.get('/admin/blogengine/post/add/', follow=True) self.assertEqual(response.status_code, 200) response = self.client.post('/admin/blogengine/post/add/', data={ 'title': 'My first post', 'text': 'This is my first post', 'pub_date': timezone.now(), }, follow=True ) post_html = response.content.decode() self.assertEqual(response.status_code, 200) self.assertIn('My first post', post_html) self.assertIn('This is my first post', post_html) self.assertEqual(Post.objects.count(), 1) ` It fails on the last line, with the object count equal to zero, indicating, as far as I can tell, that the self.client.post() didn't make it through to the ORM. Any ideas on either another method of doing this, or a method of handling the view directly from the AdminSite? -
Trigger if form has change. Django
I have a trouble ticket system. Users create ticket and get info to email. How can i send new info when ticket changed from admin panel? model: class TroubleTicket(models.Model): title = models.CharField(max_length=200') name = models.CharField(max_length=200') address = models.CharField(choices=ADDRESSES', default=None, max_length=200) room = models.CharField(max_length=50') message = RichTextUploadingField() state = models.CharField(choices=STATES max_length=30, default='New') answer = RichTextUploadingField(blank=True, null=True) email = models.CharField(max_length=200, blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True') def __unicode__(self): return self.title def get_absolute_url(self): return reverse('ticket_detail', kwargs={'pk': self.id}) class Meta: ordering = ['-create_date'] save form and sending a message if the user specified a mail: class CreateTicket(CreateView): template_name = 'incidentjournal/add_ticket.html' form_class = TicketForm model = TroubleTicket context_object_name = 'ticket' success_url = reverse_lazy('home') def form_valid(self, form): recipient = form.cleaned_data['email'].encode('utf8') new_ticket = form.save() new_ticket_id = new_ticket.pk address = new_ticket.address.encode('utf8') title = new_ticket.title.encode('utf8') name = new_ticket.name.encode('utf8') room = new_ticket.room.encode('utf8') send_to_email(recipient, str(new_ticket_id), title, address, room, name) send_to_bot(str(new_ticket_id), title, address, room, name) return super(CreateTicket, self, ).form_valid(form) Now if state or answer has been changed in the admin panel I want to send a message to the user with these changes Thanks for any advise -
djnago media production digital ocean
i created my website and media was working fine , but now in production static files are okay but media files doesn't work. when making a new post by a user usually you would have to put a thumbnail and you also have the ability to use the text editor to add pics into your post. using django-summernote. anyways it should upload them to media root in the server but it doesn't it just gives me 500 server error and in the editor it gives me Got an error uploading an image: Failed to save attachment my urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my settings.py STATIC_URL = '/static/' STATIC_ROOT = '/var/www/static-root/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), # '/var/www/static/', ] MEDIA_URL = '/media/' MEDIA_ROOT = '/var/www/media-root/' ive read that i might need to serve my media and static in another server why? static works fine but media doesn't if there's a way to fix it please help me or if i needed to serve it somehow please help with it btw im using Debian for the django code -
Searching matching strings in 2 lists does not work at all
I am developing a specific feature for a website (using Django) and I need to compare 2 lists of strings. The first list contains some required identificators and the second one contains some other identificators. I have to verify which id from the first list is missing in the second one, doing this: def mods_checker(request): html = request.POST["text"] all_mods = Mod.objects.exclude(deprecated=True) soup = BeautifulSoup(html, "html.parser") links = soup.find_all('a', {'data-type': 'Link'}) ids = [] all_ids = [] missing_mods = [] for l in links: ids.append(get_id(l.text)) for m in all_mods: all_ids.append(m.get_id()) print ids print all_ids for m in all_mods: if m.get_id not in ids: missing_mods.append(m.name) return HttpResponse(json.dumps(missing_mods)) (Sorry for the indentation, of course everything is ok in my editor) I know that this piece of code is redundant, I did it to do some checks and some debug prints. The problem is that I get a wrong set of ids (all of them, more specifically) and I don't know why. Every check I did in python editor with test data is ok. What am I doing wrong? Every print is fine and I get all ids correctly. -
ImportError: No module named django_libs.models_mixins
I am getting the following error: ImportError: No module named django_libs.models_mixins Does somebody know how to fix this? I am a django noob... -
Django visitor counter for overall website/app not for any specific object
I am a python/Django newbie. I managed to deploy a Django based website based 'somehow' to save my job :). I know this has already been answered on SO but I couldn't get things working. I want to expand it and would like to start with a visitor counter to show what impact I made to my company. My current website is hosted on RHEL 7 using Mysql, mod_wsgi, Django 1.10, Python3.5. Is there any visitor counter with complete guide which doesn't need a lot of work to set up? Any recommendations? Thanks in advance. -
django migration Model has no field named True
I have run into a migration problem. I have a simple model class MyUser(models.model): user = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True) user_roles = ((,), (,), ) role = models.CharField(max_length = 40, choices = user_roles) users_organisation = models.OneToOneField(Organisation, blank=True, null=True, on_delete = models.CASCADE) class Organisation(models.Model): name = models.CharField(max_length = 40, default ="name") address = AddressField() class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) first_name = models.CharField(max_length = 100) last_name = models.CharField(max_length = 100) user_name = models.CharField(max_length = 100) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_admin = False USERNAME_FIELD = 'email' objects = MyUserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email These are the model. It was working fine but suddenly I did a migration and I am in trouble. Applying app.0001_initial...Traceback (most recent call last): File "/home/user/.local/lib/python3.5/site- packages/django/db/models/options.py", line 617, in get_field return self.fields_map[field_name] KeyError: True During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/.local/lib/python3.5/site- packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/user/.local/lib/python3.5/site- … -
Saving Applicant model in database fails, why?
I am building a django web app which requires users to be able to apply for jobs. Here is the relevant model for the applicant: class Applicant(models.Model): job = models.ForeignKey(Job) user = models.ForeignKey(User) date = models.DateTimeField(auto_now_add=True) class Meta: # So that the same user can't apply to the same job twice. unique_together = [("job", "user"),] Here is the view using this model to create and save an applicant: @login_required def job_apply(request, job_pk): # Get the job that the user has applied for. job = get_object_or_404(Job, pk=job_pk) applicant = models.Applicant(job=job, user=request.user) applicant.save() return reverse('jobs:find') This is the error message that django gives me: Exception Type: AttributeError Exception Value: 'unicode' object has no attribute 'get' -
Regular expression to match one or more patterns matching another regular expression
I am using regular expressions for my django url configurations. I have the following regex: url(r'^myapp/prices/?([X]{1}[A-Z0-9]{3}:[A-Z0-9]{1}[A-Z09.-]{1,4})/?([0-9]{0,3})/?$', views.prices, name='prices'), This matches urls such as: htpp://127.0.0.1/myapp/prices/XNAS:GOOG/1 htpp://127.0.0.1/myapp/prices/XNAS:GOOG htpp://127.0.0.1/myapp/prices/XNAS:FB/10 I want to modify my regex pattern in my url pattern, so that I can match on strings like the above, as well as strings like the one below: htpp://127.0.0.1/myapp/prices/XNAS:GOOG+XNAS:TSLA+XNAS:FB/1 Essentially, I want my original pattern to be matched at least once, and if more than once, then the occurrences of the pattern should be separated by a '+' sign. How would I express this using regex syntax (Python) -
Sending data from my views to a html template
Im trying to create a website where users input some figures then returns some data based on these #views.py def formview(request): if request.method == 'POST': form = MyCalculator(request.POST) if form.is_valid(): myform = MyCalculator() myform.parents = form.cleaned_data['parents'] myform.jobs = form.cleaned_data['jobs'] myform.grants_bursaries_scholarships = form.cleaned_data['grants_bursaries_scholarships'] myform.student_loan = form.cleaned_data['student_loan'] myform.other_income = form.cleaned_data['other_income'] myform.rent = form.cleaned_data['rent'] myform.travel = form.cleaned_data['travel'] myform.bills = form.cleaned_data['bills'] myform.other_outcome = form.cleaned_data['other_outcome'] def total_income(self): return self.myform.parents + self.myform.jobs + self.myform.grants_bursaries_scholarships + self.myform.student_loan + self.myform.other_income def fixed_outcome(self): return self.myform.rent + self.myform.travel + self.myform.bills + self.myform.other_outcome def variable_outcomes(self): return self.total_income() - self.fixed_outcome() def food(self): return (43.66 * self.variable_outcomes) / 100.0 def socialising(self): return (22.54 * self.variable_outcomes) / 100.0 return render(request, 'Noteable_Budgeting/out.html', {'food' :food, 'socialising' :socialising}) else: print (form.is_valid()) print (form.errors) else: form = MyCalculator() return render(request, 'Noteable_Budgeting/calculator_list.html', {'form':form}) def failview(request): return render(request, 'Noteable_Budgeting/fail.html') and my #out.html {% block titleblock %} <title>Noteable Budgeting</title> {% endblock %} {% block sidebar %} {% block content %} <div class="text2"> <br> <br> <h2><i>(:-D)</i></h2> <br> <br> <h1> Your recommended spending amount on food is <u> {{ food }} <u> , <u> {{socialising}} </u>. {% for food in foood %} {{ food }} {% endfor %} </h1> <br> <b><a href="/calculator/test/">back</a></b> </div> {% endblock %} {% endblock %} I want to send … -
Cannot assign "'18'": "Pedido_Extra.especialidad_ex" must be a "Especialidad" instance
I have this error when saving the entered data of the form of the model, and I also want to save the id of the specialty captured in get, how to solve it? Any help please! views.py: def PedidoExtra(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': form = ExtraForm() else: form = ExtraForm(request.POST) if form.is_valid(): esp = form.save(commit=False) esp.especialidad_ex = id_especialidad esp.save() form.save() return render(request, 'form2.html', {'form':form, 'especialidad':especialidad})