Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically load up Django models in Shell Plus in another Directory
My Django project directory is as such main - models/ - some_model/ - some_other_model/ - .ipython - notebook1.ipynb - manage.py - notebooks/ - notebook2.ipynb When I open my notebook1.ipynb using python manage.py shell_plus --notebook all my models are imported automatically, however this isn't the case in notebook2.ipynb. In that notebook I cannot import the models because it's opened in another directory. When I change the working directory, I get an error AppRegistryNotReady: Apps aren't loaded yet. How do I make it so that my notebook2.ipynb is able to use the same models are notebook1.ipynb? The reason for this is I'm trying to mount a persistent volume in the notebook/ directory in Kubernetes, since mounting a persistent volume in the main directory has caused some errors (unless there was a way to make certain file extensions be persistent) -
Global Variable in Python cross module
I have two Python modules: one.py; and two.py I want to change X global variable in two.py. two.py running, assist one.py one.py import two def main(): two.function("20") if __name__=="__main__": main() two.py #!/usr/bin/env python X="10" def main(): while True: function() time.sleep(0.25) def function(input="00"): if(input!="00"): global X X=input print "change" print X console: one.py running sudo python two.py 10 10 10 10 -
Django - modifying custom querysets when querying on related models
Django doc says that Manager’s aren’t used when querying on related models. For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions. Does it mean Django does not provide any tool for keeping code DRY for corresponding cases, and we have to explicitly write filters of type Choice.objects.filter(question__name__startswith='What') ? My use case is the standard scenario when some of my tables have is_deleted field, and want to come up with a DRY method to unconditionally exclude deleted records from all querysets. -
Django generate csv file on view and download
I have this code: with open('stockitems_misuper.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerows(file_rows) response = HttpResponse(myfile, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv' return response I get the error: I/O operation on closed file How can I send the created csv file to the front end? -
How to display link in Django template
in views.py I have: def article(request, article_id, slug): post = get_object_or_404(Article, pk=article_id) return render(request, 'article.html', {'article': post}) in the template article.html there is: {{ article.content }} The problem is that the content field of the article contains some html tags. Let's say, the content is: <a href="http://stackoverflow.com/">my website</a> But is displayed exactly like that. I want to be a link on "my website" and to point to http://stackoverflow.com/. -
how to use custom filter within inclusion tag - django
I want to use a custom filter inside an inclusion tag in django 1.10, but whenever I try I get an error Invalid filter:'my_filter' The filter allows me to access a dictionary by a key and returns a value. The filter and inclusion tag work fine by themselves. Can anybody help? -
Running multiple independent and interactive tasks from django-celery
I'm working on a django project which manages several short-lived sandboxes through a web-api and i am currently unsure if celery would be the correct choice for what i am trying to achieve. I have multiple linux images across different architectures prepared, which i need to run on demand. I want to be able to process requests like GET /sandbox/run/uclinux/armeb HTTP/1.1 which picks the appropriate image, runs qemu and returns a unique identifier which can then be used to perform further actions with this specific qemu-instance/sandbox (e.g. interacting with serial console). These sandboxes will typically be quiet short-lived and deleted after processing of user-requested actions. Individual Sandboxes wont be running any longer than 30 minutes. I have worked with django-celery in the past (short tasks, typical queuing of async tasks) and thought that it would be fitting to handle sandbox execution independently from the webapi, but i am not sure if and how i can fulfill the following requirements: It must be possible to run and interact with multiple sandboxes at the same time The code which runs and interacts with qemu must be able to provide live updates to the django database. A user should be able to do … -
Django error on invalid form submit (VariableDoesNotExist)
I have a form that works fine with valid data but gives me a strange error with invalid data. I can't figure out what's causing it. the error: Request Method: POST Request URL: http://127.0.0.1:8000/nyt_hus/5/feedback/ Django Version: 1.9.11 Exception Type: VariableDoesNotExist Exception Value: Failed lookup for key [nythus] in "[{'False': False, 'None': None, 'True': True}, {}, {}, {'view': <app.views.FeedbackView object at 0x000001EBD8440550>, 'form': <ErrorForm bound=True, valid=False, fields=(content)>}]" template: <form role="form" action="{% url 'feedback' pk=nythus.id %}" method="post"> {% csrf_token %} {{ form.content }} <button type="submit">Send</button> </form> forms.py: class ErrorForm(forms.Form): content = forms.CharField( required=True, widget=forms.Textarea ) def __init__(self, *args, **kwargs): super(ErrorForm, self).__init__(*args, **kwargs) self.fields['content'].label = "Beskriv fejl" self.helper = FormHelper() urls.py: url(r'^nyt_hus/(?P<pk>\d+)/$', views.NytHusDetail.as_view(), name='nyt_hus_detail'), url(r'^nyt_hus/(?P<pk>\d+)/feedback/$', views.FeedbackView.as_view(), name='feedback'), views.py: class NytHusDetail(DetailView, FormMixin): model = NytHus template_name = "app/nyt_hus_detail.html" form_class = ErrorForm class FeedbackView(FormView): form_class = ErrorForm template_name = 'app/nyt_hus_detail.html' def get_success_url(self, **kwargs): return reverse_lazy('nyt_hus_detail', kwargs={'pk': self.kwargs['pk']}) def form_valid(self, form, **kwargs): form_content = form.cleaned_data['content'] template = get_template('error_template.txt') context = Context({ 'form_content': form_content }) content = template.render(context) email = EmailMessage( 'mail', content, 'from@email.com' + '', ['to@email.com'] ) email.send() return super(FeedbackView, self).form_valid(form, **kwargs) I'm using Django 1.9 and Python 3.5. -
django-websocket-redis redis connection using unix socket
I'm using django-websocket-redis and have this in my settings.py: WS4REDIS_CONNECTION = { 'host': 'unix://var/run/redis/redis.sock', 'db': 0, # 'port': 16379, # 'password': 'verysecret', } I tried all possible combinations of 'host' parameter and can't get it to connect using unix socket instead of tcp. I always get this message: ConnectionError: Error -2 connecting to /var/run/redis/redis.sock:6379. Name or service not known. Is there a way to connect ws4redis from django to redis using unix socket? If there is, how? -
Django Rest Framework Viewsets - Adapter/Service Layer Pattern
I've decided to take the plunge and code a new Django project using the Service Layer / Adapter pattern (Might be known as the Interface pattern in PHP) from the very beginning. It's actually working pretty well for base Django. However, I can't wrap my head around how to overcome this hurdle inside Django Rest Framework. I'll ask the question and then layout the code below. Question: How do I stay true to separating my data access layer and my business logic (inside the services layer) while using Django Rest Framework's viewsets and satisfying its needs for the queryset attribute to be an instance of 'Queryset'. Code Contract Services Viewsets Contract from exceptions import ServiceLayerFunctionMissing class ChecksContract: @classmethod def get_checks(cls): """Retrieve all the checks.""" raise ServiceLayerFunctionMissing('get_checks not implemented') Services from checks.contract import ChecksContract from checks.models import Check class ChecksServices(ChecksContract): @classmethod def get_checks(cls): return Check.objects.all() Viewsets from rest_framework import viewsets from checks.serializers import CheckSerializer from checks.services import ChecksServices class CheckViewSet(viewsets.ModelViewSet): queryset = ChecksServices.get_checks() serializer_class = CheckSerializer So, the problem I have is with the line queryset = ChecksService.get_checks(). The construct Queryset is a django.core.db class. It has a very specific API and with that one line I've tightly coupled my viewset … -
Why isn't django development server finding my static files
I'm really confused about this. I've got a django site set up and my settings are all correct, but when I run my server it doesn't find the files. See below for the necessary code. settings.py: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_comments', 'best_schools', 'debug_toolbar', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] # --snip-- STATIC_URL = '/static/' STATIC_ROOT = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) + '/static/' directory structure: jonathan at k-nine ~/Sites/tbs_django (master tbs_django) [02:04 pm] -> ls ./ best_schools/ db.sqlite3 license.txt manage.py* README.md requirements.txt static/ tbs/ templates/ ipython console: In [1]: from tbs import settings In [2]: settings.STATIC_ROOT Out[2]: '/home/jonathan/Sites/tbs_django/static/' In [3]: settings.STATIC_URL Out[3]: '/static/' output of manage.py findstatic doesn't even see my static directory: jonathan at k-nine ~/Sites/tbs_django (master tbs_django) [02:06 pm] -> manage.py findstatic --verbosity 2 custom-admin.css /home/jonathan/Sites/tbs_django/manage.py No matching file found for 'custom-admin.css'. Looking in the following locations: /home/jonathan/.virtualenvs/django-tbs/lib/python3.6/site-packages/django/contrib/admin/static /home/jonathan/.virtualenvs/django-tbs/lib/python3.6/site-packages/debug_toolbar/static I have this in my urls.py: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) The weird thing is that when I run manage.py runserver --nostatic it works perfectly. Why does django not find my static files? I'm running Django 1.10.2. -
Django hangs on model.save()
I wrote a command script to pull a bunch of data from some local files and write them to the sites mySQL Database. It worked great till it crashed at id 2512 because of a connection interruption during the execution of a SQL query. Since then the script hangs on current_shiur.save() in the code below. Section of the code running: if Shiur.objects.filter(path=file['path']).count() > 0: print("Found File") current_file = Shiur.objects.get(path=file['path']) print("Got Object") current_file.audioURL = "http://audio.torahrecordings.com{}.MP3".format(current_file.path) print("Set Audio Link") current_file.save() print("File Saved") result: Found File Got Object Set Audio Link and then it just hangs forever. even Keyboardinterrupt does not work. Changing the database to a SQLite3 local file "fixes the issue". when running.save() on the object from the manage.py shell however, works just fine. -
How to process this function-based-view using class-based views?
I'm following this tutorial about ajax and crud. The tutorial uses function-based-views approach, instead, I want to use class-based-views, particularly for this view. def book_create(request): data = dict() if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True books = Book.objects.all() data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', { 'books': books }) else: data['form_is_valid'] = False else: form = BookForm() context = {'form': form} data['html_form'] = render_to_string('books/includes/partial_book_create.html', context, request=request ) return JsonResponse(data) -
Django with AWS, help me find my target wsgi script
Okay, so I recently had my whole website up and running. However, I switched computers and to retrieve the websites code I downloaded the ZIP of the project. Whenever I run eb deploy errors arise as it says my WSGI points to a file that doesn't exist. Here is my project structure. -suliman_baldo -bin -include -lib -suliman_baldo -.ebextension -01-flask.config -django.config -.elasticbeanstalk -config.yml -gallery -main -static -templates -suliman_baldo -admin.py -settings.py -urls.py -wsgi.py Here is my django.config file option_settings: aws:elasticbeanstalk:container:python: WSGIPath: suliman_baldo/wsgi.py This is weird as the project structure is the same as before but the WSGI Path has changed -
Django - two sections from the same model
I have 'sites' section in my admin page. Here is part of my models.py: class Site(models.Model): category = models.ForeignKey('Category') subcategory = ChainedForeignKey( 'Subcategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True) name = models.CharField(max_length=70) description = models.TextField() keywords = MyTextField() date = models.DateTimeField(default=datetime.now, editable=False) url = models.URLField() is_active = models.BooleanField(default=False) I would like to add another Sites section in my admin which will only show inactive sites (is_active = False). Is it possible? (I mean: Sites - first section (list of all sites) Inactive sites (number of inactive sites) - second section (only inactive sites) ) Here is my admin class: class SiteAdmin(admin.ModelAdmin): list_display = ('is_active', 'name', 'description', 'keywords', 'date') fields = ('name', 'url', 'category', 'subcategory', 'description', 'keywords', 'date', 'is_active') readonly_fields = ('date',) list_editable = ('is_active',) list_display_links = ('name',) -
Save request.POST to database
in view.py: @require_POST @csrf_exempt def ipn(request): transactions_logger = logging.getLogger("django") processor = Ipn(request.POST, logger=transactions_logger) verification_success = processor.verify_ipn() encoding = request.POST.get('ok_charset', None) data = QueryDict(request.body, encoding=encoding) if verification_success: form = OkpayIpnForm(data) if form.is_valid(): print("ALL FINE!!") form.save() return HttpResponse("") In forms.py: class OkpayIpnForm(forms.ModelForm): class Meta: model = OkpayIpn exclude = [] Code for IPN Checkprocessor = Ipn(request.POST, logger=transactions_logger: class Ipn(object): OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify' OKPAY_IPN_INVALID = b'INVALID' OKPAY_IPN_VERIFIED = b'VERIFIED' OKPAY_IPN_TEST = b'TEST' OKPAY_STATUS_COMPLETED = 'completed' __verification_result = False def __init__(self, request_data, logger): if 'ok_verify' in request_data: raise Exception("ok_verify must not be present in initial request data for {}".format( self.__class__.__name__ )) self._request_data = request_data self.logger = logger return def verify_ipn(self): self.__verification_result = False headers = { 'Content-Type': 'application/x-www-form-urlencoded', } verify_request_payload = { 'ok_verify': 'true', } verify_request_payload.update(self._request_data) resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers) if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST: self.__verification_result = True # if resp.content == self.OKPAY_IPN_VERIFIED: # anyway disable test on production. # self.__verification_result = True return self.__verification_result All is ok, I revice IPN and validate it, then I try to validate form and save it to Database. But form doesn't pass validation and doesn't save to database. Thank You for help -
Preventing code duplication in Elastic Search
How do I avoid code duplication for the purposes of indexing in Elastic Search (Django Project)? It is my understanding that you can't return objects in elastic search, but a lot of times I find myself using different variables from the same related object. For example if I had an index for a Student and needed Information about the Subjects they're taking. If I wanted the first Subject the student enrolled in, I would do something like this in elastic search: ... first_subject_enrolled_id = indexes.IntegerField(model_attr='service__id') def prepare_first_subject_enrolled_id(self, obj): first_subject_enrolled = Subject.objects.filter(student=obj).order_by('id') return first_subject_enrolled.id But then let's say I also want the Subject name of the first class enrolled. I would have to repeat a lot of code. For example: def prepare_first_subject_name(self, obj): first_subject_enrolled = Subject.objects.filter(student=obj).order_by('id') return first_subject_enrolled.name Is there a way I can just call the index function prepare_first_subject_enrolled_id to avoid duplication and unnecessary indexing of similar code? -
Limit multiple "Many to One" fields into "One to One" association : Django
We've Book, User and Rating as Django model. Each Book has many Ratings Each Rating has one Book Each User has many Ratings Each Rating has one User For Book class Book(models.Model): isbn = models.CharField(max_length=32) title = models.CharField(max_length=256) def __str__(self): return self.title For Book Rating class BookRating(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.SmallIntegerField(choices=[(i, i) for i in range(1, 6)]) def __str__(self): return self.rating Problem Statement How can I ensure that each User has atmost one rating on each book? -
Can Mezzanine send an email to admin when a user signs up?
Is there any way to configure Mezzanine so that the admin user gets an email when a new (regular) user signs up? I have ACCOUNTS_VERIFICATION_REQUIRED=True, so the would-be user gets an email, but I don't want to have to approve accounts myself (ACCOUNTS_APPROVAL_REQUIRED). If this isn't possible out of the box, do I need to customize the accounts app? Or monkey-patch UserProfileAdmin.save_model? What is the best approach? -
Django - Issue with filtering when extending abstract base class
My DB has is_deleted field in some tables. And if there's such column, I want to ALWAYS exclude the results with is_deleted = true from ANY queryset. To achieve this, I am using this post to implement the goal. And here is my code. class MixinManager(models.Manager): def get_query_set(self): try: return self.model.MixinQuerySet(self.model).filter(is_deleted=False) except FieldError: return self.model.MixinQuerySet(self.model) class BaseMixin(models.Model): admin = models.Manager() objects = MixinManager() class MixinQuerySet(QuerySet): def globals(self): # http://stackoverflow.com/questions/809210/django-manager-chaining try: return self.filter(is_global=True) except FieldError: return self.all() class Meta: abstract = True class DeleteMixin(BaseMixin): is_deleted = models.BooleanField(default=False) class Meta: abstract = True def delete(self): self.deleted = True self.save() class Sms(DeleteMixin): # Some code And s REST resource: class SmsList(APIView): def get(self, request, format = None): sms = Sms.objects.user(request.user) serializer = SmsSerializer(sms, many=True) return Response(serializer.data) The problem is that the queryset still includes all records - both with is_deleted = true and is_deleted = false. What am I doing wrong ? -
Django F Object as Parameter for relativedelta
I am trying to create a custom django model manager. The end goal is to find items in the log that have expired. The issue is the expiration is a dynamic amount of months, and is stored in a field in a related table. First I am trying to find how many months the training is valid for. This is stored in course -> expiry Next I must add this amount of months to the date the user completed the course. This date is in trainingLog -> completion_date Finally see if the date result from above is less than todays date. class course(models.Model): ... expiry = models.PositiveSmallIntegerField() #In Months ... class trainingLogManager(models.Manager): def expired(self): # This code does not work. F object can not be passed as parameter to relativedelta ## TypeError: bad operand type for abs(): 'F return self.get_queryset().filter(completion_date__lt=Sum(F('completion_date') + relativedelta(months=F('course.expiry')))) class trainingLog(models.Model): ... course = models.ForeignKey(course) completion_date = models.DateTimeField() objects = trainingLogManager() ... def isExpired(self): expiration_date = self.completion_date.date() + relativedelta(months=self.course.expiry) return datetime.today().date() > expiration_date The desired outcome is a model manager similar to the function isExpired(). Goal : trainingLog.objects.expired() Current : tlog = trainingLog.objects.all() for t in tlog: if t.isExpired(): ## Do Something with object / Add to … -
Django : Form data not saving
I have a form where user just uploads an image,but problem is when I choose an image and press button to submit. It says This field is required.on the page although I have already pointed the image. And that's all it does.I checked if it was actually submitted but no, it was not.What could be the problem ? Models.py class pic(models.Model): username = "anonymous" picpost = models.ImageField(upload_to='anon_pics') creation_date = models.DateTimeField(auto_now_add=True) forms.py from django import forms from .models import pic class PicForm(forms.ModelForm): class Meta: model = pic fields = [ "picpost" ] view.py def pic_create(request): form = PicForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() context = { "form" : form, } return render(request, "create_pic.html", context) create_pic.html <body> <form method='POST' action=''>{% csrf_token %} {{ form.as_p }} <input type='submit' value='Upload Picture' /> </form> </body> Any help is highly appreciated.Thank you very much! -
Why simple search doesn't work?
I'm creating a simple search bar to search through my blog articles. The problem is that when I search something on it nothing happens, it doesn't even reach the view where the pdb traceback should run. If anyone could explain to me what I'm doing wrong and how GET should work to search queries it'd be really helpful. here is all related code for the search bar : models.py class Article(models.Model): title = models.CharField(max_length=120) description = models.CharField(max_length=1000) user = models.ForeignKey(User) create_time = models.DateTimeField(auto_now_add=True) views.py def index(request): articles = Article.objects.all() return render(request, 'index.html', {'articles': articles}) def search_articles(request): # import pdb; pdb.set_trace() (doesn't get executed if uncommented) articles = Article.objects.filter(title__contains=request.GET['title']) return render(request, 'index.html', {"articles": articles}) index.html <form role="search" method="GET" action="{% url 'search' %}"> <input type="text" name="title"> <button>Search</button> </form> {% for article in articles %} {{ article.title }} {% endif %} urls.py url(r'^$', views.index, name='index'), url(r'^search/$', views.search_articles, name='search'), I don't see any problem but somehow GET doesn't reach the view since the pdb debugger doesn't get executed. Any suggestion on where the issue might be ? -
django jquery ajax uncaught referenceerror is not defined
here is my javascript code <script src="http://code.jquery.com/jquery-1.12.2.min.js" ></script> function likeButton(id, updown, token) { $.ajax({ type: "POST", url: "/ajax/updown", data: { id: id, updown: updown, csrfmiddlewaretoken: token} }).done(function(res) { if(updown == 'LIKE') { var numb = Number($(".vote-number-like").text()) + 1 var numb = Number($(".vote-number-dislike").text()) - 1 } else if(updown == 'DISLIKE') { var numb = Number($(".vote-number-like").text()) - 1 var numb = Number($(".vote-number-dislike").text()) + 1} }).fail(function(res) { alert('Fail... login?'); }); } and my temlplate code is <a href="javascript:;" onclick="likeButton({{ instance.id }}, 'LIKE', '{{ csrf_token }}')">Like</a> <h5 class="vote-number-like">{{ instance.rating_likes }}</h5> <a href="javascript:;" onclick="likeButton({{ instance.id }}, 'DISLIKE', '{{ csrf_token }}')">Dislike</a> <h5 class="vote-number-dislike">{{ instance.rating_dislikes }}</h5> but error message like this. Uncaught ReferenceError: likeButton is not defined at HTMLAnchorElement.onclick ((index):93) I really don't know what is problem. I need your help! -
How to query model if entry exists in another model
Say I have a model like so class Animal(Model): species = CharField(max_length=128) class AnimalsAsPets(Model): animal = ForeignKey(Animal) Is it possible to query all Animals if they exist in AnimalsAsPets? Something like: Animal.objects.filter(id__in=AnimalsAsPets.objects.all())