Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
no "word wrapping" in django-admin display
So I defined models.py like this: class Venue(models.Model): ... def __unicode__(self): return self.country+"-"+self.zipcode+" "+self.city+", "+self.name+", "+self.street and I am using it in admin.py like this with "venue" as ForeignKey class EventAdmin(admin.ModelAdmin): list_display = ["date_begin", "date_end", "speaker", "description", "venue"] Everything works fine but in the admin-display every string is automatically word-wrapped except the "venue" which is only one line. And it takes up most of the space as it is rather long and other strings have to be wrapped in like 3-4 lines. Can I change it so that the "venu"-string is also automatically wrapped in 2-3 lines if it is too long? Thanks -
dj-stripe [python module] how do i sync my plans from stripe to django?
I have installed and tried it. but there is nowhere in the documentation any mentions on how to sync the plans and subscriptions from stripe to the django objects. -
sendgrid mail not working on centos server
I have configured sendgrid mail on django project and it works fine in local server, but when I deployed on centos server on digital ocean it is not sending any mail, hope some body can help me. Mail setting as follows. EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'usr' EMAIL_HOST_PASSWORD = 'pwd' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Running python file on HTML button click (Django)
Relevant information: 1) First post on here, go easy. 2) I'm a noob. 3) Trying to learn python/Django. What I'm trying to do: 1) Create an english -> pig latin translator (written in python) and have it work in browser. How I want it to work: 1) User clicks "translate" button, which then uses my existing python function to translate their input. 2) The translation is then displayed below the input. What I've done so far: 1) Created .py file that successfully translates english -> pig latin in the console. def pigLatin(sentence): translation = " " for word in sentence.split(): if word[0] in "aeiou": translation += word + "yay " if word[0] and word[1] not in "aeiou": translation += word[2:] + word[0:2] + "ay" print("hai") else: translation += word[1:] + word[0] + "ay " return translation sentence = input("Enter word/sentence you want translated to pig latin below: ") print(pigLatin(sentence)) 2) Used Jinja/added some HTML and bootstrap (please see below) What it looks like in browser 3) Created a Django project, and installed my pig latin app, my folders are structured as so: --mysite | |--pigLatinApp |----templates |------pigLatinApp |--------home.html |--------header.html 3) Attempted to use Ajax to get my button working, my … -
django start server fails
Am trying to run default python default server with virtual environment via python manage.py runserver but am getting an error "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?. I have already enabled the virtual environment and when i check django-admin --version am getting 1.11.7 Where could i be going wrong? -
models.py and views.py may be conflicting
Below are the output of the models.py from django.db import models from django.core.urlresolvers import reverse #from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Registration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length = 250) password = models.CharField(max_length = 250) email = models.CharField(max_length = 250) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Registration.objects.create(username=instance) instance.registration.save() Below is the output of the views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm from django.views import generic class IndexView(generic.View): templet_name = 'user_info/index.html' def signupview(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('registration_form.html') else: form = SignUpForm() return render(request,'user_info/registration_form.html', {'form': form}) I have two questions: 1) In my models.py I have 4 fields, 'user','username','password','email'. In my first field "user", I guess, I shouldn't be using "models.OneToOneField(User, on_delete=models.CASCADE)", because, as per my understanding, it's used when we have a primary key and foreign key in working. Please correct me if I am wrong. 2) in my views.py, the function "signupview", I am saving the form in the database through form.save(), and … -
Restore single table in Heroku PostgreSQL database from dump
I can restore my complete Heroku production PostgreSQL database from a dump with the heroku pg:backups:restore command as described here. Is there a way to restore just one table, while leaving the other tables intact? I can create a dump of the table I want to restore, but heroku pg:backups:restore will delete any table that's not in the dump. -
Django update form values on page refresh
I have a class in forms.py that set the ui for that form, some of which are a drop down menu populated by an (external) database class myForm(forms.Form): barcodes_list = getBarcodes(server_database) barcodes= forms.TypedChoiceField(label='Barcodes', choices=barcodes_list, widget=forms.Select(attrs={'style':'width:164px'}), initial = '' ) the barcodes_list is only ran on restart of the Django server. If the page is refreshed the barcode list stays the same even if there was a change on the database. I would like barcodes_list to be run again on refresh. I have tried adding this within the myForm class as per similar questions on SO def __init__(self, *args, **kwargs): super(myForm, self).__init__(*args, **kwargs) barcodes_list = ... -
Take `self` without '__init__' an instance in advance
'Generic view class' in Django puzzles me very much. for instance: class ProfileDetailView(DetailView): def get_object(self): username = self.kwargs.get('username') if username is None: raise Http404 return get_object_or_404(User, username__iexact=username, is_active=True) Without the procedure of get instantiated, it works as well. What I can understand is: class ProfileDetailView(DetailView): def __init__(self, *args, **kwargs) super().__init__() def get_object(self): username = self.kwargs.get('username') if username is None: raise Http404 return get_object_or_404(User, username__iexact=username, is_active=True) What's the mechanism behind it? -
Python Django Build Raw SQL Query From Given List
I try to get some information from my database backend performing a raw SQL query. I need to do calculations (multiplying it with a factor, truncating it) and convert it in a performant way to JSON. That's the reason why I have chosen to not use the (Django) ORM here. with connection.cursor() as cursor: cursor.execute( ''' SELECT json_build_object( 'data', array_agg(r) ) FROM ( SELECT time, trunc(column1 * 100, 2) as COL1, trunc(column2 * 100, 2) as COL2, [...] FROM measurements WHERE device_id=%s ORDER BY time DESC LIMIT 5 ) r ''', [device_id] ) result = cursor.fetchall() I need to adapt the statement above from the following list: [ {'column': 'column1', 'factor': 100, 'description': 'COL1', 'trunc': 2}, {'column': 'column2', 'factor': 100, 'description': 'COL2', 'trunc': 2}, [..] ] Since I am not used to the python syntax yet I am wondering if there is an elegant solution for creating such a statement. I know I could just loop over the list and append the query but that doesn't feel good/right to me. Any suggestions would be appreciated. -
Versioning of js and css in Django
I have uploaded js and CSS files under static folder by returning below from settings.py: return os.path.join(get_valid_filename(filename)) I want to know how can I update the same CSS and js file -
Show all book names in a category with foreign key relation, noob with django
hi i am new to djnago because of a school project , i want some help in order to get started. i need help to show data with a foreign key relation. When i click in a category i want to show all the books in that category but automatically. lets say i am at example.com/category/2 , i want somehow when the category.id is 2 to get the the Category.name , and then search(filter) at other model book.category and get the book.title i would also appreciate if i could get some template code for the loop required to present the data. Thanks in advance models.py class Category(models.Model): name=models.CharField(max_length=50) class Meta: verbose_name_plural ="Categories" def __unicode__(self): return self.name class Book(models.Model): title=models.CharField(max_length=200)` category=models.ForeignKey(Category,related_name='book_category', null=True) def __unicode__(self): return self.title views.py def category(request, category_id=1): category=Category.objects.get(id=category_id) return render(request, 'view_category.html', { 'category': category, } ) urls.py url(r'^category/(?P<category_id>\d+)/$', 'seminar.views.category'), -
Django REST API return fields from ForeignKey in related model
With the following models: class Tabs(models.Model): name = CharField(max_length=64) def __str__(self): return self.name class DataLink(models.Model): data_id = models.ForeignKey(...) tabs_id = models.ForeignKey(Tabs, ...) def __str__(self): return "{} {}".format(self.data_id, self.tabs_id) DataLink: Tabs: id | data_id | tabs_id | id | name ------+-----------+----------- | ------+-------- 1 | 1 | 1 | 1 | tab1 2 | 1 | 2 | 2 | tab2 3 | 1 | 3 | 3 | tab3 4 | 2 | 1 | 4 | tab4 5 | 2 | 4 | 5 | tab5 I need to link data between two models/tables such that for a given data_id I can return a list of corresponding tabs, using the Tabs table and the tabs_id. For example: data_id = 1 would return ['tab1', 'tab2', 'tab3'] data_id = 2 would return ['tab1', 'tab4'] Is this possible? How? Is it a bad idea? -
Create instance of model with field with choices
Lets consider this model: class MyModel(models.Model): DEFAULT = 1 NOT_DEFAULT = 2 SOMETHING = 3 SOMETHING_ELSE = 4 CHOICES = ( (DEFAULT, 'foo') (NOT_DEFAULT, 'bar') (SOMETHING, 'tar') (SOMETHING_ELSE, 'oof') ) field1 = models.CharField( max_length=128, ) field2 = models.SmallIntegerField( choices=CHOICES, default=DEFAULT ) how to i fill it with this data? name, status 'one', 'foo' 'two', 'oof' 'tree', 'foo' 'four', 'foo' 'five', 'tar' 'six', 'bar' that does not work since it's expecting an integer MyModel.objects.create('one','foo') how do i do it properly without stupid workarounds? is there a build in mapping like 'foo' -> 1 'oof' -> 4 etc.? -
Check Email Validation Django
Can someone explain how to validate an email adress in Django? So for Example i want to check if an email is a valid college email adress with the ending .edu . How can i do that? from django import forms from .models import SignUp class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['full_name','email'] def clean_email(self): email = self.cleaned_data.get('email') return email