Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing the position of drag and drop element to Django views.py
I've created 2 drag and drop boxes which an icon can be moved between using the javascript: function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.targer.id) } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementID(data)); and the relevant html <form action="" method="get"> <div id="yes_box" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="/icon/" draggable="true" ondragstart="drag(event)" /> <input type="hidden" name="icon_pos" id="icon_pos" /> </div> <div id="no_box" ondrop="drop(event)" ondragover="allowDrop(event)"> </div> <input type="sumbit" text="submit"> </form> When the user hits the submit button I would like to pass to Django views.py the position of the icon using something like pos = request.GET('icon_pos'). What do I need at add to my javascript to update the value of 'icon_pos'? I've seen similar examples online but since I'm very new to javascript I'm not sure how to adapt these to my situation. Thanks in advance. -
Using python shell, how do I associate an image with an ImageField in a class (Django)
Okay so I added a field to a model called college. Here is the new field: logo = models.ImageField(upload_to="logos", default="static/images.default.png") So I have a few images in my media folder, but how do I associate them with certain images in the class. Would I say Harvard.logo = ? Would the ? be the image path. What exactly is the image path? Using Pillow. -
How to call a django method from template without using a form?
I'm building a comment system and want to implement upvoting/downvoting, similar to SO and reddit. My question is, how exactly can I detect a click on my upvote or downvote img and call a function from django? Or is there another way of going about this? Here's my code: template ... <div class="vote_div"> <img src="upvote.png" class="upvote" /> <img src="downvote.png" class="downvote" /> </div> ... models.py class Comments(models.Model): ... #score upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) I want to call a function in my views.py to handle the voting, but as I said I don't know how to do it. As i'm aware it's not possible to call a django function from js/jquery. Any idea? -
Python: 'unicode' object has no attribute 'append'
I'm using Django and I'm trying to make a function that stores the name of visited pages in request.session. However I keep getting the error "'unicode' object has no attribute 'append'" on the line where I try to append a variable to request.session['visited_pages'] I searched online and I didn't find anything that solved the problem, I did find that you can't append directly to request.session['visited_pages'], instead you have to make a separate array. I did that but that didn't fix my problem. Here is my code: def index(request): visited_pages = get_visited_pages(request) context = { "visited_pages": visited_pages } return render(request, 'website/index.html', context) def get_visited_pages(request): current_url = resolve(request.path_info).url_name if not 'visited_pages' in request.session or not request.session['visited_pages']: request.session['visited_pages'] = current_url else: visited_pages_array = request.session['visited_pages'] visited_pages_array.append(current_url) request.session['visited_pages'] = visited_pages_array -
How to avoid code duplication with similar Django model methods?
The following model contains the two almost identical functions list_ancestors and list_descendants. What would be a good way to write this code only once? class Node(models.Model): name = models.CharField(max_length=120, blank=True, null=True) parents = models.ManyToManyField('self', blank=True, symmetrical=False) def list_parents(self): return self.parents.all() def list_children(self): return Node.objects.filter(parents=self.id) def list_ancestors(self): parents = self.list_parents() ancestors = set(parents) for p in parents: ancestors = set.union( ancestors, set(p.list_ancestors()) ) return list(ancestors) def list_descendants(self): children = self.list_children() descendants = set(children) for c in children: descendants = set.union( descendants, set(c.list_descendants()) ) return list(descendants) def __str__(self): return self.name The solution should look something like this: def list_withindirect(self, list_direct): direct = list_direct() withindirect = set(direct) for d in direct: withindirect = set.union( withindirect, set(d.list_withindirect(list_direct)) ) return list(withindirect) def list_ancestors(self): return self.list_withindirect(self.list_parents) def list_descendants(self): return self.list_withindirect(self.list_children) But I don't find a way that works. This example e.g. leads to recursion problems. -
Is it possible to integrate Django to Zimbra 8.5? and How we can utilize Django Project for Send Mass Mail?
We have an SMTP relay project and we are looking if possible to integrate the Django to Zimbra 8.5. We are sending mass email per cycle with an average of 80k to 200k. We have an existing exchange server but we are having an issue when sending mass email when it comes to an average of 700+k so we plan to migrate to Zimbra 8.5. Thank you! -
Unable to connect to server when running dockerized django app?
I have looked through the questions on this site, but I have not been able to fix this problem. I created and ran an image of my django app, but when I try to view the app from the browser, the page does not load (can't establish a connection to the server) I am using docker toolbox, I am using OS X El Capitan and the Macbook is from 2009. The container IP is: 192.168.99.100 The django project root is called "Web app" and is the directory containing manage.py. My Dockerfile and my requirements.txt files are in this directory. My dockerfile is: FROM python:3.5 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] My requirements.txt has django and mysqlclient My django app uses Mysql, and I tried to view the dockerized django app in the browser with and without linking it to the standard mysql image. In both cases, I only see 'problem loading page couldn't establish connection to server' When I did try linking the django container to the mysql container I used: docker run --link mysqlapp:mysql -d app Where mysqlapp is my mysql image and 'app' is … -
Implementation of an object in a html file
I have an app called loans which have a class named Loan with an object start_date in a Django project. I want to execute that object into a html file. Do I have to place it as {{ loans.loan.start_date}} or just {{ loan.start_date }}? Thanks in advance! -
Learning Django, but confused with va
I am going through the Django Tutorial and i am on step 3 of creating polls app. There is a variable called "question_id" and i cant understand where exactly this is defined or where its coming from. I will post the files bellow. My only guess is that this variable is somehow created by Djanog internally when class Question is defined in Models.py, but i am not sure. Its not defined in "Question" class. Here are my files: views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) #def index(request): # return HttpResponse("Hello, world. You're at the polls index.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "Your looking at result of question %s." return HttpResponse(response % question_id) def vote(reqeust, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py from django.conf.urls import url from . import views urlpatterns = [ #ex: /polls/ url(r'^$', views.index, name='index'), #ex: /polls/5 url(r'^(?P<question_id>[0-9]+/$)', views.detail, name='detail'), #ex: /polls/5/result/ url(r'^(?P<question_id>[0-9]+/results/$)', views.results, name='results'), #ex: /polls/5/vote url(r'^(?P<question_id>[0-9]+/vote/$)', views.vote, name='vote'), ] models.py import datetime from django.db import models from django.utils import … -
Django @csrf_exempt not working in class View
I have an application in Django 1.9 that uses SessionMiddleware. I would like to create an API for this application inside the same project, but when doing a POST request it does not work the @csrf_exempt annotation. I am doing the requests throw Postman and this is what I have so far: settings.py MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'a9.utils.middleware.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'a9.core.access.middleware.AccessMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', #'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.OAuth2Authentication', #'rest_framework.authentication.TokenAuthentication', ) } urls.py urlpatterns = [ url(r'^v1/', include([ url(r'^', include(router.urls)), url(r'^auth/', MyAuthentication.as_view()), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^admin/', include(admin.site.urls)), ])), ] views.py @method_decorator(csrf_exempt, name='dispatch') class MyAuthentication(TemplateView): def post(self, request, *args, **kwargs): return HttpResponse('Hello, World!') After this I get always a CSRF verification failed error. I asked this question in the IRC channel of django-rest-framework but … -
How do I give priority to the user?
I have User database table with status (Int field), timestamp and priority_flag (Int field) fields. I am using the following query to prioritize the user. users = User.objects.filter(status=status).order_by('priority_flag', 'timestamp') If the user has high priority_flag, that user should first respond to the query. For example, there are 2 users. Bob = [priority_flag=Standard, timestamp=datetime.datetime(2007, 2, 17, 23, 42, 31, 584349, tzinfo=<UTC>)] Alice = [priority_flag=Emergency, timestamp=datetime.datetime(2017, 1, 17, 23, 42, 31, 584349, tzinfo=<UTC>)] Even if the user Alice is created 10 years later, but her priority is higher than Bob. It should response first. What am I doing wrong here ? Thank you! -
Finding a python module version gives error on production box but not my dev machine
I have the pgdb module installed on my MacOsX development box, my code works (specifically a line that is pgdb.connect(etc..) works great. I runt his code on my main server (linux) and it it says module has no attribute connect. I think it is a version issue so I do what is suggested here to view the versions: How to check version of python modules? That is I do: python import pgdb print pgdb.__version__ On my macosX box, returns the version just fine on my development machine it gives the error again: AttributeError: 'module' object has no attribute '_version_' Strange thing is, doing an import pgdb does not throw an error but it acts like it is not installed on my production box. Perhaps it is a library mangling on the box I am not aware of? I should say import pgdb as myspecialsomething (That didn't do it still says no connect) ? The other thing is, I did do a sanity check and did a sudo pip install pgdb on the production box and got this: Requirement already satisfied: pgdb in /usr/lib/python2.7/site-packages Requirement already satisfied: psycopg2>=2.5.2 in /usr/lib64/python2.7/site-packages (from pgdb) -
Passing URL variables to a class based view
I have just started messing with class based views and I would like to be able to access variables from the URL inside my class. But I am having difficulties getting this to work. I saw some answers but they were all so short I found them to be of no help. Basically I have a url url(r'^(?P<journal_id>[0-9]+)/$', views.Journal_Article_List.as_view(), name='Journal_Page'), Then I would like to use ListView to display all articles in the particular journal. My article table however is linked to the journal table via a Journal_id. So I end up doing the following class Journal_Article_List(ListView): template_name = "journal_article_list.html" model = Articles queryset = Articles.objects.filter(JOURNAL_ID = journal_id) paginate_by = 12 def get_context_data(self, **kwargs): context = super(Journal_Article_List, self).get_context_data(**kwargs) context['range'] = range(context["paginator"].num_pages) return context The journal_id however is not passed on like it is in functional views. From what I could find on the topic I read I can access the variable using self.kwargs['journal_id'] But I'm kind of lost on how I am supposed to do that. I have tried it directly within the class which let's me know that self does not exist or by overwriting get_queryset, in which case it tells me as_view() only accepts arguments that are already … -
Why is django form removing fields from a model?
I got a tracking model, and an evidence model wit ha foreign to it. Im trying to upload a file in evidence related to that tracking...but when i try to save i got this error: Request Method: POST Request URL: http://127.0.0.1:8000/myapp/change_actions/tracking/create/1/ Django Version: 1.10.1 Exception Type: RelatedObjectDoesNotExist Exception Value: Evidence has no tracking. My view saves tracking form and then passes the id of that record to the evidence form as foreign.....but that error is like the form was eliminating the tracking field !!....these are my files : Models.py class Tracking(ModelBase): activity = models.ForeignKey( Activity, verbose_name = 'Actividad', null = False) code = models.CharField('Codigo de seguimiento', max_length=50) observation = models.TextField('Avance a la fecha', max_length=2000) tracking_date = models.DateTimeField('Fecha de seguimiento') def __str__(self): return self.observation class Evidence(ModelBase): tracking = models.ForeignKey( Tracking, related_name = 'Tracking_evidence', verbose_name = 'Seguimiento', null = False) evidence = models.FileField(verbose_name = 'Evidencia', null = True, upload_to='documents/') This is the form.py: class EvidenceForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.tracking = kwargs.pop('tracking') super(EvidenceForm, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): cleaned_data = super(EvidenceForm, self).clean() self.instance.tracking.id = self.tracking class Meta: model = Evidence fields = ['tracking', 'evidence'] And the view to it : class TrackingCreateView(View): template_name = ['change_actions/tracking_create.html'] breadcrumb = [{'name': 'Registro de seguimiento', … -
understanding cache duplicate queries as reported by django toolbelt
This is in the context of a project using caching in a postgres database: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'site_cache', }, } From the toolbelt: SELECT cache_key, value, expires FROM "site_cache" WHERE cache_key = ':1:jsdata' Duplicated 2 times. /Users/ME/Documents/Apps_And_Sites/Python_Apps/Django-Apps/jsproject/src/charts/use_cases/crud.py in chart_detail(89) js_dow_data = jsdow_data( ) /Users/ME/Documents/Apps_And_Sites/Python_Apps/Django-Apps/jsproject/src/jsdex/project_utilities.py in jsdow_data(22) jsdow_cached = cache.get( "jsdata" ) Corresponding code in crud.py which is the django VIEW: from jsdex.project_utilities import jsdow_data, js_dow_data = jsdow_data( ) Corresponding code in project_utilities.py def jsdow_data( ): jsdow_cached = cache.get( "jsdow" ) if jsdow_cached: my_print( "jsdow cache hit" ) data_json = jsdow_cached I don't understand how to interpret the duplication warning: In the crud.py which is the view I import jsdow_data on top of file from project_utilities, and then I call it with jsdow_data( ) . Does this count for 2 queries ? -
Java Script code not working if URL is not home/root
I have a java script code for a top navigation bar. The code only works if I am at the root (home) of the website. For example if you click on the plus icon on the top right corner you are taken to another page and then the menu stops working. I am good at JS right now and I cannot figure out why. I have guessed this could be due to the fact some of the elements are not loaded when the url is different, but I cannot fix it. I am going to post the CSS and html code to see where SCRIPTS are placed. One fact about the Script that is inside the body of the html file is that I cannot move it to outside body since the menu stops working again. I I think the cause is the same thing, but I cannot fix it. Please give me an edited code since in another question people gave me ideas, while I tried all of them and none worked. This is just to make sure that any answer is a working answer and it is not just a hunch. Thanks! Here is a link for the … -
Getting 403 from Apache served static files, even though I have read/write permissions - Django
I have a Django application that I have deployed, and all has been well until last night. When I try to run my live site, via webfaction, I get a bunch of 403 forbidden response codes for my static files. I have a symbolic link to a static directory on the top level of my project, and the STATIC_ROOT in my settings configuration is correct. I also checked the permissions of one of the files that is giving me an issue, and it says I have at least read/write permissions. But I'm still getting a 403, and am not sure why since it has been working fine for months. The apache config is all correct too, and the site is running smoothly. It is just the static resources. apache/conf/httpd.conf ServerRoot "/home/abenton42/webapps/arkansastherapistconnection/apache2" LoadModule authz_core_module modules/mod_authz_core.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule wsgi_module modules/mod_wsgi.so LoadModule unixd_module modules/mod_unixd.so LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /home/abenton42/logs/user/access_arkansastherapistconnection.log combined ErrorLog /home/abenton42/logs/user/error_arkansastherapistconnection.log Listen 20377 KeepAlive Off SetEnvIf X-Forwarded-SSL on HTTPS=1 ServerLimit 1 StartServers 1 MaxRequestWorkers 5 MinSpareThreads 1 MaxSpareThreads 3 ThreadsPerChild 5 WSGIDaemonProcess arkansastherapistconnection processes=2 threads=12 python-path=/home/abenton42/webapps/arkansastherapistconnection:/home/abenton42/webapps/arkansastherapistconnection/a$ WSGIProcessGroup … -
wagtail snippets access to request
I building a website using wagtail but I don't find the way how to access to request from wagtail snippets class and the current documentations is very poor. I'm trying to get the current session to format some fields in my model form. -
Django - combining custom querysets used as managers with abstract class inheritance
Basically, I have to achieve two goals in my project that are currently conflicting with each other in terms of implementation. The goals are: Enabling chainable filtering for model instances (my_model.objects.custom_filter1().custom_filter2() etc) For those tables with is_deleted field, and I want to exclude records marked as deleted, so that I don't have to explicitly filter for deleted records (use my_model.objects.all() instead of my_model.objects.filter(is_deleted = false)) Currently I have the following code: class MixinManager(models.Manager): def get_queryset(self): try: return self.model.MixinQuerySet(self.model).filter(is_deleted=False) except FieldError: return self.model.MixinQuerySet(self.model) class BaseMixin(models.Model): objects = MixinManager() class MixinQuerySet(QuerySet): pass class Meta: abstract = True class DeleteMixin(BaseMixin): is_deleted = models.BooleanField(default=False) class Meta: abstract = True class Sms(DeleteMixin): # core fielrds # objects = SmsQuerySet.as_manager() class Meta: managed = False db_table = 'sms' This code snipper solves the second goal. However, my first goal becomes seemingly infeasible. Prior to using abstract classes for achieving the second goal, I had the following code: class SmsQuerySet(models.query.QuerySet): def filter_1(self, user): return self.filter(...) def filter_2(self, user): return self.filter(...) def filter_3(self, user): return self.filter(...) class Sms(models.Model): # core fields objects = SmsQuerySet.as_manager() This syntax solved my first goal. THE QUESTION: The problem is that I can't combine these two structures into one logic, so that I … -
Which object should hold the many-to-many relationship in Django?
I'm just learning Django and have a quick question: I see that when creating a model you can define a many-to-many relationship between two objects. While you assign this relationship to one of the objects, Django actually creates a third table to resolve this M:N relationship. Given this, does it matter which object holds the many-to-many field or can it appear on either of the two, related objects? (coming from a relational DB background, I've got to say that the concept of assigning the M:N to one table feels a bit odd - I'm still not over the idea of not starting with an ER diagram) -
Django Form Fields on User Model look nice, how?
As you can see below any field on the form linked to the user looks lovely. The one I have added as part of the profile looks too short and doesn't fit in: The html for the form is as follows: <fieldset><legend>Personal Details</legend> <div class="form-group"> <label class="col-sm-5 control-label">{{ form.first_name.label }}:</label> <div class="col-sm-7"> {{ form.first_name }} <div class="text-danger"> {% for error in form.first_name.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">{{ form.last_name.label }}:</label> <div class="col-sm-7"> {{ form.last_name }} <div class="text-danger"> {% for error in form.last_name.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">{{ profileform.contact_number.label }}:</label> <div class="col-sm-7"> {{ profileform.contact_number }} <div class="text-danger"> {% for error in profileform.contact_number.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">{{ form.email.label }}:</label> <div class="col-sm-7"> {{ form.email }} <div class="text-danger"> {% for error in form.email.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> </fieldset> Models are as follows: class Profile(models.Model): user = models.OneToOneField(User, unique = False) contact_number = models.CharField(max_length=15) referral_code = models.PositiveSmallIntegerField() class Meta: managed = True db_table = 'fbf_profile' With the forms as follows: class RegistrationForm(BootstrapModelForm, UserCreationForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) # The default Django user model doesn't … -
Export Django model/classes to (Postgre)SQL statement
I've created a web application using django. I'm not very happy with it, and would like to export/translate the whole "model" I've created within Django (i.e. alle the classes) into an SQL statement. I know the following statment prints the relative SQL statement within django (considering only the changes). python manage.py sqlmigrate polls 0001 But how to I export the initial (whole) model into an sql file? Theoretically, I could simply export an SQL dump directly from the database. But my database has become messy (additional tables) and my models.py is a clean formulation of the original database. -
Adding field to the auth_user_group intermediatary table
Does anyone know if it is possible to add a field to the intermediatary auth_user_group table? I'd like to have a manager flag to identify a user that is a member of a group as a group manager (the permissions for this will be handled separately), but this relationship seems obfuscated by Django. Any ideas would be greatly appreciated! Thanks! -
How to dynamically add `read_only = True` on a field on serializer when creating object
I have really complicated serializer (goes three levels deep), that I am using in two views. For POST and PATCH calls. I am wondering how can I dynamically change the read_only attribute on pk field, considering the action that is performed. If I send a POST of this data to the endpont: { "id": 93, "name": "Template workout", "items": [ { "id": 74, "is_superset": false, "seq": "00002", "exercises": [ { "id": 50, "exercise": { "id": 3, "title": "sprint" }, "set_type": "time", "rest": 30, "sets": [ { "id": 141, "weight": null, "reps": null, "time_interval": 30 }, { "id": 142, "weight": null, "reps": null, "time_interval": 40 }, { "id": 143, "weight": null, "reps": null, "time_interval": 50 } ] } ] } ] } I would like to remove all the id keys with values from this structure. I am thinking that sendng it trough serializer when id is read_only=True is my best bet, but I do need the ids when updating. -
Django admin ascii error
I know what the problem is that I have a special char. But this is the tricky part: It's already in the Django db so when I want to delete it in the Admin I get the error page so I can't delete it.