Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') … -
dynamically reference property of self in python
I currently have a bunch of language checks in place in a python (django) function: def __get__(self, instance, owner): if translation.get_language() == 'fr': trans_field = getattr(instance, self.fr_field) else: return getattr(instance, self.en_field) What I want to do is run this in a loop: for language in languages: if translation.get_language() == language: return getattr(instance, self.[language]_field) else: return getattr(instance, self.en_field) How do I do this? Obviously the self.[language]_field is pseudocode -
how to handle select boxes in django admin with large amount of records
my app has grown so that that drop downs in the django admin have 100,000s of options. I can't even open my admin anymore because of its load on the database, not too mention I wouldn't be able to find an option in the select box. Does django have an autocomplete option? What is the best option for handling big data in django admin? -
how to make field unique for current user django
I've got Skill model like this: class Skill(models.Model): user = models.ForeignKey(User, blank = True) title = models.CharField(max_length=20) percentage = models.PositiveIntegerField(validators=[MaxValueValidator(100)]) expirience = models.PositiveIntegerField(validators=[MaxValueValidator(80)]) And now I want to make field "title" unique for current user, so User1 couldn't create 2 skills with same titles, but User1 and User2 both could create skill with same titles. I guess there must be some simple solutions without such validation in skill_new() view, but couldn't find any. -
django.utils.datastructures.MultiValueDictKeyError DJANGO
I have a form. When I post the form without using ajax, it works well. But when I use the ajax, I have an error like this; django.utils.datastructures.MultiValueDictKeyError: My codes are below that without using ajax. It works. HTML Form: <form id="add_form" action="/adding/" method="post" enctype="multipart/form-data"> <input type="text" name="title"> <input type="file" name="picture"> <button type="submit" id="send_form" value="ok">Ok</button> </form> My views.py codes are: if request.method == "POST": title = request.POST.get('title') pic = request.FILES['picture'] query = Images_Table(title=title, pic=pic) query.save() My model codes are: class Images_Table(models.Model): title = models.CharField(max_length=70, blank=True, null=True) pic = models.FileField(upload_to='images_folder', blank=True, null=True) Until here; everythings are normal, codes works. When I use ajax, I have an error. My HTML Form: <form id="add_form" method="post" enctype="multipart/form-data"> <input type="text" name="title"> <input type="file" name="picture"> <button id="send_form" value="ok">Ok</button> </form> My ajax codes are: $("#send_form").click(function(){ $.ajax({ url: '/adding/', method:'post', data: $("#add_form").serialize(), headers: '{{ csrf_token }}', success : function(){ alert('Success posted!'); } }); }); Error code is below; django.utils.datastructures.MultiValueDictKeyError: "'picture'" -
django - cannot import name settings
I'm working on a site in django that is actually in production. I'm trying to run it in local but i get the error: cannot import name settings when i try to access the main page. This page use the bbcode apps that's correctly installed but that I suspect to be the source of my problem (pages without bbcode work well). When i run manage.py runserver everything goes well Then here is the StackTrace when i'm trying to access the main page: Traceback (most recent call last): File "/usr/lib64/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 44, in inner response = response_for_exception(request, exc) File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 94, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/usr/lib/python2.7/site-packages/django/template/response.py", line 109, in render self.content = self.rendered_content File "/usr/lib/python2.7/site-packages/django/template/response.py", line 84, in rendered_content template = self.resolve_template(self.template_name) … -
Django Translations Not Working
I am working in a Django 1.9 / python3.5 application, and trying to make use of Django's translation utility. I have a locale directory which has an 'es' directory for spanish translations that I created a .po file in. I set it up to have a couple translations just to test it out. msgid "Sign In" msgstr "Registrarse" msgid "Create an Account" msgstr "Crea una cuenta" I have my setting file correctly configured as well # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LOCALE_PATHS = ( os.path.join(PROJECT_ROOT, 'locale/'), ) from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), # first language is the default used by modeltranslations ('es', _('Spanish')), ) LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Chicago' USE_I18N = True In my template I use the Django 'trans' template tag for the words sign in, and create an account. A select box will edit the Content-Language http response header from the application, which I have tested, and it successfully does so. However the headers sign up, and create and account, do not translate to Spanish. Is there some step I'm missing ? HTML {% load i18n %} <ul class="list-inline-xxs"> {% if customer %} <li> Welcome, <a href='{% url "customer:dashboard" %}'> {{ customer.first_name }} … -
How to work with custom templates for CMS in Django?
I am planing to develop a generic event management system. It has two parts: Public Website (information about the event, logo, sub-events, participants, list of event managers, etc.) Admin Panel (ticketing, statistics, event managers, teams, participants, etc.) What I am trying to do: When an event is selected as active in the "Admin Panel" by superadmin. The theme (HTML/django template/CSS/JS) of that event should be activated for the 'public site' instead of the default theme. I tried to look into wagtail and django-cms but I couldn't find anything. I am not even sure where to begin with this in Django. I am sorry about the title of the question, I couldn't think of anything better. Thank you. -
Update field of onetoone related model with django form
In models.py: class UserProfile(models.Model): user = AutoOneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='user_avatars/', default = 'user_avatars/default-avatar.jpg') male = 'M' female = 'F' gender_choices = ((male,'Male'), (female,'Female')) gender = models.CharField(choices = gender_choices, max_length = 10) dateOfBirth = models.DateField(default = datetime.date.today) follows = models.ManyToManyField("self", related_name = 'followers', symmetrical=False,\ blank = True) favorite_pet = models.ManyToManyField(Pet, blank = True) def __str__(self): return self.user.username In forms.py: class EditProfileForm(forms.ModelForm): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') email = forms.EmailField() gender_choices = (('M', 'Male'), ('F', 'Female')) gender = models.CharField(choices=gender_choices, max_length=10) dateOfBirth = models.DateField() class Meta: model = User fields = ['first_name', 'last_name', 'email'] I want to allow users to change their gender and dateOfBirth. However, these fields belong to UserProfile class (which has one-to-one relationship with User), thus if I add 'gender' and 'dateOfBirth' to array fields in meta class I will get "unknown fields" error from User class. Could anyone show me how to achieve my goal? Any help will be highly appreciated :D -
DRF get current user details
I want to get the current logged in user's details: views.py class UserData(APIView): permission_classes = (IsAuthenticatedOrReadOnly,) def get(self, request): serializer = UserSerializer(self.request.user) return Response(serializer.data) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['id', 'email', 'valid_email', 'nickname', 'name', 'date_of_birth', 'city', 'country', 'date_joined'] When i'm trying to access the url i get this error: AttributeError at /core/user-data/ Got AttributeError when attempting to get a value for field `email` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `AnonymousUser` instance. Original exception text was: 'AnonymousUser' object has no attribute 'email'. The thing is that i am logged in. What could cause the error? -
Get error in Django Unsupported lookup '_gt' for IntegerField or join on the field not permitted
I try to sort goods in online shop In models-- class Good(models.Model): stock = models.IntegerField(default=0) In views -- def stock_view(request): goods = Good.objects.filter(stock__gt=0) context = {"goods": goods} return render(request, "goods/sale.html", context) -
Django - How to exclude already selected object from queryset in form?
I am seeking an advice on how to approach the following problem: I am having these models: Event > EventAttendees > EventRoster. Every event has attendees (users) which I would like to assign to specific positions (attributes of EventRoster) for that particular Event. Example: -Event(Football/Soccer game), attendees: (Bob, John, Mike, Steve), EventRoster: (Bob = goaltender, John = left wing, Mike = center, Steve = defence) Idea is to have a form for event, where anyone from attendees can be assigned to any of the positions. Each form field would represent a position, where attendee can be selected, if that attendee was not already selected for different position. My problem is, that I am selecting attendees from EventAttendees.objects.all() or .filter(event__pk=pk) without updating this queryset to exclude attendees that are already selected for some other position. What I am aiming for is to exclude attendee from queryset if that attendee is already selected in form field (position). Basically to have empty queryset once all attendees are assigned to all positions. What would be the best way to approach this? I have found similarities in so called chained fields, but I guess these are not applicable in this scenario. Probably I will not … -
Python email account script
I am looking for python(Django actually) based email script that will automatically create emails and verify them as well (could be for gmail,yahoo or any email service). The problem is I don't know how to automate this process. I have google many times but it shows me result for sending emails (spamming). Then the script will use that email to signup for further websites. I just need to know process for email creation. -
Where to write predefined queries in django?
I am working with a team of engineers, and this is my first Django project. Since I have done SQL before, I chose to write the predefined queries that the front-end developers are supposed to use to build this page (result set paging, simple find etc.). I just learned Django QuerySet, and I am ready to use it, but I do not know on which file/class to write them. Should I write them as methods inside each class in models.py? Django documentation simply writes them in the shell, and I haven't read it say where to put them. -
Django Oscar payment method errors when setting up
I've been having problems setting up the payment methods that can be used with Django Oscar. I've tried using django-oscar-datacash and django-paymentexpress. The problem is, everytime I try to migrate, it's been saying that there is not module named south. However, when I installed south and migrated, what happened was it said that south doesn't exist in the database. I've read about south being removed from the current versions, so I tried rolling my Django back to version 1.7. When I tried to migrate, it threw and HTMLParserError which was fixed in the latest Django versions that are not compatible with south anymore. How do I properly setup payment methods in Django Oscar? Aren't there any new libraries since the ones that I saw were modified 3-5 years ago. I also tried django-oscar-paypal but when I migrate, nothing is migrating and that the documentation is kind of confusing. Is there any way around this issue? -
Object is not JSON Serializable django AJAX
I have this script $.ajax({ url: "/schedule/ajax/view_people", data: { 'schedule': id }, dataType: "json", success: function(data) { console.log(data); }, error: function(data) { console.log(data.responseText); }, type: "post" }); And I have this view def view_involved_people(request): schedule = request.POST['schedule'] query = Schedule.objects.get(id=schedule) data = {'people': query} return JsonResponse(data) Why does it display that the object is not serializable when I already called the JsonResponse function -
Django Template won't escape HTML
I have a model that extends a django-mailbox email message. If an email message is in text format, as_html() will convert the text to html. (It wraps the text in a <pre> tag.) class EmailReply(models.Model): def as_html(self): if self.message.html: return self.message.html elif self.message.text: context = { 'email': self.message.text } return mark_for_escaping( render_to_string( APP_NAME+'/email/text_as_html.html', context ) ) message = models.OneToOneField('django_mailbox.Message') ... I want to display several email messages in a single html page. I have a view that iterates over several EmailReply objects. Rather than linking to the message, I need to include the html in the iframe's srcdoc. (I'm converting the page to PDF, and the converter works better having everything in one page.) {% for email in emails %} <div class="page"> <ul> <li>Subject: {{ email.message.subject }}</li> </ul> <iframe srcdoc="{{ email.as_html|escape }}" frameBorder="0" scrolling="no" sandbox></iframe> </div> {% endfor %} For messages that have an html component, the html is escaped: <div class="page"> <ul> <li>Subject: Example 1</li> </ul> <iframe srcdoc="&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;[...]" frameBorder="0" scrolling="no" sandbox></iframe> </div> However, messages that are text come through without being escaped: <div class="page"> <ul> <li>Subject: Example 2</li> </ul> <iframe srcdoc=" <!DOCTYPE html> <html> <head> <title>Email Reply</title> <meta charset="utf-8" /> </head> <body> [...] </body> </html> " frameBorder="0" scrolling="no" sandbox></iframe> …