Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Initialize form with request.user in a ModelForm django
I have this ModelForm class ScheduleForm(forms.ModelForm): class Meta: model = Schedule fields = ['name', 'involved_people',] def __init__(self, user, *args, **kwargs): super(ScheduleForm, self).__init__(*args, **kwargs) self.fields['involved_people'].queryset = Profile.objects.exclude(user=user) This is my view def create_schedule(request): form = ScheduleForm(request.POST or None) schedules = Schedule.objects.all().order_by('deadline_date') if form.is_valid(): schedule = form.save(commit=False) schedule.save() messages.success(request, "Schedule added successfully!") return render(request, 'schedule/index.html', {'schedules': schedules}) context = {'form': form} return render(request, 'schedule/create_schedule.html', context) How do you pass request.user in the view? How do you initialize the form with request.user in it? -
wave.Error: file does not start with RIFF id Is there mistake in my code?
I got an error,wave.Error: file does not start with RIFF id . I wrote in views.py if __name__ == "__main__": train_label = np.array([]) test_label = np.array([]) nfft = 2048 nceps = 12 train_data = np.empty((0, 12), float) test_data = np.empty((0, 12), float) directory = os.listdir('/sound_app/sounds') for file_name in directory: feature = get_feature(file_name, nfft, nceps) if len(train_data) == 0: train_data = feature else: train_data = np.vstack((train_data, feature)) train_label = np.append(train_label) test_label = np.append(test_label,file_name) in mfcc.py def get_feature(wavfile,nfft,nceps): wav,fs = wavread(wavfile) t = np.arange(0.0,len(wav)/fs,1/fs) center =len(wav)/2 cuttime = 0.8 global wavdata wavdata = wav[int(center-cuttime/2*fs):int(center+cuttime/2*fs)] global time time = t[int(center-cuttime/2*fs):int(center+cuttime/2*fs)] ceps = mfcc(wavdata,nfft,fs,nceps) return ceps.tolist() /sound_app/sounds's file has many wav file.I doubt these wav file are really wav file,so I run command /sound_app/sounds/0517.wav & /sound_app/sounds/0518.wav etc ,so it is returned RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 44100 Hz .So I think these are really wav file.Therefore I cannot understand why this error happens.Do i make a mistake in my code?How should I fix this? -
Django static file loading error on centos
I have static file loading issue and when I run collectstaic command, it throws error 'Found another file with the destination path 'admin/js/vendor/xregexp/xregexp.min.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path'. Following is my settings for static files in centos server. STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATIC_ROOT = '/root/www/static-root/' MEDIA_URL = '/media/' MEDIA_ROOT = '/root/www/media-root/' I couldn't find another place where static files get stored. How I can solve the issue, thank you. -
Django - get linked models in many to many
I have two different models: A group model class Group(models.Model): (...) users=models.ManyToManyField(users.User, related_name='trainings') And a very standard user model. I'm trying to write a function where it returns all of the linked groups for a given User object. What would solve my problem is something like this: def get_groups(user): connected_groups = Group.objects.filter(user in users) But that throws an error. It the thing that I am trying possible? Or should I instead create a 'linked_groups' variable within the User model? -
'P' for what in url(r'^(?P<slug>[\w-]+)/$' [duplicate]
This question already has an answer here: what does this django regex mean? `?P` 3 answers In Django's urls.py: url(r'^(?P<slug>[\w-]+)/$', I understand 'slug' is variable,'[\w-]+' is value. What's 'P' stand for? -
Django Rest Framework: How to set a field to null via PATCH request?
I have a Model and a ModelSerializer with this field: models.py: leftovers_from = models.ForeignKey('DayPlanning', null=True, blank=True, related_name='extra_for', on_delete=models.CASCADE) serializers.py: leftovers_from_id = serializers.PrimaryKeyRelatedField(queryset=DayPlanning.objects.all(), source='leftovers_from', write_only=True, required=False) Now I can perfectly fine create a new object for this model using a POST request (both with or without this field being null/None/empty.) However when I try to update the field using PATCH I can only update it with a different value (a PK of the Foreign model). I've tried passing null, '', 0 and -1 to leftovers_from_id, however the result is either This field cannot be empty or PK 0 not found. How do I clear this field using a PATCH request? Thanks! -
How correctly show ValidationError in Django and AJAX?
In my Django project I have modal with form where superuser can create new user. I want to show ValidationError which I set in forms.py file when superuser by mistake write existing email or passwords are not similar. Right not when superuser submit form which has mistakes as I described above browser raise error: SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data Uncaught TypeError: a.replace is not a function at Function.htmlPrefilter (jquery.min.js:3) at qa (jquery.min.js:3) at Ja (jquery.min.js:3) at r.fn.init.append (jquery.min.js:3) at r.fn.init.<anonymous> (jquery.min.js:3) at T (jquery.min.js:3) at r.fn.init.html (jquery.min.js:3) at Object.error (crud.js:45) at i (jquery.min.js:2) at Object.fireWith [as rejectWith] (jquery.min.js:2) QUESTION: How to show error messages correctly when data is not valid? forms.py: class UserCreateForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'is_active', 'is_superuser', 'password1', 'password2') def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError(_("Email already exists.")) return email def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError(_("Enter the same password as above, for verification.")) return password2 views.py: class UserCreateView(CreateView): template_name = 'users/create_user.html' form_class = UserCreateForm def get(self, request, *args, **kwargs): data = dict() user_create_form = UserCreateForm() context = {'user_create_form': user_create_form} … -
Django - Filter select choices based on another selected element
I have two models that are related class Filial(models.Model): descricao = models.CharField(max_length=255) empresa = models.ForeignKey( 'BOXCFG.Empresa', related_name="filiais", on_delete=models.CASCADE) class Empresa(models.Model): razao_social = models.CharField(max_length=255) logo = models.ImageField( upload_to=logo_directory_path, default='images/totvs.jpg') I want to create a form that only shows Filial options that are related to the selected Empresa in a previous form field on the same page. Is there an easy way to do this with Django? -
Need Help in a django empty popup
I want to create a popup in a django template but the popup appears empty This is my code so far: <input type="button" value="{{ account.account_id }}" class="btn btn-primary" data-toggle="modal" data-target="#myModal" id="myid"/> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> <iframe src="{% url 'Trinity:accountinfo'%}?id={{account.account_id}}" width="300" height="380" frameborder="0" allowtransparency="true"></iframe> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> but if I do the iframe like this : <iframe src="{% url 'Trinity:accountinfo'%}?id=123509817994125" width="300" height="380" frameborder="0" allowtransparency="true"></iframe> It works! But I want that the id to take dinamically not hardcoded. Any idea would appreciate! Thanks! -
Unable to python manage.py migrate successfully
This is the crux of the error: django.db.utils.OperationalError: (1553, "Cannot drop index 'user_id': needed in a foreign key constraint")