Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2 Bootstrap4 form validation style
I’m trying to incorporate the ‘red’ ‘green’ bootstrap validation feedback, but I just can’t get it to work. I’ve tried different combinations of classes, but I’ve never gotten it to show green on is_valid, I can’t remember if my error messages displayed correctly either(since deleted-wasn’t sure if they were messing with it). Form.py class EmployeeNameForm(ModelForm): class Meta: model = CustomerEmployeeName fields = [ 'employee_choices', 'first_name', 'middle_name', 'last_name', ] widgets = { 'employee_choices': Select( attrs={'class': 'form-control', }), 'first_name': TextInput( attrs={'class': 'form-control', 'placeholder': 'First', }), 'middle_name': TextInput( attrs={'class': 'form-control', 'placeholder': 'Middle (optional)', }), 'last_name': TextInput( attrs={'class': 'form-control', 'placeholder': 'Last', }), } View.py def create_employee_profile(request): if request.POST: name_form = EmployeeNameForm(request.POST) if name_form.is_valid(): new_name_form = name_form.save() return redirect(new_name_form) else: return render(request, 'service/template_create_or_update_profile.html', {'name_form': name_form} ) else: name_form = EmployeeNameForm( initial={'employee_choices': 'E'} ) return render(request, 'service/template_create_or_update_profile.html', {'name_form': name_form} ) Base.html {% load static %} <!DOCTYPE html> <html lang="en" <head> <!-- Required Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"> <!-- Jquery link --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <!-- Popper link --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script> <!-- Bootstrap 4 link --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script> <!-- static.style.css --> <link rel="stylesheet" href="{% static 'style.css' %}" type="text/css" … -
Django Admin Selective Inline Model
in Django admin site the inline model looks like this: the many to many objects appear in a dropdown. is there anyway (or a library) to show all the objects in a table and each row with a checkbox so the user could select each object they want? thank you for helping sorry about the image quality -
Issue with users model in zinnia and cookiecutter-django integration
First of all my setup: Linux Mint 18.2 Zinnia 0.20 Django 1.9.9 cookiecutter-django 1.9.9 Python 3.5.2 I have created a project from scratch with cookiecutter-django, using version 1.9.9, once that in zinnia docs it's recommended to use django < 2.0. I simply: git checkout 1.9.9 I followed the docs and the project is running ok. HOWEVER, after add zinnia I'm unable to migrate. Here my file config/settings/common.py THIRD_PARTY_APPS = ( 'crispy_forms', # Form layouts 'allauth', # registration 'allauth.account', # registration 'allauth.socialaccount', # registration 'mptt', 'tagging', 'zinnia', ) TEMPLATES = [ { # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND 'BACKEND': 'django.template.backends.django.DjangoTemplates', # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs 'DIRS': [ str(APPS_DIR.path('templates')), ], 'OPTIONS': { # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug 'debug': DEBUG, # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', # Your stuff: custom template context processors go here 'zinnia.context_processors.version', # Optional ], }, }, ] and confi/urls.py urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), # Django Admin, use {% url 'admin:index' %} url(settings.ADMIN_URL, include(admin.site.urls)), # User management url(r'^users/', include('rmining.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), # Your stuff: custom urls includes go here url(r'^weblog/', include('zinnia.urls')), url(r'^comments/', include('django_comments.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I run python manage.py migrate … -
Order queryset by alternating value
I have the following model: class Entry(models.Model): name = models.Charfield(max_length=255) client = models.Charfield(max_length=255) client is the name of the client as could have values like facebook, google, and so on. Is it possible to order the queryset so that the result is alternating the values of client? What I expect is something like this: Entry.objects.order_by('alternate client') --> | client | name | | google | robert | | facebook | linda | | google | kate | | facebook | jack | | google | nina | | facebook | pierre | I am using django2.x and postgres if that helps. -
Django Table-based Form - Update Processing
Apologies if this is a silly question but I have been hunting for a solution and I am stuck! In my views.py I pass a nested list with data from an API call. That data is then iterated over in the template and displayed in a table. I want the user to be able to modify certain fields (text fields) in the table and to post the updates which will then only update the certain fields that have been changed. Can someone suggest how I might do this? {% for interface in intData %} [...] <td><select name="vlan"> {{ interface.4 }} {% for dictionary in vlanData %} {% for vlan, description in dictionary.items %} {% if vlan == interface.4 %} <option value="{{ vlan }}" selected>{{ vlan }} - {{ description }} </option> {% else %} <option value="{{ vlan }}">{{ vlan }} - {{ description }} </option> {% endif %} {% endfor %} {% endfor %} </select></td> -
Django PDF is not work I try to render pdf from user download but I get this
enter image description here fsock = open(filename, 'r+',) response = HttpResponse(fsock, content_type="application/pdf") response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment;'+title+".pdf" -
ValueError when executed in separate thread
I have a function that processes a zip file of csvs in my Django application. I call the function after a button press when rendering the view by creating a new thread and sending the function as the run method. Here is the function I want to call: update_db.py def upload_files(csv_files): conn = sqlite3.connect('/path/to/db.db') c = conn.cursor() for csv_filename in csv_files.namelist(): if csv_filename.endswith('.csv'): csv_file = csv_files.open(csv_filename) # extract team name from csv_file string, remove whitespace table_name = csv_filename.rsplit('/',2)[1] table_name = re.sub('[^\w+]', '', table_name) try: df = pandas.read_csv(csv_file, error_bad_lines=False) df.to_sql(table_name, conn, if_exists='append', index=False) ##do some stuff except pandas.errors.EmptyDataError as ex: print(str(csv_file) + ' was empty; continuing...') continue; conn.commit() conn.close() The problem is that the function runs perfectly fine if I call it in views, but if I try passing it to a thread it doesn't. This is what I have in the calling environment: def upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] if str(myfile.name).endswith('.zip'): unzipped = zipfile.ZipFile(myfile) # If I uncomment this line, it doesn't throw an error #upload_files(unzipped) # When these lines execute, I get an error t = threading.Thread(target = upload_files, args = (unzipped, )) t.daemon = True t.start() return render(request, 'webapp/upload.html', { 'success': True }) … -
Django signals on Many-to-Many change
I have 3 models: class Product(TimeStampedModel): category = models.ForeignKey('Category', related_name='products', to_field='category_name') brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name') class Brand(models.Model): brand_name = models.CharField(max_length=50) categories = models.ManyToManyField('Category', related_name='categories') class Category(models.Model): category_name = models.CharField(max_length=128) I want to update Brand-Category M2M relationship after I change Product.category. I try to connect the signal m2m_changed, like it is described in the docs: @receiver(m2m_changed, sender=Brand.categories.through) def category_changed(sender, **kwargs): print("Signal connected!") Also I have registered a signal in the apps.py in project_folder: def ready(self): from my_app.signals import category_changed But the problem is - this code doesn't have any effect. I change the Product.category - and doesn't see any prints. How should I fix it to make it work? -
Success message in Django
In my django app I am taking form input.Once that form is validated I am displaying a success message with help of Django Message Framework. Current State I am able to display a success message in the template after submission of form when I redirect it to same url(The url of the form itself) My views.py if form.is_valid(): form_data = form.save() messages.success(request, 'Submited Successfully') return redirect('form-url') What I want Once the form is submitted I want to display a success message on the same page(form-url) and then I want to redirect to a new url list-of-submitted-forms. For that I did something like this to my views.py if form.is_valid(): form_data = form.save() messages.success(request, 'Submited Successfully') return redirect('list-of-submitted-forms') The problem I am facing I am redirecting to a new url.But without getting success message on the form-url page.Also again when I go to form-url page(By clicking a button which redirects to that url) the message of 'Submited Successfully' is shown -
Read only permission to a specific group in admin panel django
I want to give a permission that only user can see the existing entries in a model without edit/change right for a specific group. I tried to add custom permission to provide this but when I do not add the change permission to a user who belongs the group for a specific model, because I do not want to be changed an entry in the model from a person that belongs the group, at that time the model that I did not give change permission turns not to be clickable models therefore, existing objects can not be seen by clicking. How can I provide this feature that a person who belongs a group, only can see the entries of the model without change permission in admin panel. Thanks in advance. -
API architecture for Long time taking process
I don't know is this the right place to ask or not, please pardon me in advance. I have developed the API using DRF but facing the major performances issue. Here is what the scenario is: I am using DRF. Our API call is growing towards 5k per day. Each API call is taking 3 to 10 minutes of time while responding ( as It creates upto 300 pdf label unique format) I am using uwsgi( many worker) now with the Apache. We have implemented the caching but not able improve very much performances level. Primary query: Shall we use gunicorn instead of uwsgi? What about message/ job queue? Is this work. My current server RAM is only 32 GB. Shall I have to increase this if yes how much ( we personal don't want to go for vertical scaling) Please suggest the approach, first time I am handling such level of performance issue. I am very optimistic about message/ job queue and gunicorn. -
Django - How do I figure out what module is being logged by django?
I want to add a global custom formatter to all django modules so I can ingest a consistent log file with Elasticsearch. How do I figure out what django modules are logging what so I can change all their formatters? Here is my log config in settings.py. Using django 2.0. # NOTE: Copied from DEFAULT_LOGGING and added custom format # from django.utils.log import DEFAULT_LOGGING LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}, 'require_debug_true': {'()': 'django.utils.log.RequireDebugTrue'}}, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(module)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}}, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_true'], 'level': 'INFO'}, 'django.server': { 'class': 'logging.StreamHandler', 'formatter': 'django.server', 'level': 'INFO'}, 'mail_admins': { 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], 'level': 'ERROR'}}, 'loggers': { 'api': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False}, 'django': { 'handlers': ['django.server', 'mail_admins'], 'level': 'INFO'}, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False}}, } -
upgrade to django 1.11.12 error in models/manager.py contribute_to_class
I haven't touched a project in a long time and realized I upgraded my django to version 1.11.12. Trying to re-run project (runserver) and found several out of date packages (easy-thumbnails and psycopg2). Ran pip install upgrade on those. Now when I run, I get the following error and it seems like it is coming form my models? Not sure what it is telling me though or the proper course of action. Maybe there was another upgrade step I missed when I upgraded to django 1.11? (sorry been ages since I touched this code) Unhandled exception in thread started by <function wrapper at 0x104ab2500> Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/shane.thomas/programming/sw_nga_site/swsite/models.py", line 12, in <module> from filer.fields.image import FilerImageField File "/usr/local/lib/python2.7/site-packages/filer/fields/image.py", line 4, in <module> from ..models import Image File "/usr/local/lib/python2.7/site-packages/filer/models/__init__.py", line 3, in <module> from .clipboardmodels import * # … -
urlpattern keeps redirecting to a 404 [duplicate]
This question already has an answer here: Getting 404 not found using path() in Django 1 answer I am following the standard build your first blog web app in Django from here. I am trying to display a separate page by getting the blog's index value from the url using this code. from django.conf.urls import url, include from django.urls import path from django.views.generic import ListView, DetailView from .models import Post from .views import blogindex urlpatterns = [ path('', ListView.as_view( queryset = Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html" )), url(r'^(?P<pk>\d+$)', DetailView.as_view( model = Post, template_name = "blog/post.html")), ] everytime I go to a URL localhost/blog/2 it just gives me 404 not found. Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ ^$ ^blog ^blog ^(?P<pk>\d+)$ The current path, blog/2, didn't match any of these. main urls.py urlpatterns = [ path('admin/', admin.site.urls), url('^$', include('home.urls')), url('^blog', include('blog.urls')) ] -
how to pass dates in django
I am a Django newbie and am stuck on a small problem. I am trying to build a view where the user enters a from and to date and I need to pull records from my database according to these dates. I have worked out how to pull records without the user input dates(I tested using system dates, used deltas according to the documentation listed on the official website and i understood it) however am stuck now on how to get them as a user input. Here are a few relevant details of my project: models.py contains a lot of fields but here is the date field entry: date = models.DateField(auto_now_add=True) This entry defines the date the record is created. forms.py: I am using an unbound form(not linked to the model created in models.py) and am using the Jquery plugin listed here in a simple html page to show the from and to date. As a result the dates are passed as plain text in the form according to the documentation listed. The only way I know on how to get a user input is through a form(bound or unbound) which usually ends up as a POST request passing data … -
Populate django table column across multiple levels of foreign keys
I need to populate a column of my table with an property from a model separated from the table model by multiple levels of foreign keys. When I attempt to access the property, I just get a dash for every row instead of the value of the property. From tables.py: class AssignmentsTable(tables.Table): ... full_name = tables.Column(accessor='assignment.participant.full_name', verbose_name='First & Last Name (Participant)') ... class Meta: model = AssignmentDetail sequence = (..., "full_name", ...) From models.py: class AssignmentDetail(models.Model): assignment = models.ForeignKey(Assignment) ... class Assignment(models.Model): ... participant = models.ForeignKey(Account, blank=True, null=True) class Account(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) ... @property def full_name(self): return '%s %s' % (self.first_name, self.last_name) Is this something that can be done with django tables, and if so, how? -
Please explain why is this UnboundLocalError occurring?
This is my code - def Edit_View(request,pk): try: my_form = Profile.objects.get(pk=pk) except: raise Http404('Page Doesnt Found') form = ProfileForm(request.POST or None, instance=my_form) if request.method == 'POST': if form.is_valid(): form.save() return redirect('detail_view',pk=pk) else: return render (request, 'edit_view.html',{'form':form}) This is working fine, but when writing form = ProfileForm(request.POST or None, instance=my_form) after if request.method == 'POST': like def Edit_View(request,pk): try: my_form = Profile.objects.get(pk=pk) except: raise Http404('Page Doesnt Found') if request.method == 'POST': form = ProfileForm(request.POST or None, instance=my_form) if form.is_valid(): form.save() return redirect('detail_view',pk=pk) else: return render (request, 'edit_view.html',{'form':form}) it gives UnboundLocalError at /post/2/edit/ local variable 'form' referenced before assignment error, i want to know why such thing happening ! why earlier this didn't happen and later such error occurred and what is this UnboundLocalError? Please be guiding me. Thanks in Advance -
i would like to create an role based permission in django in which user can change the permissions dynamically from the front end
I would like to create a role-based permission in Django in which user can change the permissions dynamically from the front-end.Is there any readily available plugins are there.Can anyone suggest me the best method to resolve this -
Nginx 500 Error on POST to database, But It Actually Posts
I have a django app running on a droplet right now on DigitalOcean. It is running Nginx, gunicorn, MySQL. When I POST a form, it gets added to the database, but I get a 500 server error. I just go back to my homepage and test what I just did, and it's fine. Why am I getting the 500 error? I also get this error when I go to my admin page and try to view the actual item in my database. -
I am trying to get all updated value in a model and send an email to users about the changes in django
i have a model A which has a many to one relationship with another model B,i want to be able to get send an email notification to emails which will be queried from model B any time values change in model A how can i do that in django? class ModelA(models.Model): """ model to store informations about the ModelA """ name = models.CharField(max_length=15, blank=True, unique=True) creator = models.ForeignKey(AppUser, blank=True, null=True, on_delete=models.CASCADE) periodicity = models.CharField(max_length=10, blank=False, choices=PERIODICITY_CHOICES) begin_date = models.DateField(blank=False) end_date = models.DateField(blank=True, null=True) subscription_fee = models.DecimalField(max_digits=5, decimal_places=2, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) public = models.BooleanField(default=False) maximum_sub = models.PositiveIntegerField(blank=True, null=True, validators=[MinValueValidator(2)]) def save(self): emails = [] body = """ Hello <user first name or nothing>, This is to notify you that ModelA you're subscribed to has been updated. Here is what has changed: <field_name_1>: <current_value> <field_name_2>: <current_value> etc... Thank you """ if self.pk is not None: modelA_id = ModelA.objects.get(pk=self.pk) modelA_members = ModelB.objects.filter(pk=modelA_ID) emails = [i for i in modelA_members.email] send_mail('ModelA change Notification', body, "noreply@example.com", [emails]) super(ModelB, self).save() # def __unicode__(self): return u'{0}'.format(self.name) class ModelB(models.Model): """ defineModelB """ modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE, blank=False) user = models.ForeignKey(AppUser, on_delete=models.CASCADE, blank=False, ) cash_out_date = models.DateField(blank=True, null=True) -
Image not showing in Django - issue with file path?
I am generating images from matplotlib and saving them in a folder in my project directory named: media/risking/ I am not saving these images or the filename to the DB. In my html I am trying to call the file via: <img src="{{fig_name1}}" alt="oops"> Where fig_name1 is the variable with the name of the file (I have printed the name, and it is fine). My setting.py looks like: MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' However, when I load the page I get the URL: http://127.0.0.1:8000/risking/summary/2/2018-04-30_13_18_37.205595+00_00Lobo_Loco_InPlace.png where risking = app name, summary = view name and 2 = primarykey. I have also tried: <img src="/media/risking/{{fig_name1}}" alt="suck">, which gives me this file path: http://127.0.0.1:8000/media/risking/2018-04-30_13_18_37.205595+00_00Lobo_Loco_InPlace.png However, the image still doesn't show up. For reference, here is my app's urls.py: app_name = 'risking' urlpatterns = [ path('info/', ProspectInfoView.as_view(), name='info'), path('properties/<pk>/', ProspectPropertyView.as_view(), name='properties'), path('risk/<pk>/', ProspectRiskView.as_view(), name='risk'), path('info-edit/<pk>/', ProspectInfoEditView.as_view(), name='info-edit'), path('list/<username>/', ProspectsListView.as_view(), name='list'), path('summary/<pk>/', ProspectSummaryView.as_view(), name='summary'), path('delete/<pk>/', ProspectDelete.as_view(), name='delete'), path('notyours/', NotYourView.as_view(), name='notyours'), ] And the project URLs.py file: urlpatterns = [ path('admin/', admin.site.urls), path('', IndexView.as_view(), name='index'), path('about/', AboutView.as_view(), name='about'), path('courses/', CoursesView.as_view(), name='courses'), path('contact/', contact, name='contact'), path('contact/success/', successView.as_view(), name='success'), path('services/', ServicesView.as_view(),name='services'), path('accounts/', include('accounts.urls', namespace='accounts')), path('accounts/', include('django.contrib.auth.urls')), path('risking/', include('risking.urls')), path('sales/', salescontact, name='sales'), path('sales/success/', SalesView.as_view(), … -
"... matching query does not exist." error, but object clearly does exist
I have a lesson model: class Lesson(models.Model): list_name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.list_name A sound model: class Sound(models.Model): sound_hash = models.CharField(max_length=40, primary_key=True, editable=False) lessons = models.ManyToManyField(Lesson, verbose_name="associated lessons", related_name="words") And a test_pair model: class TestPair(models.Model): master_sound = models.ForeignKey(Sound, related_name="used_as_master") user_sound = models.ForeignKey(Sound, related_name="used_as_user") My form looks something like this: class SoundTestPairForm(ModelForm): user_sounds = forms.ModelMultipleChoiceField(Sound.objects.all()) class Meta: model = TestPair fields = ['master_sound'] def __init__(self, *args, **kwargs): super(SoundTestPairForm, self).__init__(*args, **kwargs) self.fields['master_sound'] = forms.CharField() self.fields['master_sound'].widget.attrs['readonly'] = 'readonly' def clean(self): cleaned_data = super(SoundTestPairForm, self).clean() if 'user_sounds' not in cleaned_data.keys(): raise forms.ValidationError('You must select at least one sound to be compared') cleaned_data['master_sound'] = Sound.objects.get(pk=self.fields['master_sound']) return cleaned_data This is throwing a DoesNotExist error. The traceback points to this line: cleaned_data['master_sound'] = Sound.objects.get(pk=self.fields['master_sound']) The local vars are as follows: self <SoundTestPairForm bound=True, valid=True, fields=(master_sound;associated_test;associated_lesson;user_sounds)> cleaned_data {'associated_lesson': u'pooooooooooooooooooooooop', 'associated_test': u'cats a', 'master_sound': u'ad27ec5e0d048ddbb17d0cef0c7b9d4406a2c33', 'user_sounds': [<Sound: Pants>]} But when I go to python manage.py shell, and import my model: Sound.objects.get(pk=u'ad27ec5e0d048ddbb17d0cef0c7b9d4406a2c33') <Sound: oombah> It hits the appropriate object. This is something I've been dealing with for a long time, and it's super frustrating. I try to switch my logic around and ultimately it ends up throwing a DoesNotExist error, regardless of what I try. Does anyone have … -
Different SESSION_COOKIE_AGE for Different Domain or APP
I have 2 app in one django project. I allow two Domain(e.g. aaa.com & bbb.com) to access my django project. (Actually, aaa.com to app A, bbb.com to app B). (There is some reasons that I want to create 2 app in 1 project.) And I want to set different SESSION_COOKIE_AGE for these 2 domains. So I'm thinking about these solutions... (Solution A) aaa.com - SESSION_COOKIE_AGE = 10 (domain & age are just an example) bbb.com - SESSION_COOKIE_AGE = 20 or (Solution B) App A - SESSION_COOKIE_AGE = 10 App B - SESSION_COOKIE_AGE = 20 Is django support it? If NOT, Since I use this code to create a cookies in views.py for App A, request.session._get_or_create_session_key() request.session.modified = True Can I specific cookies age in views.py which overwrite the setting in settings.py? I'm using django 2.0.2 Thanks! -
Why django in docker does not works?
Dockerfile: FROM python:3.6.5-jessie MAINTAINER example-user RUN apt-get update \ && apt-get install -y vim RUN mkdir require COPY ./requirements.txt require/requirements.txt RUN pip install -r require/requirements.txt EXPOSE 8000 requirements.txt: Django==2.0.2 As above, I made a image that has name sample-image Next, I runned a container from sample-image like, docker run -ti --name sample_django -p 8001:8000 sample-image /bin/bash And on container bash, I commanded like, root@4a947abf5ce5:/# mkdir startdir && cd startdir root@4a947abf5ce5:/startdir# django-admin startproject sample . root@4a947abf5ce5:/startdir# python manage.py runserver it returned it: Performing system checks... System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 01, 2018 - 12:44:45 Django version 2.0.2, using settings 'sample.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Because I set -p 8001:8000 on running container, I found this page in browser( 127.0.0.1:8080), but it did returned it: QUESTION: How can I set port on container correctly? Or is there anything i missed? -
Django: Why is console email backend not sending emails?
I'm trying to make an app to reset user password via email. I'm using the Django by Example book chapter 3, and also took guidance from this site: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html Settings.py contains the following line: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' together with the required email settings. I get to the password_reset view, enter dummy mail, click send, which finally brings me to the password_reset_done view. Below is the console output: C:\PythonProjects\by-example-bookmarks>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). May 01, 2018 - 21:13:39 Django version 2.0.4, using settings 'bookmarks.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [01/May/2018 21:13:51] "GET /account/login/ HTTP/1.1" 200 1090 [01/May/2018 21:13:57] "GET /account/password_reset/ HTTP/1.1" 200 830 [01/May/2018 21:14:04] "POST /account/password_reset/ HTTP/1.1" 302 0 [01/May/2018 21:14:05] "GET /account/password_reset/done/ HTTP/1.1" 200 602 After the "POST" output I expect to see a dump of the email in response to .console.EmailBackend setting, but got nothing, ever. What could be the cause of the failure to simulate sending email? Environment: Windows 7, on CMD console, under pipenv shell