Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dispaly form Validation Errors bug
I have a form clean fuction: def clean_items_price(self): items = self.cleaned_data.get('items') items_price = self.cleaned_data.get('items_price') if items: if items_price <= 0: raise forms.ValidationError(_("Put the price for items or unselect items")) else: return items_price elif not items and items_price > 0: raise forms.ValidationError(_("You don't select items to sell")) else: return items_price I recive next problems: Django don't show error to template. I try everything. {{ form.items_price.errors }} {{ form.errors }} but when in view i wrote next: if request.method == 'POST': form = ITemsEdit(request.POST, instance = item) if form.is_valid(): item.save() return go_to else: print(form.errors) i receiving next message to terminal: <ul class="errorlist"><li>items_price<ul class="errorlist"><li>Put the price for items or unselect items</li></ul></li></ul> -
User selects language on login page using form django
I have a login page with the following form: <form class="login-form" name="LoginForm" action="{% url 'login' %}" method="post"> {% csrf_token %} <p> <table> <tr> <td>{{ form.username.label_tag }} </td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> </p> <input class="button button-small" type="submit" value="Login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> <a>English</a> <a>French</a> and I have a forms.py that looks like this: from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'type': 'password', 'name': 'password', 'class': 'form-control'})) and urls.py that looks like this: from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from stellar.forms import LoginForm from stellar.views import index2 from django.conf.urls.i18n import i18n_patterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('example.urls')), url(r'^login/$', auth_views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name = 'login'), url(r'^logout/$', auth_views.logout, {'next_page': '/login'}), url(r'^i18n/', include('django.conf.urls.i18n')), ] Basically, if the user clicks on English or French the language of the page should change. How do I go about doing this? -
Access object being "currently filtered" in custom Django manager
I'm trying to create a custom manager for Django, and it would be very helpful if I could access the current instance (current row?) being filtered within the filter itself, but I have no idea if that's possible. So, I am trying to implement a coupon (discount) system in which some of the coupons can be used a maximum number of times (something along the lines of "Get a 10% discount on your first 3 buys") and I'd like to use my custom manager to get the coupons that a particular user can still utilize. Allow me to show it with an example. Let's say I have a situation like: ---------------------------------- Discount coupon ---------------------------------- id=1 max_times = 3 --------------------- usages = ManyToMany('UsagesRecord') =====> Usage Record (1) ---------------------------------- --------------------- id = 1 used_by_user=2 times_used=1 coupon_id=1 # related name to the coupon --------------------- Usage Record (2) --------------------- id = 2 used_by_user=5 times_used=3 coupon_id=1 # related name to the coupon ---------------------------------- Discount coupon ---------------------------------- id=2 max_times = 1 --------------------- usages = ManyToMany('UsagesRecord') =====> Usage Record (1) ---------------------------------- --------------------- id = 1 used_by_user=2 times_used=1 coupon_id=2 # related name to the coupon In my custom manager, I am trying to create a custom method get_for_user, … -
How to get all user in django template without using views.py?
I have an existing project that has no views.py and models.py.It has a user login system.I want to get the list of all user in the template.I have searched more but found no solution. -
Unable to start 2nd view function
Currently, im trying to make it so that I can complete a question on a page then when it's submitted to the database the next page will load. furthermore, every time I point it towards the templates folder it is piggybacking off the original one meaning that it can't find the new HTML page. My idea is that when question1 is completed it will link to question2 where the def question2 code will execute and so on. But the forms won't display correctly and I believe it is due to the def question2 not running correctly. def question1(request): question_form1 = QuestionForm1() if request.method == 'POST': form = QuestionForm1(request.POST) if form.is_valid(): form.save() # saves to database return HttpResponse('question2.html') else: return render(request, 'music/failed.html') return render(request, 'music/question1.html', locals()) def question2(request): question_form2 = QuestionForm2() if request.method == 'POST': form2 = QuestionForm2(request.POST) if form2.is_valid(): form2.save() # Saves to database return render(request, 'music/question3.html', locals()) else: return render(request, 'music/failed.html') return render(request, 'music/question2.html', locals() ) -
How can I run a Django management command asynchronously?
I have a Django management command that I'd like to issue in an asynchronous manner (via the call_command function). The flow of my code looks something like: User fills out a web form (or edits pre-existing values in a form). User clicks the submit button, and I do some processing. Once processing is done, I'd like to issue a management command without forcing the user to wait for it to return. If the management command fails for some reason, I'm not too concerned (my logs will catch those cases), so allowing the user to proceed on their merry way is fine by me. Is this kind of asynchronous call possible, and if so, how best can I do it? Is the threading library sufficient for this case? I'm aware of packages like Celery, but using something like that seems like tremendous overkill for something as simple as what I'm trying to do. -
Django REST Framework: How can I decode the url when a request coming to the server
I have built an API using Django REST framework. Some uuids consisted of slash ("/") e.g: "text/text". In my client-side (AngularJS web-app) I encode these uuids using encodeURIComponent function. So, the encoded version of uuid seems like: "text%2Ftext". An example of request could be like the following: https://domainName.com/api/record/text%2Fext Do you know how can I decode the url when a request (like the above example) coming to the server-side? -
Call two function inside a class based view - Django
I have a class connected to a template, inside it I have two functions, one is to authenticate the user (using credentials available in my db) and the second one is to actually get some data and push it to my template. However using print('whatever') I see that neither function gets called when I call the class. Why? views.py class GenerateReport(TemplateView): # This view is responsable to access users data and return it template_name = 'ga_app/report.html' def generate_report(request): # authenticate user c = CredentialsModel.objects.get(user_id = request.user.id) credentials = c.credentials http = httplib2.Http() http = credentials.authorize(http) service = build('analyticsreporting', 'v4', http=http) print('This first function is not called') def print_data(request): # Get some data profile_id = GoogleProperty.objects.get(user_id = request.user.id) return service.data().ga().get( ids='ga:' + profile_id, start_date='7daysAgo', end_date='today', metrics='ga:sessions').execute() print('This second function neither') return render(request, self.report, {'metrics': metrics}, {'profile_id': profile_id}) urls.py url(r'^re/$', GenerateReport.as_view(), name='re'), The shell obviously doesn't show anything printed out, and the template doesn't render metrics and/or profile_id -
Django-compressor Error on Heroku & Amazon S3 "UncompressableFileError"
So I know there are a few articles on this subject already, but I have tried every combination of settings to make django-compressor work, but with no success. Any ideas? settings.py STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATIC_URL = '/static/' DEFAULT_FILE_STORAGE = "mysite.s3utils.MediaS3BotoStorage" COMPRESS_ROOT = STATIC_ROOT STATICFILES_STORAGE = 'mysite.storage.CachedS3BotoStorage' COMPRESS_STORAGE = STATICFILES_STORAGE STATIC_URL = 'https://mysite.s3.amazonaws.com/' COMPRESS_URL = STATIC_URL s3utils.py from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage class StaticS3BotoStorage(S3BotoStorage): """ Storage for static files. """ def __init__(self, *args, **kwargs): kwargs['location'] = 'static' super().__init__(*args, **kwargs) class MediaS3BotoStorage(S3BotoStorage): """ Storage for uploaded media files. """ def __init__(self, *args, **kwargs): kwargs['location'] = 'media' super().__init__(*args, **kwargs) class CachedS3BotoStorage(S3BotoStorage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.local_storage = get_storage_class( "compressor.storage.CompressorFileStorage")() def save(self, name, content): self.local_storage._save(name, content, max_length=None) super().save(name, self.local_storage._open(name)) return name index.html {% load compress %} {% compress css %} <link href="{% static 'libs/twitter-bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> {% endcompress %} Error: compressor.exceptions.UncompressableFileError: 'https://mysite.s3.amazonaws.com:443/libs/twitter-bootstrap/css/bootstrap.min.css' isn't accessible via COMPRESS_URL ('https://mysite.s3.amazonaws.com/static/') and can't be compressed Setup: Django v1.10.6 Python v3.5 Django-compressor 2.1.1 -
Error when creating a new user from a template in django
I am creating a form so that users can register together with their data in a profile model, the problem is in the Category field which is ManyToMany and gives me error when saving. This is my form. class UserForm(UserCreationForm): negocio = forms.CharField(max_length=30) encargado = forms.CharField(max_length=30) imagen = forms.ImageField() direccion = forms.CharField(max_length=30) telefono = forms.DecimalField(max_digits=15, decimal_places=0) email = forms.EmailField() categoria = forms.ModelMultipleChoiceField(queryset=Categoria.objects.all()) lat = forms.CharField(max_length=30) lng = forms.CharField(max_length=30) These are my models. class Perfil(models.Model):#Este es el perfil del usuario(solo existe uno por cada usuario) user = models.OneToOneField(User, related_name='profile') nombre_negocio = models.CharField(max_length=50, unique=True) encargado = models.CharField(max_length=50,null=True,blank=True) imagen = models.ImageField(upload_to = 'perfiles',null=True,blank=True) direccion = models.CharField(max_length=100) telefono = models.DecimalField(max_digits=15, decimal_places=0,null=True,blank=True) email = models.EmailField() category = models.ManyToManyField(Categoria) inicio = models.DateTimeField(null=True,blank=True) final = models.DateTimeField(null=True,blank=True) lat = models.CharField(max_length=50,null=True,blank=True) lng = models.CharField(max_length=50,null=True,blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.nombre_negocio) super(Perfil, self).save(*args, **kwargs) def __unicode__(self): return self.nombre_negocio class Categoria(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(editable=False) imagen = fields.ImageField(upload_to = 'categorias',null=True,blank=True,dependencies=[ FileDependency(processor=ImageProcessor( format='JPEG', scale={'max_width': 200, 'max_height': 150})) ]) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Categoria, self).save(*args, **kwargs) def __unicode__(self): return self.name This is my view. class RegistrarUsuario(FormView): form_class = UserForm template_name = 'home/registrar.html' success_url = '/registrar' def form_valid(self,form): user = form.save() email … -
Custom Django Template Tags not being loaded into Templates
I have been searching the internet for quite some time for this one, but have not been able to fix my issue. I am trying to concatenate strings in one of my Django templates, and initially was using add as such... {% with "http://127.0.0.1:8000/post/"|add:p.post_id|add:"/" as post_link %} ... used here ... {% endwith %} ... but found that to be buggy and bad form. So I tried to create a custom template tag that would concatenate strings with the name addstr... {% with "http://127.0.0.1:8000/post/"|addstr:p.post_id|addstr:"/" as post_link %} ... used here ... {% endwith %} ... but am getting an "Error during Template Rendering, Invalid filter: 'addstr'" error when I do. I created a templatetags directory in the correct spot with an init.py and cloud_extras.py inside of it. The contents of cloud_extras.py are: from django import template register = template.Library() @register.filter def addstr(arg1, arg2): """concatenate arg1 & arg2""" return str(arg1) + str(arg2) I also have the app properly installed in settings.py and am loading the template in the view correctly (I know this is true because I have been working with this for a while now and decided to create links for the titles of posts) Thank you so much for … -
Make unavailable to choose some values of CHOICES in admin and custom form
In my model I have next fields: class Project(models.Model): members = models.ManyToManyField(User, through='Membership') ***Other fields here*** class Membership (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ROLE_CHOICES = ( ('manager', 'Manager'), ('developer', 'Developer'), ('business_analyst', 'Business analyst'), ('system_analysts', 'System analysts'), ) role = models.CharField(max_length=20, choices=ROLE_CHOICES,) I have 2 question. 1) How in admin page make some values of 'ROLE_CHOICES' in 'role' field unavailable. For example admin can can choose only manager or developer. 2) How to make the same behavior in the form? In custom form make available to select only a few values of 'role' field. Lets say 'developer' and 'business_analyst'? I would be grateful for any help! -
Django not sending email through gmail
I am trying to build a online book store and I am trying to send an verification email to new signed users, but for some reason Email is not getting sent, I also tried to use app specific password in gmail. A help will be greatly appreciated. Here is my Email code in Settings Email EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER='kshitu.rangari@gmail.com' EMAIL_HOST_PASSWORD='jgpcjiajvklxraof' EMAIL_PORT=587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'books@pickabook.com' Code in my Views.py from .models import Book def index (request): return render (request,'template.html') def store (request): return render (request, 'store.html' ) def store (request): count = Book.objects.all().count() context = { 'count':count, } return render (request,'store.html',context) -
How to setup a virtual environment for Python 3.6
I am trying to develop a website with the following: Front End: Angular 2 along with BootStrap Back End: Django REST framework Database: SQL I am connecting Front End and Back End using AJAX with JSON language. I need to create a virtual environment to run Django with Python 3.6. Can anyone guide me how to execute it. I hear it is different from earlier versions. -
Python: Caching a 251mb hash in memory
I am building a webapp using django and I deal with large excel files (about a million rows) that I parse into a hash for faster calculations and manipulations. I want to cache the hash, but the hash is 251mb in size and I don't think memcache allows you to cache such large variables. Does anyone have any suggestions as to how I should deal with this? I'm open to ways other than caching, too. -
Django with Bootstrap 4 how do I make images display as a square?
I've been playing around with bootstrap 4 lately to create a project and after a lot of trying I can't make uploaded images of different sizes display as a square when I display them. Remember how Instagram only displayed square images for thumbnails? I want to achieve that. I have done some research and tried a bunch of things written down by other people but the only thing that came close enough to that was this one: http://stackoverflow.com/a/23518465/1067213 but the result is not what I actually want it to do: As you can see the images are not square and there is a gap underneath the first one so that it aligns with the other two columns (I do want all columns to be the same width and height). I use Django to create the URLs to the image files. Here is my html: <div class="row"> {% if competition_list %} {% for competition in competition_list %} <div class="col-md-4"> <div class="card"> <div class="image"> <img class="card-image-top img-fluid" src="/{{competition.image.url}}" > </div> <div class="card-block"> <h4 class="card-title">{{competition.name}}</h4> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p><a class="btn btn-secondary" href="https://v4-alpha.getbootstrap.com/examples/jumbotron/#" … -
How Do I Represent Student-Lecturer Relationship in Django?
So I'm trying to make a web app that is meant to aid interaction between students and teachers. However, I need to know how to structure the model of relationships in Django. Here are 2 things you should know: A teacher can have many students (users) under him or her. A student can only have one user as his teacher. In other words, teachers are meant to have as many students as possible, while each student can only have one teacher. How should I represent this in Django? And what's the best way to manage this relationship? For the latter question, I'm thinking about creating a class that looks like this: class Relationship(models.Model): ##student and lecturer models shall inherit the User class; hence, the student = models.ForeignKey(User, related_name = 'lecturer_set') lecturer = models.ForeignKey(User, related_name = 'student_set') class Meta: unique_together = ('student', 'lecturer') PS: I know the above class might be wrong. Just trying to explain what I need to implement in the Relationship class. -
Erlang vs Python(Django framework) for real time chat application
I want to develop real time chat application like whatsapp. After some research, i found that whatsapp uses erlang functional language. I never worked on erlang. I am proficient in Python and i thinking of designing backend services in Django. Is there any way by which i can make real time chat application in Python which has features like erlang real time chat application posses(i.e. concurrency, scalability etc). -
Is it possible to add your own strings to a Django SearchVectorField?
I know how to do this with raw PostgreSQL commands, but want to know if there is a way to do this with Django PostgreSQL search. class Person(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=256) active = models.BooleanField(default=False) search_vector = SearchVectorField(blank=True) def update_search(person): vector = SearchVector('name') + SearchVector('description') if person.active: vector = vector + SearchVector('alive') person.search_vector=vector django.core.exceptions.FieldError: Cannot resolve keyword 'alive' into field. I tried making 'alive' a @property method, but it looks like it only wants a db field for search. Is there a way to do this in pure Django or should I go the raw SQL route? -
Onmouseover does not work with Django - Python
I copied html to django, like everything was set up, there are pictures, etc. But here with onmouseover the problem - does not work. Tried it - onmouseover="this.src={% static 'res/ico/instagram_h.png'%}" onmouseover="this.src="{% static 'res/ico/instagram_h.png'%}" onmouseover= "{% static 'res/ico/instagram_h.png'%}" And many more options, but the picture does not change, although if you just upload the html file to the browser, it all works. -
Django: aggregate on option display value
In a Django view, I am attempting to return Sum values for a model. The field I am aggregating on is one whose values are defined by an options tuple. The result I get back is a QuerySet where the elements are dicts that show the coded value from the relevant field, not the display values from the options tuple. Is there any way to get the display values in this dict? MODEL: REG_STATUS_OPTIONS=(('V1', 'value 1'), ('V2', 'value 2')) class RegDetails(models.Model): ... registration_status = models.CharField(max_length=2, choices=REG_STATUS_OPTIONS, default='V1') VIEW: def view(request...): ... totals = RegDetails.objects.all().annotate(total=Count('registration_status)) This returns something like this: <QuerySet [{'registration_status': 'V1', 'total': 3}, {'registration_status': 'V2', 'total': 1}]> Is there any way to get this to include "Value 1" in the dicts rather than 'V1'? I figure this must involve get_registration_status_display() but I can't figure out how to do this. Thank you -
How can I access a column in Django (nested queries)?
how can I access the profil.name from all_shared_profiles in the template? Maybe I have to use Chaining filters? Can you please give me an example? models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, on_delete=models.PROTECT) class ProfileShared(models.Model): profile = models.ForeignKey(Profile, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) view.py: def profiles(request): current_user = request.user all_own_profiles = Profile.objects.filter(owner=current_user) all_shared_profiles = ProfileShared.objects.filter(user=current_user) context = {'all_own_profiles': all_own_profiles, 'all_shared_profiles': all_shared_profiles} return render(request, 'library/profiles.html', context) template: {% for profil in all_own_profiles %} {{ profil.name }} {% endfor %} {% for profil in all_shared_profiles %} {{ profil.name }} {% endfor %} -
Django's strong reference or am I misunderstanding django's OOP
Note: long post, food for the fanatics :) Django 1.10 python 2.7 I think I am running into some strong reference issues with Django. Well, at least I think that is the issue here. I haven't yet done much with Django's OOP without the class based views. I've worked with the Java's OOP quite a while, where you can redefine an attribute, and the old reference is dropped, and not picked up the variables old reference that easily after redefining the attribute. Ill try to be as explicit as possible, since it might not have anything to do with strong referencing, but maybe just a dumb mistake. And also you can read what the code (as far as published) does, and what I think the code does. I'm working on an agenda, containing a multi-dimensional list of CalendarDay objects: calendar[month 1-12][days 1-31] = CalendarDay(year, month, day, **kwargs) This CalendarDay object has some attributes like is_weekend, is_non_existing_day, absence_days, etc, etc. From the database, I'm fetching the coworker's AbsenceRequests. Those requests are split into single days, and placed into the correct CalendarDay.absence_days list. So every CalendarDay can contain multiple AbsenceDay objects. Some of the classes have grown quite a bit since I've … -
Newbie Django Issue
I'm getting this error: NoReverseMatch at /genomics/ Reverse for 'pipelinedetail' with arguments '('02152ad7-8399-441c-ba8f-f8871460cd5f',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] When I navigate to this URL: http://127.0.0.1:8000/genoa/ My genoa_urls.py has: urlpatterns = [ # ex: /polls/samples url(r'^$', views.samples, name='samples'), url(r'^(?P<sequence_id>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/pipelinedetail/$', views.pipelinedetail, name='pipelinedetail'), ] The offending line in my template is: <td><a href="{% url 'polls:pipelinedetail' me.sequence_id %}">JSON</a></td> And my view contains: def pipelinedetail(request, sequence_id): # sequence_id = '7e6bd861-934f-44be-872a-b59826107bda' sample = get_object_or_404(Sample, pk=sequence_id) sample_details = sample.values('pipeline_detail', 'r1_fastqc_data', 'r2_fastqc_data', 'flagstatqc_metrics', 'mlstqc_metrics', 'variantqc_metrics') context = {'sample_details': sample_details} return render(request, 'polls/pipelinedetail.html', context) Here's the top level urls.py: urlpatterns = [ # polls in the url maps to polls.urls.py url(r'^polls/', include('polls.urls')), url(r'^genoa/', include('polls.genoa_urls')), url(r'^admin/', admin.site.urls), ] What am I doing wrong? -
Django Forms displays incorrectly
Currently trying to create a questionnaire in Django, i have a forms.py like so and is causing issues in terms of how it displays from django import forms from django.contrib.auth.models import User from .models import Question, Question1_CHOICES,Question2_CHOICES class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] class QuestionForm1(forms.ModelForm): Q1 = forms.MultipleChoiceField( required=False, widget=forms.RadioSelect, choices=Question1_CHOICES ) class Meta: model = Question fields = ['question1', 'question2',] widgets = { 'question': forms.RadioSelect() } class QuestionForm2(forms.ModelForm): Q2 = forms.MultipleChoiceField( required=False, widget=forms.RadioSelect, choices=Question2_CHOICES ) With this code I get a display problem like this , im not sure how to correct it and i feel the problem lies withing my forms.py file. But my choices are inside my models.py which i can send if needed. The questions should be on separate pages and both HTML documents link to there required QuestionForm to make that display the questions but, on page one im seeing both Q1 & Q2 and im not sure why