Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Two FormViews in a Template
everyone! I want to display to forms in a template My forms are: class ContactForm(forms.Form): contact_name = forms.CharField( required=True) contact_email = forms.EmailField( required=True) contact_phone = forms.CharField( required=True) subject = forms.CharField( required=True) message = forms.CharField( required=True, widget=forms.Textarea) class CVCreateForm(forms.ModelForm): class Meta: model = CV fields = '__all__' And I have two FormViews: class ContactView(FormView): form_class = ContactForm succes_url = reverse_lazy('webpage:home') def form_valid(self, form): context = super(ContactView, self).form_valid(form) contact_email = form.cleaned_data['contact_email'] subject = form.cleaned_data['subject'] message = 'Name: {}\nPhone:{}\n{}'.format(form.cleaned_data['contact_name'], form.cleaned_data['contact_phone'], form.cleaned_data['message'],) send_mail(subject, message, contact_email, ['maumg1196@gmail.com']) return context class CVCreateView(FormView): form_class = CVCreateForm succes_url = reverse_lazy('webpage:home') def form_valid(self): context = super(CVCreateView, self).form_valid(form) form_owner = form.cleaned_data['owner'] form_cv = form.cleaned_data['cv'] form_email = form.cleaned_data['email'] send_mail('Curriculum Vitae', form_cv, form_email, ['maumg1196@gmail.com']) cv = CV(owner=form_owner, email=form_email, cv=form_cv) cv.save() return context (Note: In the second form the 'form_cv' is gonna be a PDF file I think that isn't a problem to send the email but I don't know very well.) I want to display this two FormViews in a TemplateView Thanks :) -
Django - Same page record 2 models and use searchbox for select a few foreignkey
I have these models; class User(models.Model): name = models.CharField(max_length=40) phone = models.CharField(max_length=13) class Project(models.Model): name = models.CharField(max_length=500) start_date = models.DateTime() class ProjectUser(models.Model): user = models.ForeignKey(User) project = models.ForeignKey(Project) Q1 : So i want to record project and projectUser from same page. Q2 : if possible i want to use searchbox instate of combobox. Like Stackoverflow's tags (has search, select and cancel button to selected one) Thanks from now. -
Bootstrap nav-tabs not working in django template
I am using bootstrap nav-tabs in my django template. Basically, I have certain data that I am showing using a data-table. Each row in data-table has a view button, upon clicking the view button a modal window pops up which consists of below code with bootstrap nav-tabs. Each modal window has three tabs menu1, menu2, menu3 Here I am iterating the same code for all the data in data-table using for loop .For the first row's view button in the data-table, the nav-tab works fine, meaning the active class gets changed depending on which tab we click and the respective content in that tab is displayed. But for all other rows in the data-table when one clicks the view button the modal pops up, the 'active' class for the elements with classes tab-pane is supposed to change depending on which tab one clicks, but it is not getting changed. I mean if I click menu2 button the element with menu2 as id should become active in general, but it is not happening. The content of menu1 is getting shown by default for all the tabs. But this works perfectly fine for the first row in the data-table, Any hints on … -
How to write and set a custom dashboard perm in django-oscar
question regarding django-oscar framework: I'm using a mixin in my dashboard views to handle a concrete user access permission, customizing dispatch(). I'd like to remove the mixin, and add this user-access-requirement to the permissions_map in the parent dashboard view to affect all of them. So it'd be something like: class DashboardApplication(BaseDashboardApplication): permissions_map = { 'index': (['is_staff', 'my_custom_requirement'], ['partner.dashboard_access', 'my_custom_requirement']), } My questions are, is this the correct approach? Where should I write this function? Thanks -
Django-gears collectasset command error: gears.exceptions.FileNotFound:
I has a problem with django-gears package, when trying to run collectassets command: python manage.py collectassets This project successfully works on one server, but when i am trying to copy him to another one, i has a following error: gears.exceptions.FileNotFound: js/plugins/fancybox/jquery.fancybox.pack.js When i am trying to load index page, i have a: OSError at /[Errno 2] No such file or directory from this string in template: {% css_asset_tag "css/style.css" %} Gears config: GEARS_ROOT = os.path.join(PROJECT_ROOT, 'static') GEARS_DIRS = ( os.path.join(PROJECT_ROOT, 'assets'), ) GEARS_COMPRESSORS = { 'text/css': 'gears_clean_css.CleanCSSCompressor', 'application/javascript': 'gears_uglifyjs.UglifyJSCompressor', } GEARS_COMPILERS = { '.less': 'gears_less.LESSCompiler', '.styl': 'gears_stylus.StylusCompiler', } GEARS_PUBLIC_ASSETS = ( lambda path: not any(path.endswith(ext) for ext in ('.css', '.js')), r'^css/style\.css$', r'^css/ie/ie\.css$', r'^css/tinymce\.css$', r'^css/fancybox/jquery\.fancybox\.css$', r'^js/script\.js$', r'^ww/css/style\.css$', r'^ww/js/script\.js$', ) Which reason may generate this errors ? Project works on gunicorn, also i set 777 for assets and static folders. -
ImproperlyConfigured error with include to other url file
I'm using django-cookiecutter to bootstrap my project which will include api paths. Following the steps in Two Scoops of Django 1.11 to configure my urls to follow a similar pattern to this: api/foo_app/ # GET, POST api/foo_app/:uuid/ # GET, PUT, DELETE api/bar_app/ # GET, POST api/bar_app/:uuid/ # GET, PUT, DELETE When I try to setup my project like this I'm getting the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'my_project.core.api_urls' from /Users/username/Development/my_project/my_project/core/api_urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. My current setup: my_project.config.settings.base.py ROOT_URLCONF = 'config.urls' DJANGO_APPS = [ # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Useful template tags: # 'django.contrib.humanize', # Admin 'django.contrib.admin', ] THIRD_PARTY_APPS = [ 'crispy_forms', # Form layouts 'allauth', # registration 'allauth.account', # registration 'allauth.socialaccount', # registration 'rest_framework', ] # Apps specific for this project go here. LOCAL_APPS = [ # custom users app 'my_project.users.apps.UsersConfig', 'my_project.core.apps.CoreConfig', ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS my_project.config.urls.py from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views urlpatterns = [ url(r'^users/', include('my_project.users.urls', namespace='users')), url(r'^api/', include('my_project.core.api_urls', namespace='api')), … -
Update Queryset and Stay on the Same Page
I currently have a from that my users fill out. From there the site admin has to either approve or decline the form. I'd like to quickly approve or decline these entries. Here is the relevant models.py class MyModel(models.Model): STATUS_CHOICES = ( ('Submitted', 'Submitted'), ('Approved', 'Approved'), ('Declined', 'Declined'), ) user= models.ForeignKey(UserProfile) status = models.CharField(max_length=55, choices=STATUS_CHOICES, default='Submitted') Once the user submits it, I have a view that lists all instances where MyModel.status is Submitted. Here is that views.py @staff_member_required def review(request): pending = MyModel.objects.filter(status="Submitted") Finally I have an approve view: # views.py @staff_member_required def approve(request, id): MyModel.objects.filter(id=id).update(status="Approved") #urls.py url(r'^review/approve/(?P<id>[\w\-]+)/$', views.approve), What I want to do is have a button I can click on to approve the form and have the accepted object disappear, as opposed to having to click a button to accept, then refresh the page and do the same thing for the next one. Any idea on how I can accomplish this? -
Name 'self' not defined in class?
I'm attempting to filter a queryset by owner, but using self.request.user results in a NameError for some reason. class PackageListView(LoginRequiredMixin, ListView, Self): model = Package user = self.request.user queryset = Package.objects.filter(owner=user).order_by('-received_date') How do I fix this? -
How to generate a Matplotlib plot in a Django web app which can be parametrized using a form
I'm trying to write a Django web app which displays a plot of a function with several parameters, however I wasn't able to find any examples of this on the web. So far I've created an mpl app within a mpldjango project with the following structure: . ├── db.sqlite3 ├── manage.py ├── mpl │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── mpldjango ├── __init__.py ├── __pycache__ ├── settings.py ├── urls.py └── wsgi.py where mpl/views.py is import django from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np def make_canvas(rate): rate = float(rate) fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) x = np.arange(-2, 1.5, 0.01) y = np.sin(np.exp(rate * x)) ax.plot(x,y) return canvas def mplimage(request, rate=2): canvas = make_canvas(rate=rate) response=django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response and mpldjango/urls.py is from django.conf.urls import include, url from django.contrib import admin import mpl.views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'mplimage.png/a=(?P<rate>[0-9]+)', mpl.views.mplimage), url(r'mplimage.png', mpl.views.mplimage), ] Now, after python manage.py runserver, if I browse to http://localhost:8000/mplimage.png/a=3, for example, I get the plot with the rate parameter set to 3: and similar if I … -
Moving fields to separate model in Django
Let's say we have a Person model with email, bounced and bounced_date fields. We want to allow users to have more than one email address. We create a separate EmailAddress model with address, bounced, bounced_date, and a ForeignKey field to Person. We use order_with_respect_to so users can have email addresses ordered by preference. Writing the migration needs a few lines of SQL. We also define email property in the Person model which return the address field of the first related EmailAddress, so we don't need to make code changes everywhere the email field was used on our Person objects. The last thing I cannot find a way to do is finding a way to have .get(email='example@example.com') still working. EmailAddress are unique so there should still be a unique user attached to each email address. -
Django 'if settings.DEBUG:' What that mean
I am django beginner. When i code file upload, i don't understand this code if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) why we had to code if settings.DEBUG:. Please answer, thank you -
Save image from URL with serializer
I am creating an API that saves images in a django model. Through the API is sent a URL and django is responsible for downloading the image and saving it in the model. This is my model: class Picture(Media): image = models.ImageField(upload_to=picture_path, blank=True, null=True) entity = models.CharField(max_length=20, choices=ENTITIES, default=ENTITY_CLASIFICADO) This is my serializer: class PictureSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = Picture fields = ("pk", "image", "entity",) From the URL I generate a PIL object. How do I specify the serializer that stores the object? My views.py class PictureViewSet(generics.ListCreateAPIView): def create(self, request, *args, **kwargs): r = requests.get(request.data["url"]) img_temp = NamedTemporaryFile(delete = True) img_temp.write(r.content) Now, I'm saving the empty image field. serializer = self.get_serializer(data=request.data) I would like to add the PIL object to request.data and it looks like this: <QueryDict: {'url': ['https://s3.amazonaws.com/cat/encabezado.jpg'], 'image': ['MY PIL IMAGE'], 'entity': ['clasificado'], 'csrfmiddlewaretoken': ['JRMLIXkxqg6sF5YP19NLTvgFOmVWH9ARSmM']}> Thanks! -
Import Django does not work on virtualenv(ubuntu)
I am trying something like this source my_env/bin/activate Then I check if Django is installed python -c "import django; print(django.get_version())" 1.9.13 But import fails import django Only cross appears.How to fix Django import? -
Understanding the process sequence in Django's middleware
I'm quite new to Django, and have been assigned the task of building a web application that authenticates a user against LDAP, once authneticated the user can search for a person/group in the LDAP Server. In the last few weeks I've been stuggling with how to set this up and wrote a few posts already, but they didn't come up with anything. I realised, because I originally wanted to perform all the LDAP authentication tasks in my views.py, that this approach was not how Django intended. Instead, these kind of authentication functions are intended to be built as middleware, which has opened up a whole new can of worms for me. I realised in any case I was restricted in performing this whole task in view.py, because this prevented a user from switching to a new page and still remaining authenticated in LDAP (I found the parsing of the conn object a bit clumsy, see here). Anyway, after reading around and watching several informative videos, like here and here, I managed to get the first step of my middleware working. However, there are some processes occuring in Django that are at work, and I don't fully understand why. Let me … -
Unable to overload (override) DRF's save() method
I'm trying to override my serializer's save() method (as per the docs) to support bulk instance creation. At the moment, I have something that looks like this: serializers.py def validate(self, data): return super(WidgetSerializer, self).validate(self.business_logic(data)) def save(self): print("---------Calling save-----------") more_business_logic() instances = [] for widget in self.validated_data: instances.append(Widget(**self.validated_data)) Wiget.objects.bulk_create(instances) return instances viewset.py def partial_update(self, request): if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) print("---------Calling partial update----------") serializer.save() What happens: I get prints to stdout indicating validate() and partial_update() executed I don't get a print to stdout indicating that save() occurred I get new Wiget instances in the database, but their properties indicate that the more_business_logic() call in save() didn't occur. However, I do get printouts indicating that business_logic in validate() call occurred. I presume from this that I'm somehow still stuck with the super class's save()? How can I override this method? -
Redirecting non www to www DJANGO, HEROKU, GO DADDY
I am Hosting a Django website on Heroku. I bought the domain from Go Daddy When I try http://example.com the page doesn't show up I want it to redirect to https://www.exapmle.com Please help!! -
script doesn't work in django template
I tried to follow this tutorial but for some reason, the JS does nothing in my template. I copied each step in it, added is an anchor div with an id of “newItems” and included the infinite scroll script as asked. my template looks like this: <body> {% for i in "0123456789" %} {% for j in "0123456789" %} <li>{{i}} , {{j}}</li> {% endfor %} {% endfor %} <a id="newItems">in here</a> <script> $(document).ready(function(){ $(window).bind('scroll', loadOnScroll); }); // Scroll globals ... SAME AS IN THE TUTORIAL ... </script> </body> my view.py: def debate_archive(request): debates = range(1,1000) paginator = Paginator(debates, 10) if request.method == 'GET': if request.is_ajax(): if request.GET.get('page_number'): # Paginate based on the page number in the GET request page_number = request.GET.get('page_number'); try: page_objects = paginator.page(page_number).object_list except InvalidPage: return HttpResponseBadRequest(mimetype="json") # Serialize the paginated objects resp = serialize_debates(page_objects) return HttpResponse(json.dumps(resp), mimetype='json') debates = paginator.page(1).object_list return render(request, 'polls/example.html', locals()) my urls.py: url(r'^test/$', views.debate_archive, name='home'), Any ideas? -
Django admin error while deleting
I have a curious error : TypeError at /admin/wall/articles/ __str__ returned non-string (type Articles) I have a model Articles. I just try to delete some articles of my database from the admin panel of Django. I said it's curious because it happens only on some objects. I can remove most of articles but for an unknow reason, some entry in database return an error if I'm trying to delete them. I doesn't happens in my others models. This is a screenshot of phpmyadmin showing all entries in my table "Articles": For example, I have an entry with id 70. In the Django admin pannel I can't delete it, I have an error. For testing a recreate the exact entry (see on id 75) and I can delete this entry from django admin pannel. Why could I delete some contents but not all ? This is my model Articles : class Articles(models.Model): title = models.CharField(max_length=50, null=False, verbose_name="Titre") text = HTMLField() image = models.FileField(upload_to='media/articles/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Image de présentation") games = models.ForeignKey(Games, verbose_name="Jeux", blank=True, null=True) author = models.ForeignKey(User, verbose_name="Auteur") is_statut = models.BooleanField(default=True, verbose_name="Statut") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def __str__(self): return self.title This my … -
Django datatime field
I'm reading the PostgreSQL documentation and I see that Postgres does not have a datatime data type. When I run ./manage.py sqlmigrate myapp 0001_initial Django actually generates a datetime field: CREATE TABLE "myapp_event" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "start" datetime NOT NULL); So I'm a bit confused. Is datetime suppose to be timestamp? -
Using split in a django template
I have a dictionary passed to an html django template: return render_to_response('showdata.html', context_instance=RequestContext(request, {'dictdati': context} )) this dictionary has this structure: {0: 'TO;DEC;1;2012/02/28 15:39:06.000;TO;1234;SI;DI;1234;TO;1\n', 1: 'TO;DEC;1;2012/02/28 15:39:06.000;TO;567;SI;DI;567;TO;1\n'} and in an html template I need to print some of the values in the each row of the dict. If in a python file I use for key,val in dictdati.items(): print val.split(';')[0] it prints the first value correctly (TO) but in an html template {% for key,val in dictdati.items %} {{ val.split[0] }} {% endfor %} in the browser I receive the error: TemplateSyntaxError at /getdata/ Could not parse the remainder: '[0]' from 'val.split[0]' Can someone give me an idea to solve this problem? -
Postgres 8 support with Django 1.8
I am upgrading Django from 1.5 to 1.8. My production server is running postgres 8.4.20 but Django 1.8 says it dropped support for Postgres <= 9.0. If I go ahead and upgrade, is it likely to still work or will it fail in some spectacular way? If it's going to fail, I need to consider the implications of upgrading postgres before I carry on. -
Django - user profile :UNIQUE constraint failed: main_userprofile.user_id
I'm trying to build profile model for my existing user model . models.py class UserProfile(models.Model): first_name = models.CharField(max_length=12,null=True) last_name = models.CharField(max_length=12,null=True) avatar = models.ImageField(null=True,upload_to='media_file/avatar/') user = models.OneToOneField(User,on_delete=models.CASCADE, related_name='profile',unique=True) bio = models.TextField(max_length=500) birthday = models.DateTimeField( blank=True, null=True) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) def __str__(self): return self.user.username so i build forms.py to : class UserProfileForm(forms.ModelForm): birthday = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = UserProfile fields = "__all__" exclude =["user"] and i wrote my views.py like this : def profile_form_update(request): if request.method =="GET": form = UserProfileForm() return render(request,"profile_form.html",{"form":form}) if request.method == 'POST': instance = get_object_or_404(UserProfile, user=request.user) form =UserProfileForm (request.POST or None, request.FILES or None,) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() context = { "form":form, "instance": instance,} return render(request, "profile_form.html", context) first this is working ,when i make profile in django admin panel .and when I'm trying to load the existing form ,form renders with content that stored in database.when any changes to form that comes with an error: IntegrityError at /profile/update/ UNIQUE constraint failed: main_userprofile.user_id i know somehow my problem is with existing data stored in user models.and i did some google and someone said : You are telling UserProfiles that the … -
Custom Django management commands broken on Windows
I am currently working to upgrade from django 1.3 to 1.8. I have my app working on Ubuntu (Ubuntu 16.04) now however am having problems with the Windows version. When I run my custom management commands on Windows the following errors are generated: Traceback (most recent call last): File "D:\src\proj\grp\tests\test_list_members.py", line 29, in setUp call_command('syncgroups') File "D:\src\env\lib\site-packages\django\core\management\__init__.py", line 103, in call_command parser = command.create_parser('', name) File "D:\src\env\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "C:\Python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments I have managed to locate the source of the issue, it appears that the handling of __future__.unicode_literals is different on Windows than on Ubuntu. For example the following works on Ubuntu but not on Windows (the same TypeError error as above is seen) from __future__ import unicode_literals from optparse import OptionParser OptionParser().add_option('-v', '--verbose') Does this mean that Django 1.8 no longer supports custom management commands on Windows? Any workarounds would be greatly appreciated! -
Como crear usuario administrador django
Actualmente estoy tomando un proyecto que esta muy avanzado y adicionalmente soy nuevo en django . Quisiera Saber de que manera puedo añadir a un usuario como administrador desde view ,normalmente los desarrolladores de la web lo realizaban desde el shell de python motrare de que manera ellos los modelos y que tiene comunicación con los siguientes comandos desde el shell de python : De esta manera se carga desde el shell de python def load_examples(apps, schema_editor): Customer.objects.create_user('0', 'V', 'Buendia', 'Grupo', 'buendia@grupo.com', 'holijiji', '0212-0000000','0424-0000000', datetime.date(1985, 12, 24)) user = PlazasUser.objects.get(id=0) content_type = ContentType.objects.get_for_model(PlazasUser) permission = Permission.objects.create(codename='admin', name='Administrator', content_type=content_type) user.user_permissions.add(permission) user.is_active = True user.save() Models: class PlazasUser(AbstractBaseUser, PermissionsMixin): sap_id = models.CharField('Número de SAP', max_length=20) id = models.CharField('Identificador', max_length=10, primary_key=True, unique=True, null=False) id_type = models.CharField('Tipo de documento', max_length=1, choices=(('V', 'Venezolano'), ('E', 'Extranjero'), ('J', 'Jurídico'))) email = models.EmailField('Correo electrónico', max_length=255, unique=True) name = models.CharField('Nombre', max_length=30, null=False) last_name = models.CharField('Apellido', max_length=30, null=False) failed_login = models.SmallIntegerField('Intentos fallidos', default=0) needs_sap_modify = models.BooleanField(default=False) is_active = models.BooleanField('Está activo', default=False) want_mails = models.BooleanField('Desea reciibir correos de Automercados Plaza\'s', default=False) created_at = models.DateTimeField(default=timezone.now) Class Customer(models.Model): user = models.OneToOneField(PlazasUser, primary_key=True) phone_regex = RegexValidator(regex=r'^\d{4}-\d{7}$', message="El número telefónico debe tener el formato: '0212-1112233'") phone_number = models.CharField('Número telefónico', max_length=12, validators=[phone_regex]) mobile_number = models.CharField('Teléfono móvil', … -
How do I set an alias field in Tastypie resource
Say I have a Django model like this class Entry(models.Model): id = models.AutoField(primary_key=True) key = models.CharField(max_length=64, null=1) But in a tastypie api resource I want users to be able to filter by "key" field and an alias. So i suppose this should look somewhat like this. class EntryResource(ModelResource): entry_key_alias = <ALIAS FIELD?> to key class Meta: list_allowed_methods = ['get'] queryset = Entry.objects.all() resource_name = 'entries' I failed to find it in docs or stackoverflow.