Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Rest-Framework and Angular-JS
I got this error while running var myApp = angular.module('imageuploadFrontendApp',['ngResource']); myApp.config(function($resourceProvider){ $resourceProvider.defaults.stripTrailingSlashes = false; }); myApp.controller('MainCtrl', function($scope, Images) { console.log('In main control'); $scope.images = Images.query(); }); getting an error like this Error: [$injector:unpr] Unknown provider: ImagesProvider <- Images <- MainCtrl -
django - get field via verbose name
suppose I have this field in Foo model field1 = CharField(max_length=10, verbose_name='Bar') Is there a way to return field1 via its verbose_name? Here is my visualization for it but it throws a TypeError Foo._meta.get_field(verbose_name='Bar') -
Django, best way to render italics in html for empty text field
I have a field called notes in a model. If the field is empty, I want to output 'No notes' and I want to do it in italics. You can set the text to be 'No Notes' by using a get command in the models.py def get_notes(self): if len(self.notes) == 0: return "No notes" return self.notes How do you have the html render as italics for the text 'No notes'. Html: Your Notes: {{ object.get_notes }} -
Django 2.0, can't fix searchbar working in django 2.0
I have a problem with my searchbar in django. I create a simple view: class BookList(ListView): model = Book def book_list(request): books = Book.objects.all() search_term = '' if 'search' in request.GET: search_term = request.GET['search'] books = books.filter(text__incontains=search_term) context = {'books': books, 'search_term': search_term} return render(request, 'book_list.html', context) And simple form: <form class="form-inline my-2 my-lg-1"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" value="{{ search_term }}" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">search</button> When i try to search something in my search bar it was isn't working. I'm newbie in Django and i don't know how to fix it. Did you, Guys know how to fix it? Thanks for Your'e reply. -
function or class from url
I use django as a backend. I have big project and there are many views(ViewSets from django-rest-framework, views and functions). And I use React as a front and and how can I get function or class which will be called from the url. For example I have the url: api/v2/users/322/send_letters/1232/ from this url I want to know which class or function will be called. -
GeoDjango + PostGIS: pure geometry SRID
I am thinking about using django (2.0.6) with Postgres/postGIS as a backend (10/2.4?). However, the model geometries I intend to use will not be stored "against" a spheroid (whether earth mars, etc) or any other kind of SRID. Rather a 100% pure geometry in 3D cartesian coordinates, where 1 unit = 1 meter. How am I to declare model fields and insure they are pure geometry both: at database level at application level Would this work? geometry = models.MultiPolygonField(_('Geometry'), spatial_index=True, dim=3) Or better to set the SRID?: geometry = models.MultiPolygonField(_('Geometry'), spatial_index=True, dim=3, srid=0) Many thanks -
post_delete is not called
Django 1.11.7 Python 3.6.5 I tried to implement following code to delete a file when a model is deleted. But post_delete is not called. @receiver(post_delete, sender=HogeFileModel, dispatch_uid=uuid.uuid4()) @receiver(post_delete, sender=FugaFileModel, dispatch_uid=uuid.uuid4()) def auto_delete_file_on_delete_part_file(sender, instance, using, **kwargs): print('Called post_delete') if instance.file: if os.path.isfile(instance.file.path): os.remove(instance.file.path) How to fix it? -
Django unique_together on DateRangeField
My model is like this: class B(Model): parent = ForeignKey(A) duration = DateRangeField() title = CharField(max_length=200) class Meta: unique_together = ('master', 'duration') The above unique_together, just checks for equality in case of duration. How can I implement unique_together, so that overlapping duration doesn't get inserted into the table for Model B? -
Can a field be disabled in View.py of Django project?
def resume_edit(request, r_id): r = Resume.get.object(pk=r_id) resume = ResumeModelForm(instance=r) resume.fields['email'].widget.attrs['readonly'] = True return render(request, 'resumes/resume.html', context) I tried to do this but its not working, i know how to do it in Forms.py , but i want to know in views its possible or not? -
cant migrate mysql to django
I'm trying to migrate mysqldb to Django and it's giving me this error. I am using Python 3.6 and Django 2.0.5. I've installed and set up mysql, as well as created the database, I just want to migrate it now. I'm new to Django so I'm not sure where I'm going wrong. I thought it might have something to do with me using python 3.6. Anyway any help or advice would be appreciated at this point. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/sam/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/sam/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/home/sam/anaconda3/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/sam/anaconda3/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/sam/anaconda3/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/sam/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mysite' Here is settings.py, if that helps. # Application definition … -
make view accessible to only specific users (i.e. who created that model) in django rest
I have one model which has user as its ForeignKey attribute which is auto fill ie. logged in user is filled there. I have made token authentication. Only Authenticated // i mean authorized users can visit that view. But i am planning to make such that only the user which had created that model object can only update the content of that object. For example: class Something(models.Model): sth_name = models.CharField(max_length=18) sth_qty = models.IntegerField() user = models.ForeignKey(User) on my View: I override perform_create() to associate to above model automaticall. def perform_create(self, serializer): return serializer.save(user=self.request.user) What do i exactly need to do? I have to write some permissions method, But I am really stuck. -
UserProfile db showing (None) in django
I was dealing with user authentication in django and created a UserProfile model with foreign key to User in-built model. Then I created explicitly defined User model and then deleted it to restore the original code. But now in my UserProfile database accessed from admin page is showing (None) for all the profiles created earlier. 1 And when I click on it it shows an error. 2 How do I delete that (None)? -
Django jquery get forloop.counter
I am working on a calendar where some dates are full and others are open. All dates are dislayed with buttons but the Open-Date-Buttons open a form to create a new event on that date whereas the Full-Date-Buttons dont do anything. To open the form i am using a modal (the code for that is pretty mach copy pasted from bootstrap). I am using a for loop in the template to create all the buttons. Whenever a Open-Date-Button is clicked i need to pass the forloop.counter to my function. I already managed to pass other variables with jquery like this: var test = '{{empty}}' But i fail to pass the forloop.counter My html looks like this: {% for days, active in zip %} {% if active %} <button type="button" class="daybutton daybutton1" data-toggle="modal" data-target="#myModal{{forloop.counter}}">{{forloop.counter}}</button><!-- Modal --> <div class="modal fade" id="myModal{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel{{forloop.counter}}"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Wählen Sie eine Uhrzeit für Ihren Termin am</h4><h5 id="count">{{ forloop.counter }}</h5><h6> {{month}} {{year}}</h6> </div> <div class="modal-body"> {{forloop.counter}} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Schließen</button> <button id="submit_btn{{forloop.counter}}" class="btn btn-link">Send the invitation</button> </div> </div> </div> </div> <script type="text/javascript"> $(document).on("click", "#submit_btn{{forloop.counter}}", function(event){ count = $("#count").html() alert( count ); }); </script> {% … -
class issue is not working
I am following a tutorial and trying to make a website sort of like stack overflow that allows people to post their issues. But for right now, nothing shows on my html page. I suppose something wrong with my HTML page or maybe models.py. But I could not figure it out why. Anyone could help ? models.py class Issue(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) project = models.ForeignKey(Project,on_delete=models.PROTECT) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique=True) content = models.TextField() author = models.ForeignKey(User,on_delete=models.PROTECT) published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now = True) status = models.CharField(max_length=9,choices= STATUS_CHOICES,default='draft') def save(self,*args,**kwargs): self.slug = slugify(self.title) super(Issue,self).save(*args,**kwargs) def get_absolute_url(self): return reverse('blog:issue_detail',args=[self.slug]) def __str__(self): return self.title view.py def list_of_issue(request): issue = Issue.objects.filter(status='published') paginator = Paginator(issue,10) page = request.GET.get('page') try: issues = paginator.page(page) except PageNotAnInteger: issues = paginator.page(1) except EmptyPage: issues = paginator.page(paginator.num_pages) template = 'blog/issue/list_of_issue.html' return render(request,template,{'issues':issues,'page':page}) list_of_issue.html {% extends 'blog/issue/base.html' %} {% block description %}This is the description{% endblock %} {% block title %}List of blog Issue{% endblock %} {% block content %} <div class="row"> <div class="col-md-8"> <div class="page-header"><h1>Our lastest issues</h1></div> <button class="btn btn-default"><a href="{% url 'blog:new_issue'%}">New issues</a></button> {% for Issue in Issues %} <h2><a href="{{Issue.get_absolute_url}}">{{ Issue.title }}</a></h2> <small>Written by {{ Issue.author }} on {{ Issue.published}} … -
Django celery not finding celery module
I'm trying to set up celery with Django from the tuts but I keep getting ModuleNotFoundError: No module named 'celery' I have a main project called Tasklist with the structure: - Tasklist/ - manage.py - Tasklist/ - __init__.py - settings.py - celery.py - urls.py My init.py is as follows: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] And my celery.py is like so: from __future__ import absolute_import, unicode_literals import os from celery import Celery app = Celery('') @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I'm not sure if I need to alter the settings.py - but I'm running in a local environment so I shouldn't need to start a celery worker? I'm pretty confused! I read that django-celery is redundant now the latest version of celery is here, so I only have celery 4.1.1 installed. -
Django Select user and dynamic render
in django display users i can select to create Threat. automatically does that in admin control so, how to handle that in my template, and view, to let me select who user i want. i need also add more feature,to add for loop for each user in the link <a></a> may be the link be written in the form post i guess I want to render the page with dynamically Threat's id in the URL -
getting the errors mentiones below:
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: : (admin.E108) The value of 'list_display[0]' refers to 'question_text', which is not a callable, an attribute of 'QuestionAdmin', or an attribute or method on 'polls.Question'. : (admin.E108) The value of 'list_display[1]' refers to 'pub_date', which is not a callable, an attribute of 'QuestionAdmin', or an attribute or method on 'polls.Question'. : (admin.E116) The value of 'list_filter[0]' refers to 'pub_date', which does not refer to a Field. model.py file: import datetime from django.db import models from django.utils import timezone class Question(models.Model): #... def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'published recently?' class Choice(models.Model): #... def __str__(self): return self.choice_text question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) admin.py file: from django.contrib import admin from . models import Choice, Question class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information',{'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] admin.site.register(Question, QuestionAdmin) -
Modifying template according to date with django
I'm wanting to modify the options on a template according to the date. The code I'm suspecting will look something like this: {% for campaign in filter.qs %} {% if campaign.event_date__gte=datetime.today() %} <code> {% endif %} {% endfor %} I believe my issue is that I'm trying to write it like a view - I'm just not too sure how to edit this within the template and not the views.py -
How to initialize Meta class 'model' variable in Django?
This may be a Django or a general python question. I have a ModelForm. Based on a user input I need to make use of one model or the other. For example, if the input is 'M', I need to associate he form with MaleTable otherwise with FemaleTable. I can create 2 ModelForms class DemographicM (ModelForm): class Meta: model = MaleTable class DemographicF (ModelForm): class Meta: model = FemaleTable but, I would like to use just one ModelForm and initialize it with the right model based on input. I understand that Meta is just an inner class. How can I initialize the 'model' variable at the time of the form creation? -
Django call function based on multiple events
In the Application, I need to call a function if there are any changes to few selected fields in five of the Models and few APIs gets called. What is the best approach to do this? I have considered doing it via signals but really appreciate best possible approaches and suggestions. Also, the function that needs to be called is fairly complex and if I'm converting it to background task, how can I make sure only latest call gets executed? -
python manage.py collectstatic is not coying static files from app folder
I'm doing the course , and at class 10 we learn to use python manage.py collectstatic . The problem is that it is just collecting the admin assets (not the assets from the app that I'm developing). Does anyone know why this is happenning? -
Django not sending emails to valid address
I need Django to send a confirmation email, but it keeps telling me my email is not a valid address - is there something wrong with my code? Error: SMTPRecipientsRefused at /accounts/signup {'=?utf-8?q?email?=': (553, b'5.1.2 The recipient address <=?utf-8?q?email?=> is not a valid RFC-5321\n5.1.2 address. h7-v6sm4740542wmc.44 - gsmtp')} Views.py function: def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error':'Username has already been taken'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], password=request.POST['password1'], email=request.POST['email']) email = user.email auth.login(request, user) msg = EmailMessage('Request Callback', 'Here is the message.', to=['email']) msg.send() return redirect('home') else: #<---- I think you need this one too return render(request, 'accounts/signup.html', {'error':"Passwords didn't match"}) else: #if it's a GET return render(request, 'accounts/signup.html') -
Django Ajax - POST request succeeds, data not saved on DB
I'm using a bootstrap modal to allow firefighter to update their status in an app I'm working on. The modal has buttons that make a POST request when clicked. csrf tokens are disabled for testing purposes models.py class Firefighter(models.Model): STATUS_OPTIONS = ( ('AV', 'Available'), ('OD', 'On Duty'), ('UN', 'Unavailable'), ('LV', 'Leave'), ) first_name = models.CharField("First Name", max_length = 200) last_name = models.CharField("Last Name", max_length = 200) status = models.CharField("Status", max_length = 20 , choices=STATUS_OPTIONS, default='Available') views.py def updateStatus(request, id): from django.http import JsonResponse if request.method=='POST' and request.is_ajax(): try: obj = Firefighter.objects.get(id=id) obj.data_attr = request.POST['status'] obj.save() return JsonResponse({'status':'Record Saved'}) except Firefighter.DoesNotExist: return JsonResponse({'status':'Record does not exist'}) else: return JsonResponse({'status':'Invalid POST request'}) Returns the Record Saved JSON response when run. urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^status/$', views.status, name='status'), url(r'^status/update/(?P<id>\d+)/$', views.updateStatus, name='update'), button jQuery $('#btnAvailable').on('click', function() { // You gotta include the csrf_token in your post data $.post(`/status/update/${clickedID}/`, {'status': 'AV'}, function() { $('#change-status').modal('hide'); location.reload(true) }); }); Everything runs as it should, chrome shows no console errors for the POST request and yet the status does not save on the DB. For example /status/update/22/ has their status currently set to UN (Unavailable) the post request should set their status to AV (Available) … -
Django allow spaces in username within UserChangeForm
Bit of a frustrating issue, there's a few similar questions but I can't seem to get any of the answers to work for me. First of all: signup/login on my site is done exclusively through django-allauth. It has a setting ACCOUNT_USERNAME_VALIDATORS and this works fine for creating users - I just had to define a validator with this regex r'^[\w\.@+\- ]+$' and point the setting to it. The issue is if I try to edit an existing user in the admin (for example to give them permissions), I get an error on save that the username field is invalid because of spaces. I've tried a couple of things like this method from the django docs: from django.contrib.auth.models import User from django.contrib.auth.validators import UnicodeUsernameValidator class MyValidator(UnicodeUsernameValidator): regex = r'^[\w\.@+\- ]+$' class MyUser(User): username_validator = MyValidator() class Meta: proxy = True And I've also tried overriding the UserChangeForm in my admin.py: class MyUserChangeForm(UserChangeForm): username = forms.RegexField( label='Username', max_length=30, regex=r'^[\w\.@+\- ]+$', help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).') class CustomUserAdmin(UserAdmin): form = MyUserChangeForm admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) But no luck with either. I can't help but feel I'm missing something silly, from other answers it seems … -
NameError at / global name 'Httpresponse' is not defined
I have Django installed on my virtual system which has python 2.7 inbuilt to it. I am new to Django , I followed the steps from documentation and have added details in views.py from django.http import HttpResponse but I still get the following error: should I have the Http Response package in my environment or this is a issue because of Python lower environment? Please help enter image description here