Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending Email Error in Django in Production
Hi there i have contact form where user put the email address and an email will be sent locally. But when i use this code in production it will give the exception in Django like this. Exception Type: OSError at /contact-us/ Exception Value: [Errno 101] Network is unreachable In settings.py i have use this code for sending emails DEBUG = True ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_email_address' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True code of forms.py class ContactForm(forms.ModelForm): class Meta: model = Consulting #fields = ['email'] fields = '__all__' widgets = { 'email': forms.TextInput(attrs={'class': 'form-control form-control-lg'}), 'name': forms.TextInput(attrs={'class': 'form-control form-control-lg'}), 'content': forms.TextInput(attrs={'class': 'form-control form-control-lg textarea-autosize'}), } def clean_email(self): email = self.cleaned_data.get('email') return email code written in views.py def contact_page(request): contactform = ContactForm(request.POST or None) if contactform.is_valid(): instance = contactform.save(commit=False) if Consulting.objects.filter(email=instance.email).exists(): messages.warning(request, 'Your Email Is Already Exists', "alert alert-warning alert-dismissible") print("This Email Is Already Registered") else: instance.save() messages.success(request, 'Thanks For The contact.', "alert alert-success alert-dismissible") subject = "Thankyou for joining our newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] signup_message = """ welcome to devdap contact """ send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=signup_message, fail_silently=False) context = { 'form': contactform } return render(request, "pages/contact_us.html", context) -
DRF - SerializerMethodField for NestedSerializer
I've a serializer as follow:- class ABCSerializer(serializer.ModelSerializer): class XYZSerializer(serializers.Serializer): a = serializers.CharField(default='abcd') #Try1:- Setting default values. b = serializers.IntegerField(default=1) c = serializers.ListField(default=['']) def get_attribute(self, instance): # Try 2. This works only when many != True. return [ { 'a': 'abcd', 'b': 1, 'c': [] }] field1 = XYZSerializer(many=True) def get_field1(self, instance): # Try 3 return [ { 'a': 'abcd', 'b': 1, 'c': [] } ] class Meta: fields = ('uuid', 'field1') extra_kwargs = { 'uuid': {'source': 'user_id'} } I want to return the default value of XYZSerializer. How can I do it? I've tried over-riding get_attribute of XYZSerializer, but that only works when many != True. I've also tried get_field1, but to no avail. How can I pass the default value of XYZSerializer? -
Relogin with password only in django
I just created authentication app based on django its working file with login and logout features. But my problems is that, I want to add features so that use, Just logout use can easily login with the help of password only. -
django mongo db not in query error while check if name exist in a list
My query: SeekerRegister.objects.filter(seeker_name__nin=['soubhagya']).values() Errors: >>> s = SeekerRegister.objects.filter(seeker_name__nin=['soubhagya']).values() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 844, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 862, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1263, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q split_subq=split_subq, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1225, in build_filter condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1090, in build_lookup lhs = self.try_transform(lhs, lookup_name) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1126, in try_transform (name, lhs.output_field.__class__.__name__)) django.core.exceptions.FieldError: Unsupported lookup 'nin' for CharField or join on the field not permitted. I am using mongodb with djongo engine. when i am using above query i amgetting these errors. I wants filter if name is not in the list -
How to perform STD Query in Django?
How should i perform STD operation when i'm working with Django? SELECT STD(total_cost) FROM purchase; tnx -
Disable checkbox by clicking another checkbox (HTML/DJANGO)
I have 2 checkboxes on my site. One of them gives me opportunity (or not) to click(change state) second one. So if first checkbox is checked I can change state of second but if first checkbox is unchecked then I just can't (checkbox is disabled). So I wrote simple if/else statement in html (with django python) and it looks like : {% if first.value %} {% if second.value %} <input id="myCheck" type="checkbox" checked="checked"> {% else %} <input id="myCheck" type="checkbox"> {% endif %} {% else %} {% if second.turnOnOff %} <input id="myCheck" type="checkbox" disabled="disabled" checked="checked"> {% else %} <input id="myCheck" type="checkbox" disabled="disabled"> {% endif %} {% endif %} Maybe some of you are confused why I have if statement for second checkbox, I just check his last value from database to know that it was True or False. I checked that code and it doesn't work good. I mean If I refresh page after each change state of first checkbox it works but is should work all the time without refreshing page all the time. What I'm doing wrong ? -
docker-compose same config for dev and production but enable code sharing between host and container only in development
As the most important benefit of using docker is to keep dev and prod env to be the same so let's rule out the option of using two different docker-compose.yml Let's say we have a Django application, and we use gunicorn to serve for production and we have a dedicated apache2 as a reverse proxy(this apache2 is out of docker by design). So this application(docker-compose) has only two parts, web(Django) and db(mysql). There's nothing wrong with the db part. For the Django part, the dev routine without docker would be using venv and python3 manage.py runserver or whatever shortcut that an IDE provides. We can happily change our code, the dev server is smart to pick up and change and reflect in no time. Things get tricky when docker comes in since all source code should be packed into the image, this gives our dev a big overhead of recreating the image&container again and again. One might have the following solutions(which I found not elegant): In docker-compose.yml use volume to mount source code folder into the container, so that all changes in the host source code folder will automatically reflect in the container, then gunicorn will pick up the change … -
NameError - 'form' is not defined
Error - name 'form' is not defined i am getting NameError. I am not not using form_class so please review my code. How can i add a form and list all jobs in same view. class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' status = None start_date = None end_date = None def post(self, request, *args, **kwargs): if form.is_valid(): self.status = form.cleaned_data['status'] self.start_date = form.cleaned_data['start_date'] self.end_date = form.cleaned_data['end_date'] return HttpResponseRedirect('/useradmin/job/') def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) company_name = self.request.user.userprofile.user_company context['jobs'] = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) context['form'] = JobSearchForm() if self.start_date: print(self.start_date) return context -
type object 'Event' has no attribute '_default_manager'
I am getting the following error: AttributeError at /admin2/event/edit/1/ type object 'Event' has no attribute '_default_manager' from the newly added code: (views.py) @method_decorator(staff_member_required, name='dispatch') class EditEvent(LoginRequiredMixin, UpdateView): template_name = 'admin2/events/edit-event.html' form_class = AddEventForm model = Event slug_url_kwarg = "events_id" slug_field = 'id' success_url = '/admin2/event/' (urls.py) url(r'^admin2/event/edit/(?:(?P<events_id>.+)/)?$', login_required(EditEvent.as_view()), name='edit-event-view'), (models.py) class Event(models.Model): title = models.CharField(help_text='Name of the event', max_length=250, null=False, blank=False) location = models.CharField(help_text='Location of the event', max_length=250, null=False, blank=False) date = models.DateTimeField(auto_now=False) (forms.py) class AddEventForm(forms.ModelForm): class Meta: model = Event fields = ('title', 'location', 'date') Full traceback here: http://dpaste.com/002BGGT I am using Django 1.11 (outdated but I am unable to update) -
Django form as GET - Retrieving data from existing tables
how to write the views.py by GET request if I got some value from user from django import forms accountId = forms.DecimalField(label='account number', max_length=100, widget=forms.TextInput(attrs={ 'class': 'form-control', })) The accountId is a PK of table "account". I have another table called "person" in the account models I have person_Id - Which is a foreign key I need to make a get request - first, make sure that the accountID is valid and existing in the table "account" seconde, retrieve the data from the tables and display them to the user on the screen - localhost:8000/polls/.... means, I got the "accountId" and verified that it is valid, and now look for the row in the SQL table that refers to this accountId number and retrieve the data from other fields(accountNo, openDate, typeA=(some enum)), In addition, access the "person" table and also retrieve the data(by the accountId provided from this table). all the tutorials were about POST How do I perform this action what I need to write in the views.py? (and what I need to write in the xx.html to view the user's data after he has entered the AccountIdshould) if somebody can write it, it will help -
Invalid block tag: 'render_field', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I'm getting this error message from django, and don't understand why, especially because I use this exact code to render forms in other templates in my project. This is the full template: <div class="row"> <div class="col-8"> <form action="{% url 'great_songs:new_playlist' %}" method="POST"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {% render_field field class+="form-control" %} </div> {% endfor %} <button name=submit>submit playlist</button> </form> </div> </div> -
TypeError: 'NoneType' object is not subscriptable in Django unittests for message
Am trying to do a unit test for a view that returns a message when some input is duplicated in the database.it gives me the error TypeError: 'NoneType' object is not subscriptable Here is the view @login_required def worker_create(request): worker_create_form = WorkerCreateForm(request.POST) if request.method == 'POST': if worker_create_form.is_valid(): form = worker_create_form.save(commit=False) phone = form.phone check_phone = Worker.objects.filter(phone=phone) if check_phone.count() != 0: messages.error(request, 'رقم الهاتف مستخدم من قبل') else: form.save() return redirect('worker_list') else: worker_create_form = WorkerCreateForm(request.POST) context = { 'worker_create_form': worker_create_form, } return render(request, 'erp_system/worker/create.html', context) and here are the tests I've created for it class WorkerCreateTest(TestCase): def setUp(self): User.objects.create_user(username='test_user', email='test@gmail.com', password='test_password') branch = Branch.objects.create(name='test branch') Worker.objects.create(name="ay btngan ", phone='01207199086', branch=branch) def test_get_request_unauthenticated(self): response = self.client.get(reverse('worker_create')) url = reverse('worker_create') self.assertRedirects(response, '/login/?next=' + url) def test_get_request_authenticated(self): self.client.login(username='test_user', password='test_password') response = self.client.get(reverse('worker_create')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed('erp_system/worker/create.html') def test_post_request_empty_data(self): self.client.login(username='test_user', password='test_password') response = self.client.post(reverse('worker_create'), {}) self.assertFormError(response, 'worker_create_form', 'name', 'This field is required.') self.assertFormError(response, 'worker_create_form', 'phone', 'This field is required.') self.assertFormError(response, 'worker_create_form', 'branch', 'This field is required.') def test_post_request_invalid_data(self): self.client.login(username='test_user', password='test_password') branch = Branch.objects.create(name='test again ') name = 'just a name' for i in range(300): name += 'h' response = self.client.post(reverse('worker_create'), {'name': name, 'phone': '01207199086', 'branch': branch.id}) self.assertEqual(response.status_code, 200) def test_post_request_duplicated_phone(self): self.client.login(username='test_user', password='test_password') branch = Branch.objects.create(name='test … -
Model form with multiple polymorphic model fields
We have a table with related columns: class Table(models.Model): name = models.CharField() class Column(PolymorphicModel): table = models.ForeignKey(Table) name = models.CharField() value = models.CharField() active = models.BooleanField() class Column1(Column): class Meta: proxy = True class Column2(Column): class Meta: proxy = True class Column3(Column): class Meta: proxy = True All our tables with have these 3 columns, which as you can see have the same attributes no matter the subclass. I need a form to create/update a table. But we don't want to have the typical ModelMultipleChoiceField since we know we always want those 3. What we want is to display each column as multi fields that can be filled in separately. Our table form would look like this: name Column1 name value active Column2 name value active Column3 name value active I have been trying to figure out a clean way of doing this but have had no success so far. Perhaps nested forms? Would that work? -
How to display the user Avatar on all templates (django) i use base.html
Hello everyone I want to finish my project using django The problem in how to make avatar image appear on all project templates If an avatar is displayed in one template, for exemple: www.site.com/index the other does not work www.site.com/page2/page3...... help me please cz i get tired for this here is my model.py class author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) profile_picture = models.ImageField(blank = True, upload_to = 'Avatar') def __str__(self): return self.name class articles(models.Model): article_author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) avatar = models.ForeignKey(author, on_delete = models.CASCADE) -
Displaying an Image in ModelForm
I have the following model: class Portfolio(models.Model): id = models.AutoField(primary_key=True) member = models.ForeignKey(Member, on_delete=models.CASCADE) image = models.ImageField(upload_to='portraits/', default='/images/some_image.png') For that I made the ModelForm: class PortfolioForm(forms.ModelForm): class Meta: model = Portfolio exclude = ['id'] I need many of those in one template so I am creating them in the Following way in my view def portfolio_form(request, pk): ... forms = [PortfolioForm(request.FILES, instance=x, prefix=str(x.id)) for x in p] finally in the html I have this: <form enctype="multipart/form-data" action="{% url 'elec:portfolio_form' pk=id %}" method="POST">{% csrf_token %} ... {% for field in form %} {% if field.image %} <p>dfadsfa</p> <td><img src="{{field.image.url}}"/></td> {% else %} <td align="center" valign="middle">{{field}}</td> {% endif %} {% endfor %} <input type="submit" class="btn btn-default" value="Save and Refresh" /> </form> Now what I expect to see is the image that I am saving into that Model. The if statement is coming back as false but why?. What am I doing wrong? Everywhere I looked it should work like this. Also I have added the request.FILES in PortfolioForm with that the instance is not called how can I fix that? -
ProgrammingError at /admin/Asset/movie/
column Asset_movie._id does not exist LINE 1: SELECT "Asset_movie"."_id", "Asset_movie"."name", "Asset_mov... ^ HINT: Perhaps you meant to reference the column "Asset_movie.id". When ever i use the _id field in my movie module i am getting this error, suppose if i comment the _id field, then at the time my code is executing successfully, but i need the _id field ,help me guys class movie(models.Model): _id = models.AutoField( primary_key=True ) name = models.CharField(max_length=50, blank=False) Partner = models.CharField(max_length=10, blank=True) -
Django: How to refer to a variable if a templatetag returns multiple values
How can I access to the variable if a customtemplate tag returns multiple variables? templatetags.py def custom_tag(context): # do something return A, B and html {% load templatetags %} {% custom_tag as A %} # A used as A {% custom_tag as B %} # B used as B How can I refer to each variable? -
How to interact with integer field in Django SQLite Database?
How to update an integer field in a SQLite DB managed with Django models ? Extract of my Django models : class Event(models.Model): title = models.CharField(max_length=100) [...] attendees = models.ManyToManyField(Attendee) max_attendees = 8 #max_attendees = models.PositiveSmallIntegerField(null=True, blank=True) Testing with python3 manage.py shell >>> from main.models import * >>> Event.objects.first() <Event: 8 places left> >>> Event.objects.first().max_attendees 8 >>> Event.objects.first().max_attendees = 2 >>> Event.objects.first().save() >>> Event.objects.first().max_attendees 8 As you can see, the value is not updated even with a save() on the "object". I also tried : >>> Event.objects.first().max_attendees = models.PositiveSmallIntegerField(2) But it's not updating the value of max_attendees neither. How can I modify the value of this max_attendees field ? -
Django: Get Data from python method with jquery/js
I've got a method where I loop through a .txt file and randomly create myself a code from different words inside that file. Now I'd like to somehow get that data/the code and call it with a js function. More specifically, when clicking on a button, it should always call that python method and give me the returned value, which I then can use to show it on my page. in my validators.py I've got my method finished def generate_code(request): ... return JsonResponse(code) # where code is just a one word string in my urls.py: url(r'form/generate/code/?$', views.generate_code), But how do I call this function now and get the returned value to use it in my JS? I know I've got to do something like $.ajax({ type: "GET", url: '/api/form/generate/code/' data: ???, success: function(data) { console.warn(data) } }); But what would my data be? Shouldn't that be my returned JsonResponse from the python method? -
Changing a tuple list so that the first entry is the same as the second entry
I have an example country tuple list: [("GB", "Great Britain"), ("IR", "Ireland"), ("IC", "Iceland")] For the sake of my task, I do not need the country code, only the human readable value. However Django accepts tuples in it's choiceField as such. I wrote a simple method to create a new tuple that will just contain the friendly name as both values in the tuples, e.g : [("Great Britain", "Great Britain"), ("Ireland", "Ireland"), ("Iceland", "Iceland")] But i'm looking to see if there is an easier way to do this in Django or python in comparison to my implementation. Anyone have any ideas? Method def change_country_tuples(country_list): new_country_list = [] for country in country_list: new_country_list.append(tuple((country[1], country[1]))) return new_country_list Django choice field call country = fields.ChoiceField( label='Choose country', choices=[('', 'Select a country')] + change_country_tuples(country_choices), ) -
Select a valid choice. That choice is not one of the available choices
In my app, i have a dropdown (department) that's depending on the previously selected value from a dropdown(faculty filed). I am using ajax to get the new value which works fine. However, when i try saving the form, i get Select a valid choice. That choice is not one of the available choices. Here is my model from django.db import models from system.models import FacultyData, DepartmentData, SessionData, SemesterData, SettingsData # Create your models here. class SchoolFees(models.Model): fid = models.ForeignKey(FacultyData, on_delete= models.SET_NULL, null=True) did = models.ForeignKey(DepartmentData, on_delete= models.SET_NULL, null=True) sid = models.ForeignKey(SessionData, on_delete= models.SET_NULL, null=True) amount = models.CharField(max_length=30) def __str__(self): return self.amount and my form.py from django import forms from . import models from system.models import FacultyData, DepartmentData, SessionData from .models import SchoolFees class FeesCreationForm(forms.ModelForm): fid = forms.ModelChoiceField(queryset=FacultyData.objects.all(), empty_label="--Select Faculty--", widget=forms.Select(attrs={'class': 'form-control'})) did = forms.ModelChoiceField(queryset=DepartmentData.objects.all(), empty_label="--Select Faculty First--", widget=forms.Select(attrs={'class': 'form-control'})) sid = forms.ModelChoiceField(queryset=SessionData.objects.all(), empty_label="--Select Session--", widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = models.SchoolFees fields = ['sid', 'fid', 'did', 'amount'] widgets = { 'amount': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Amount'}) } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['did'].queryset = DepartmentData.objects.none() in my view.py, i have a method for getting department based on the faculty chosen. and also for saving the new fee def create_fee(request): … -
get() missing 1 required positional argument: 'key'
Im getting error because i want Post form from templateclass. i am able to display form but not able to get post values JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) company_name = self.request.user.userprofile.user_company context['jobs'] = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) context['form'] = JobSearchForm() # form = self.request.POST.get() # print(form) return context def post(self, request, *args, **kwargs): form = self.request.POST.get() print(form) return HttpResponseRedirect('/jobs/') -
Django nested templates
In trying to keep with DRY, I'm setting up my Django project HTML files now. I have successfully extracted most repeated information to my base.html page. On most (but not all) of my pages, my content is displayed within a general 'panel' which is basically just a container set-up with styling, but it's got a few div-tags to it so it looks a bit ugly and I'm having to type out the exact same code out several times on each page. My idea was to extract this to a 'panel.html' then call it whenever I need it, for example some pages might just have one 'panel' whereas my dashboard (it's an administrative site) will have maybe 15+. So it seemed a better idea and cleaner to not have to type out all this code each time I need to set up a 'panel'. My ideal page would look something like.. {% extends 'base.html' %} {% block content %} {% extends 'panel.html' %} {% block panel_content %} Panel content... {% endblock panel_content %} {% extends 'panel.html' %} {% block panel_content %} Second panel content {% endblock panel_content %} {% endblock content %} I know I can't use extends multiple times but … -
How to apply django initial migration?
showmigrations shows that there is 31 available migrations: # python3 manage.py showmigrations admin [X] 0001_initial [X] 0002_auto_20190114_1409 [X] 0003_auto_20190114_1410 auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_auto_20190114_1409 authtoken [X] 0001_initial [X] 0002_auto_20160226_1747 [X] 0003_auto_20190114_1409 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name [X] 0003_auto_20190114_1409 exchange_delivery [X] 0001_initial [X] 0002_enlarge_phone_field [X] 0003_unique_external_id [X] 0004_add_warehouse [X] 0005_add_delivery_point_type [X] 0006_update_delivery_type_operating_mode [X] 0007_add_delivery_point_region_model [X] 0008_update_warehouse_exchange [X] 0009_add_verbose_name_for_warehouse_and_add_delivery_point_banned_group [X] 0010_add_active_flag_to_warehouse [X] 0011_auto_20190114_1409 sessions [X] 0001_initial [X] 0002_auto_20190114_1410 volt [X] 0001_initial [X] 0002_auto_20190114_1410 How to apply all this migrations ? migrate shows that No migrations to apply # python3 manage.py migrate Operations to perform: Synchronize unmigrated apps: corsheaders, export, opinion, volt.integration1c.delivery, custom_logger, event_listener, legacy, region, order, catalog, promo_table, messages, staticfiles, api, best_product, shop, general, market_cpa, rest_framework, delivery, exchange, talk Apply all migrations: auth, authtoken, sessions, exchange_delivery, admin, volt, contenttypes Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... /usr/lib/python3.6/site-packages/django/core/management/commands/loaddata.py:239: RemovedInDjango19Warning: initial_data fixtures are deprecated. Use data migrations instead. RemovedInDjango19Warning Installed 0 object(s) (of 6) from 1 fixture(s) Running migrations: No migrations to apply. Project is under Django 1.8.14 -
how to call javascript function using widgets in django form
Hi i want to call js function when a field in form is clicked or typed in I have used this code: class ProviderSugForm(forms.ModelForm): class Meta: model = ProviderSug fields = ['due_date', 'price', 'description', 'discount'] widgets = { 'due_date': forms.DateInput(attrs={'class': 'datepicker'}), 'price': forms.NumberInput(attrs={'onclick': 'numberWithCommas()'}), } but the js function is gray in my html template and not working