Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 or more levels of Dropdown Menu Filter
**Hi, I am trying to make a webpage where I can register a pre-defined(in Admin area) Product and associate it to Category and Subcategory, using a dropdown menu, that in each iteration filters the subsequent and show only the items associated with the previous. Example: I want to register a Product called "Tablet" associated with Subcategory "Mobile Devices" and this subcategory is associated with Category "Electronic". So, in order to do this, the webpage will show Category to be selected, then after selecting it as electronic, will only show as subcategory "Mobile Devices" and any other under the same category. After selecting the Subcategory, it will filter the next menu Product, to show only Product under subcategory "Mobile Devices" such as Tablet, Cellphone etc. Here is my model.py** class Category(models.Model): company_name = models.CharField(max_length=100) def __str__(self): return self.company_name class Subcategory(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=100) def category_name(self): return self.category.company_name def __str__(self): return self.name class Product(models.Model): subcategory = models.ForeignKey(Subcategory) description = models.CharField(max_length=100) def subcategory_name(self): return self.subcategory.name def category(self): return self.subcategory.category.company_name def __str__(self): return self.description **Here is my view.py** def regsubcategory(request): if request.method == 'POST': subcategory_form = RegSubcategoryForm(data=request.POST) if subcategory_form.is_valid(): cdata = subcategory_form.cleaned_data.get ddata = subcategory_form.cleaned_data.get subcategory_selected = Subcategory.objects.filter(name=cdata('subcategory_select')) product_selected = Product.objects.filter(name=ddata('product_select')) … -
The definition of `context` contradicts to its original meaning
I am confused with definition of 'context' in Django for months. In Django documentation: Context:A dict to be used as the template’s context for rendering. Oxford definition: The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning. the data from a view's dict is filled to blank of template which contradict to context's original meaning. Take an instance to explain my question : In views.py context = {key:value} render(request, template_name, context) in template <p> The parts of a discourse that surround a word {{ key }} and can throw lights on its meaning.<\p> Literallly, the 'context' is the parts outside the curly bracket not the parts inside to be filled in. Now,in django,context is the part within bracket. Or, that's it, just accept it for granted. How to perceive the definition of context in Django? -
How to toggle readonly_fields in Django admin?
Need to add button to django admin page, if you want to edit Model, you push Edit then edit what you need, and save it. When you open it after saving, it must be uneditable again. So, how to do that? I have simple admin.py code: from django.contrib import admin from .models import Order class OrderAdmin(admin.ModelAdmin): list_display = ['__str__', 'email', 'project_type', 'price'] list_filter = ['email', 'first_name', 'project_type', 'price'] readonly_fields = ('first_name', 'last_name', 'email', 'phone', 'project_type', 'price') fields = ('first_name', 'last_name', 'email', 'phone', 'project_type', 'services', 'price', 'slug') def has_add_permission(self, request): return False admin.site.register(Order, OrderAdmin) -
Correctly handling Django migrations conflicts
I'm currently working on a dev branch and I will need to merge it to master one day. I have up to 20 migrations files on my dev branch and about the same number on master at the moment. I needed to make migrations on both branches which will result in migrations having the same prefix, (ex 0003_auto) Now, there are other threads out there about this topic but I never found a relevant one. Basically, I want to know how to correctly handle migrations conflicts but for a general case. In other words, not considering my particular case, if you have migrations files generated by makemigrations with the same prefix, what is the best/secure way of handling this. Here are two ways I have figured myself (maybe entirely wrong): Deleting all migrations files, merge the code and then running a fresh makemigrations and migrate which will result in only one migration file. Using the flag --merge flag: makemigrations –merge I know there are multiple other ways (see this). Now, knowing all this I'd like to know what is the best way of handling this. In general, what should I use that will correctly merge conflicts and get me a … -
Unable to access attributes of the JSON data - django
I have this view def view_involved_people(request): schedule = request.POST['schedule'] query = Schedule.objects.get(pk=schedule).involved_people.all() serialized = serializers.serialize('json', query) data = {'data': serialized} return JsonResponse(data) I have this script $.ajax({ url: "/schedule/ajax/view_people", data: { 'schedule': JSON.parse(id) }, dataType: "json", success: function(data) { console.log(data); }, error: function(data) { console.log(data.responseText); }, type: "post" }); When I do console.log(data), it return this: How can I access the values of the returned data. Do I have an error with my JSON? -
Modify default form for a model in the admin site to accept Postgres arrays
I'm new in Django and I've followed the tutorial. I know that when I do: from .models import Question admin.site.register(Question) I make the administrator capable to create and edit questions from a form that is created from the definition of the model. The problem that I have is that this is a model I made for my project: class Catalog(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=500) creation_date = models.DateTimeField('creation date') creators = ArrayField(models.CharField(max_length=35, blank=True), size=10) subjects = ArrayField(models.CharField(max_length=35, blank=True), size=5) instrument = models.CharField(max_length=50) facility = models.CharField(max_length=50) ... And creators and subjects seems to act like normal CharFields. So my questions are: How can I edit the form that is displayed by default? How can I treat creators and subjects like arrays in the form? Thank you. -
possible to return list of dict instead of a list when using for in? django
I have a code which returns a list, which looks something like this [user.name for user in Model.field.filter()] I know this would return me a list of user name but I am wondering if it would be possible to return list of dict? such as [ {'name': 'name1', 'email': 'email1', {'name': 'name2', 'email': 'email2', ] -
Django, JWT, Angular 4, how to redirect after success login
class CreateUserView(CreateAPIView): serializer_class = UserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) user = self.model.get(username=serializer.data['username']) payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) return Response( token, status=status.HTTP_201_CREATED, headers=headers ) else: return Response( status=status.HTTP_400_BAD_REQUEST ) how to add that to DB? class LoginUserView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user: payload = jwt_payload_handler(user) token = { 'token': jwt.encode(payload, SECRET_KEY), 'status': 'success' } return Response(token) else: return Response( {'error': 'Invalid credentials', 'status': 'failed'}, ) And how redirect after success login to url in angular -
Select2 overdrive option value
Hi i have select2 script witch Django i need save in DB text not value. I think best way to do this is use jquery and detect change event and replace val to option text. Please help me make jquery script. my html: <div class="col-lg-4"> <select name="depositvalues_set-0-name" data-placeholder="Wybierz oponę" data-width="100%" class="form-control m-select2 django-select2 django-select2-heavy select2-hidden-accessible" maxlength="100" id="id_depositvalues_set-0-name" data-allow-clear="true" data-minimum-input-length="0" data-field_id="MTQwMTE3Nzg3OTU1OTQ0:1eAPuS:iiIjCRFFWJ-hM1k153lOvcNLLDs" data-ajax--url="/select2/fields/auto.json" data-ajax--cache="true" data-ajax--type="GET" tabindex="-1" aria-hidden="true"> <option value="" selected=""></option> <option value="1">Opona Kumho 195/75R16 C KC-11 Dostawcza Zimowa</option> </select> Select name is dynamic -
What is the 'instance' created from class 'ListView'?
I follow a tutorial and define class ListView: class RestaurantListView(LoginRequiredMixin, ListView): def get_queryset(self): return RestaurantLocation.objects.filter(owner=self.request.user) I attempt to figure out what's the instance created from the class To accomplish it, I add print for debugging. class RestaurantListView(LoginRequiredMixin, ListView): print(self) # intend to print the objects created def get_queryset(self): return RestaurantLocation.objects.filter(owner=self.request.user) Error reports then NameError: name 'self' is not defined -
Django Model choices based off another model
Sorry if this is confusing, I'm still a bit green with Django. So basically I have two models and I want a selection from one to have all the choices from another model. So basically: class Show(models.Model): venue = models.CharField(max_length=100, choices = VENUE NAME) class Venues(models.Model): Name = models.CharField(max_length=100) Essentially I want the venue to have a list of the venue names that were input into that model. Is this possible? -
The map in head to traverse Django files
There are multiple files in Django: urls.py views.py models.py templates and forms.py to create data. The diagram of it enables you to understand the functions and principles. take a popular vertical map for instance. MTV diagram It's frustrating if you traverse the fils vertically in mind when shift from file to file in editor. What's is a good structure to picture and see them in mind simultaneously when working. -
Import Django Models Into PyCharm's Python Console
I am following the Django tutorial and using PyCharm. I am trying to import Question and Choice from models.py INTO the PyCharm "Python Console". I have __init__.py files located in top-level mysite, lower-level mysite, and in polls directory. I am using a virtual environment and it is activated in the PyCharm Python Console. C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pydev\pydevconsole.py" 51164 51165 PyDev console: starting. import sys; print('Python %s on %s' % (sys.version, sys.platform)) sys.path.extend(['C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial', 'C:/Users/Jarad/PycharmProjects/OfficialDjangoTutorial']) Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 >>> import sys >>> import os >>> import django >>> os.getcwd() 'C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial' sys.path.append('C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial\mysite') >>> os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.mysite.settings' >>> django.setup() >>> from mysite.polls.models import Question, Choice Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\mysite\polls\models.py", line 8, in <module> class Question(models.Model): File "C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\venv\lib\site-packages\django\db\models\base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class mysite.polls.models.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. apps.py from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' Restate my goal: import the Question and Choice models in PyCharm's "Python Console" because the code hints and inspection of … -
Forms and views in Django: How to clean data, especially data re. mptt models, in formtools.wizard?
I’m trying to write a form using python2.7, django1.11.5, crispy_forms, formtools’ wizardview and djnango-mptt. Sadly, I’m having problems with outputing a cleaned data from the form. Here are some examples of the form fields that I’m using. Forms: from dal import autocomplete class StandardModelForm(forms.Form): first_field = forms.ModelChoiceField( queryset=StandardDjangoModel.objects.all(), widget=autocomplete.ModelSelect2( url='/standard-model-autocomplete/', ) ) helper = FormHelper() helper.form_method = 'POST' class Meta: model = StandardDjangoModel class MPTTModel1Form(forms.Form): second_field = TreeNodeChoiceField( queryset=MyMPTTModel.objects.all(), widget=autocomplete.ModelSelect2( url='/mptt-model-autocomplete/', ) ) class MPTTModel2Form(forms.Form): third_field = TreeNodeMultipleChoiceField( queryset=MyMPTTModel.objects.filter( level=2, contribution_type=1, ), widget=forms.CheckboxSelectMultiple() ) Models: class StandardDjangoModel(models.Model): name = models.CharField( max_length=50) def __unicode__(self): return self.name class MyMPTTModel(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) field = models.CharField( max_length=200) CONTRIBUTION_TYPES = ( (1, 'One'), (2, 'Two'), (3, 'Three'), ) contribution_type = models.IntegerField( choices=CONTRIBUTION_TYPES, blank=True, null=True) @property def root(self): return self.get_root().field def __repr__(self): return self.field def __unicode__(self): return self.field The views are as simple as can be: from formtools.wizard.views import SessionWizardView class FormularView(SessionWizardView): def done(self, form_list, **kwargs): user_form_input = self.get_all_cleaned_data() return render(self.request, 'summary.html', { 'form_data': user_form_input }) However, if the user inputs a non-ascii character, the following exception is raised (for clarity I've posted only the last lines): File "C:\PYTHON27\lib\site-packages\django\utils\encoding.py", line 80, in force_text s = six.text_type(bytes(s), encoding, errors) UnicodeEncodeError: 'ascii' codec … -
SyntaxError: unexpected EOF while parsing Django
I have this code and I have no idea why this happen.. I'm starting at django so please someone could help me? from django.conf.urls import url from django.contrib import admin from controlinv import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^Login/$', views.login, name='index-login'), url(r'^Inicio/$', views.index, name='indexF') At the end in the console says File "C:\intercamiones\mercedes\src\mercedesapp\urls.py", line 23 url(r'^Inicio/$', views.index, name='indexF') ^ SyntaxError: unexpected EOF while parsing -
Django contact form sending email
I created a contact form to send me an email when the user fills it out. Everything appears to be working, but I'm not getting an email. Here's my console output: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Michael Plemmons From: mplemmons1982@gmail.com To: californiamikegreen@yahoo.com Date: Thu, 02 Nov 2017 22:40:50 -0000 Message-ID: <20171102224050.12741.24539@ubuntu> hello this is a test ------------------------------------------------------------------------------- [02/Nov/2017 22:40:50] "POST /contact/ HTTP/1.1" 302 0 [02/Nov/2017 22:40:50] "GET /success/ HTTP/1.1" 200 36 This is views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from .models import * from .forms import contact_form from django.core.mail import send_mail, BadHeaderError from django.shortcuts import redirect def contact(request): if request.method == 'GET': form = contact_form() else: form = contact_form(request.POST) if form.is_valid(): contact_name = form.cleaned_data['contact_name'] contact_email = form.cleaned_data['contact_email'] contact_message = form.cleaned_data['contact_message'] try: send_mail(contact_name, contact_message, contact_email, ['californiamikegreen@yahoo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "contact.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your message.') This is urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'contact/$',views.contact, name='contact'), url(r'^success/$', views.success, name='success'), ] this is forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class contact_form(forms.Form): contact_name = forms.CharField(label='Contact Name', max_length=255) contact_email = … -
Django. Get data from post json request and search
I have my models FormField: class FormField(models.Model): fieldName = models.CharField(max_length=50) text = 'text' email = 'example@email.mail' phone = PhoneNumberField() date = models.DateTimeField TYPE_OF_FIELD_CHOICE = ( (text, 'text'), (email, 'example@email.mail'), (phone, '+9123456789'), (date, '2017-01-01') ) field_type = models.CharField(max_length=25, choices=TYPE_OF_FIELD_CHOICE, default=text) def __str__(self): return self.fieldName FormPattern class FormPattern(models.Model): formName = models.CharField(max_length=50) fields = models.ManyToManyField(FormField) def __str__(self): return self.formName And i need get data from json request and search it in FormField For example : mysite/get_data?f_name1=value1&f_name2=value2 If i found form with fields like this i need to send response in json with name of form's pattern. How can i handle this. I read something about json_view but dont find anything about get data from post json request. Please help if you can. -
How to show objects in the form field (Multiple Select Field) based on a condition in django form.
I have a many to many field linked with my model1. Now, I created a form for this model1 and added this many to many field as a form field and used FilteredSelectMultiple widget to edit this. Now, the problem is the related many to many field has a soft delete option, which I am tracking with active field in the model2. So, now in the form all the objects are displayed even if they are deleted, is there any way I can show the objects which have active as true in this form field. My model form looks as follows: class Editform(form.ModelForm): class Media: css = .. js = .. class Meta: Model = model1 fields = [ "x", "y", "ManytoManyfield"] widgets = { 'ManytoManyfield': FilteredSelectMultiple("Displaay name", False) } -
How to use reverse foreign key relationship twice in one query
I've the models defined as follows: class A(models.Model): name = models.CharField() class B(models.Model): a = models.ForeignKey(A, related_name='aa') name = models.CharField() class C(models.Model): b = models.ForeignKey(B, related_name='bb') name = models.CharField() I'm making a RESTful webservice for model A and I've a queryset defined as queryset = A.objects.prefetch_related('aa').all() But I want data from model C as well. But I'm not sure how can I do that? -
Overide Textarea in Django without models. Only in forms
I want to change default size of Textarea. I read: [https://docs.djangoproject.com/en/1.11/_modules/django/forms/widgets/#Textarea][1] But I don't know how can I override it MY CODE: forms.py: from django import forms class KarForm(forms.Form): message = forms.CharField( widget=forms.Textarea, label="", ) views.py: from django.shortcuts import render from .forms import KarelForm def home(request): form = KarForm() context = { "form": form } return render(request, "form.html", context) -
Django HttpResponseRedirect Results in 404 Error
I have a Django project called investigations which includes an app called alerts. The project worked in development but, while deploying to IIS, I had to change the URLs, and now an HttpResponseRedirect call is not working in one of my views. Here is the view: def alerts(request): newAlerts = Alert.objects.filter(disposition='') formset = AlertFormSet(request.POST or None, queryset=newAlerts) helper = AlertFormsetHelper() context = {'formset':formset, 'helper':helper} if request.method == 'POST': for form in formset: if form.is_valid(): if form.has_changed(): if form.is_valid(): form.save() entity = form.cleaned_data['entity'] messages.success(request, 'SUCCESS: Alert for %s was dispositioned' % entity) return HttpResponseRedirect('/alerts') return render(request, 'alerts/alerts.html', context) The page renders correctly when going to domainname/investigations/alerts. However, when a submit button is hit to save the changed form in the formset, a 404 error with no accompanying detail is returned. The address in the address bar is still domainname/investigations/alerts, as it should be. Here are the urlpatterns in urls.py for the alerts app: url(r'^investigations/$', views.index, name='index'), url(r'investigations/alerts', views.alerts, name='alerts') Why is the HttpResponseRedirect redirecting to the same page (as it should be) but returning a 404 error instead of the page itself? -
Django ImportError: No module named 'collection'
As stated in the title, I keep getting an error when trying to create a form. It's on the line that has: from collection.forms import contact_form An I'm getting the error: File "/home/mike/CINS465/465proj/project/firstapp/views.py", line 2, in <module> from collection.forms import contact_form ImportError: No module named 'collection' Any idea where I'm going wrong? I'm new to django and this was pulled from a tutorial on creating a contact form. I thought collection was built-in to django Thanks -
django/db/backends/mysql/operations.py full path please for ubuntu
Need full path for django.db.backends folder. I already searched for django folder in usr/lib, usr/local/lib/python2.7/dist-packages but unable to find it. -
Allow user to edit his own 'profile model', which has a OneToOne relationship with the user model
I am using the default User model along with a custom AgentBasicInfo 'profile model' with additional information about the user. I am trying to give each user the ability to edit his profile model and only his own. I am using the generic.edit UpdateView. I am confused as to how I approach this. I have tried a few things but gotten errors, mainly NoReverseMatch. See my code below: views.py class EditBasicInfo(LoginRequiredMixin, UpdateView): model = AgentBasicInfo form_class = AgentBasicInfoForm # the user want to edit this post must be owner this post def get_queryset(self): post_qs = super(EditBasicInfo, self).get_queryset() return post_qs.filter(user=self.request.user) models.py class AgentBasicInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_first_name = models.CharField(max_length=30) user_last_name = models.CharField(max_length=30) preferred_email = models.EmailField() office_phone_number = models.CharField(max_length=10) brokerage_of_agent = models.CharField(max_length=50) def __str__(self): return self.user_last_name urls.py url(r'^edit_base_info/(?P<pk>\d+)/$', views.EditBasicInfo.as_view(), name='edit_base_info'), HTML URL tag {% url 'edit_base_info' agentbasicinfo.id %} I need some guidance as to how I can achieve this. Thank you! -
Symptom form not saving data entered.
I am attempting to create a health app that saves patient data. I created the Unique_Identity table and the Symptom table along with a Unique_Identity_Symptom table the contains ForeignKeys for both tables. The Unique_Identity table contains the ManyToManyField field that establishes a relationship between both tables. Issue : Each time I enter data into to Symptom form and press save it redirects to the Symptom without saving it, and the data entered remains in the field What am I doing wrong? Here is the code : models document from django.db import models from django.contrib.auth.models import User from Identity import settings import datetime class Symptom(models.Model): symptom_Identity = models.CharField(max_length = 80, default = '') content = models.TextField(max_length = 1000, default = '') class Unique_Identity(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) first_name = models.CharField(max_length = 80, null = True ) last_name = models.CharField(max_length = 80, null = True ) contact = models.CharField(max_length = 15, null = True) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) symptom_relation = models.ManyToManyField(Symptom, through = 'Unique_Identity_Symptom') class Unique_Identity_Symptom(models.Model): patient = models.ForeignKey(Unique_Identity, related_name = 'symptoms') …