Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin how to manipulate OneToMany related objects(not just inline)
I have 2 models. One has a foreign key to another. Say: class Organization(models.Model): title = models.CharField(max_length=300) class User(models.Model): name = models.CharField(max_length=300) organization = models.ForeignKey(Organization) I want to show all users who work in current organization in organizationAdmin, like a list of change links. It should be possible to add new user to select existing user and set his organization to current No need to edit them inline Just like permissions in userAdmin + adding and changing them Is there any ready solution? Not to make forms by hands -
Total count of objects in Django Model
Using Django ~=1.11 and Python 3.6 I am a beginner! Every answer I've found online for my question is more advanced than what I'm looking for. Here's my model: class Byte(models.Model): text = models.CharField(max_length=30) def __str__(self): return self.text Here's my view: def byte_list(request): bytes = Byte.objects.order_by('text') return render(request, 'cloudapp/byte_list.html', {'bytes': bytes}) Here's my template: {% block content %} <div class="total"> <h2>Total number of words and phrases entered: {{ byte.count }}</h2> </div> <hr> {% for byte in bytes %} <div class="byte"> <h2>{{ byte.text }}</h2> </div> {% endfor %} {% endblock %} This allows the creation "Byte" objects in the /admin, with only one field - a small text field. Right now, the template simply displays a list of all the objects created. Question/Problem: I'd like to display the total number/count of objects that have been created for the Byte model. In the template, I have a tag {{ byte.count }} to display this. I've tried using count() and Aggregation, but not sure how to work those into my model/view/template. I'm looking for the most simple and up-to-date way to accomplish this, whether it's using a method or @property in the model, or some type of query set in the view. -
Django query date range by url
I have a model with an attribute tracking things by date added, and I want to be able to query for objects added after a certain date. There is a DateTimeFromToRangeFilter that looks useful, but I don't see any guidance on how to format my URLs to make use of it. How can I query for objects by a range of dates? -
Django - Easiest way of making parallel API calls
Suppose that I have a Django view and that I would like to call two APIs at the same time. def djangoview(request): #Call API 1 #Call API 2 before API Call 1 finishes #Wait for both calls to finish output = [Apicall1.response, Apicall2.response] return(HttpResponse) I've been trying to use multiprocessing library and pools without success. I'm using Apache2 and Wsgi, how can I make this work? Maybe making the call on a different thread? -
How can I generate a nav bar in django?
I was wondering if it's possible to generate a nav bar. My idea was to get a list of sorts from urls.py and use a {% for %} block to ieterate through and create the navbar in the template. Any suggestions on how I could go about implementing this strategy, or if there's a better strategy? -
Create a site similar to tripadvisor with django
I'm completely new to web development, so I was thinking of using django, since I already have experience in python. What I would like to create is a site in which user can login and leave reviews of things, possibily add new things (places, objects, programs) to review and things like that (tripadvisor is just to give an idea). I know django is used for backends, but since I should learn it from scratch (or would I?, dont know how much python knowledge helps with django) would another language be better suited for the task? Additionaly, how complicated would it be (considering the backend only)? Thanks -
How to join wagtail and django sitemaps?
I'm using wagtail app in my Django project. Is it possible to join django sitemaps (https://docs.djangoproject.com/en/1.11/ref/contrib/sitemaps/) with wagtail sitemaps (wagtail.contrib.wagtailsitemaps)? Tried using django sitemap indexes, but it divide only django sitemap, how I can include wagtail sitemap? -
AttributeError: module 'wagtail.wagtailadmin.edit_handlers' has no attribute 'FieldPanel'
python 3.6 wagtail 1.10.1 Some hours ago my wagtail based project stopped to launch successfully. It fails here: from wagtail.wagtailadmin import edit_handlers print(dir(edit_handlers)) class Article(Page): html = RichTextField() content_panels = Page.content_panels + [ edit_handlers.FieldPanel('html', classname="full"), edit_handlers.InlinePanel('gallery', label="Carousel items", classname='ArticleImage'), ] with error AttributeError: module 'wagtail.wagtailadmin.edit_handlers' has no attribute 'FieldPanel' After that I decided to ensure that it's not error of my environment and configured docker file: FROM python:latest ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt RUN pip install wagtail ADD . /code/ after that docker container hadn't been launched successfully (raised same error) I wrote this code according to docs: http://docs.wagtail.io/en/v1.9/reference/pages/panels.html How to solve? Thanx -
Internationalization of Django Library
I'm using a library (or python package? Not very familiar with the vernacular) that has all the good {% trans %} to translate strings. Whenever I generate the strings from my app with the makemessages command, those strings are never listed, I have to add them manually one by one. What Am I missing here? -
Pass a list from a view to a form
I have a view in my views.py and a form in my forms.py. I need some information to run my form and these informations are in my view. The question is, how do am I supposed to pass a list() of datas which contains ids to my form. Could you give my a simple example please ? Many Thanks -
Make in line or search pdf document with django?
I'm working with python to create a specific and personalized pdf document of assistance to meeting, in addition other document if the attendat worked in a workshop, then send the document(s) via mail to each one attendant with gmail (more or less 400 documents, 250 attendants) To improve the retrieval of the pdf document, I'm considering in django a module to enter the id number granted and to show the PDF document, and the person download it; in this way it would no longer send to each assistant the pdf document. But, I know that other way to solve this is making in line the PDF document, this includes a hashlib string like digital sign, the name of attendant, dates, etc. My question is: what way is the best to retrieve the PDF document or documents? (if the person atended two workshops and the general assistence to meeting, must have three PDF documents) a) search with django using the id in a folder with all documents? b) create in line all the PDF document using the id for each attendant? Thanks in advance, I know I have to improve my skills with django but I know that with your comments, … -
How can I access ALL model attributes from two tables joined together using django ORM
I want to access all values from two related tables that I joined together based on one of the tables attributes: obj = A.objects.filter(B__sample='sample_name').select_related() but when i do: {% for o in obj %} {{o.sample}} {{o.results}} {{o.qc}} {% endfor %} only o.results and o.qc (from table A) are returned, o.sample is not returned (from table B) how do i access all of the values from table A and B from my queryset object? -
Django Error : hasattr(): attribute name must be string
I'm getting a Django/Pythonic error and I don't have any idea How I can solve it. I tried lot of things but the error still there up to now. My error is : hasattr(): attribute name must be string This error comes from my Django's Form. When I click on validate form, I get this problem. My models.py file looks like : class Individu(models.Model): NumeroIdentification = models.CharField(max_length=30, null=True, verbose_name='Numéro Identification physique', unique=True) Civilite = models.CharField(max_length=12,choices=CHOIX_TITRE, verbose_name='Civilité') NomJeuneFille = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True) Nom = models.CharField(max_length=30, verbose_name='Nom de famille') Prenom = models.CharField(max_length=30, verbose_name='Prénom(s)') Sexe = models.CharField(max_length=30, choices=CHOIX_SEXE, verbose_name='Sexe') Statut = models.CharField(max_length=30, choices=CHOIX_STATUT, verbose_name="Statut civil") DateNaissance = models.DateField(verbose_name='Date de naissance') VilleNaissance = models.CharField(max_length=30, verbose_name='Ville de naissance') PaysNaissance = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') Nationalite1 = models.CharField(max_length=30, verbose_name='Nationalité 1') Nationalite2 = models.CharField(max_length=30, verbose_name='Nationalité 2', null=True, blank=True) Profession = models.CharField(max_length=30, verbose_name='Profession') Adresse = models.CharField(max_length=30, verbose_name='Adresse') Ville = models.CharField(max_length=30, verbose_name='Ville') Zip = models.IntegerField(verbose_name='Code Postal') Pays = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays') Mail = models.CharField(max_length=30, verbose_name='Email', blank=True) Telephone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True) Creation = models.DateTimeField(auto_now_add=True) InformationsInstitution = models.CharField(max_length=30, null=False, verbose_name='Informations Institution') Utilisateur = models.CharField(max_length=100, null=False, verbose_name="Utilisateur", default=" ") Etat = models.CharField(max_length=30, choices=CHOIX_ETAT, default=" ", null=False, verbose_name="Etat") def save(self, *args, **kwargs): for field_name in ['NomJeuneFille' … -
django book for real world web applications
i need to know, is there any book for django that focus on developing real world web applications ? I got my basics cleared. now i want to develop a fully featured e-commerce or social networking website. is there any book out there ? -
Having trouble reading Apache config variable trough wsgi in Django 1.11
I'm trying to read database settings from the Apache config and getting error. I tried many solutions from other questions, but it looks like this may be the Django 1.11 version issue. This is what I have. In httpd.conf: <VirtualHost *:80> .... SetEnv DB_NAME XYZ SetEnv DB_USER abc .... </VirtualHost> In wsgi.py: import os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.abspath(os.path.join(BASE_DIR, '..')) sys.path.append(PROJECT_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings' import django.core.handlers.wsgi _application = django.core.handlers.wsgi.WSGIHandler() env_variables_to_pass = ['DB_NAME', 'DB_USER', ] def application(environ, start_response): for var in env_variables_to_pass: os.environ[var] = environ.get(var, '') return _application(environ, start_response) In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], ...... }, } And when I run my application, I'm getting 'Internal Server Error'. This is what in the apache_error.log: [wsgi:error] raise KeyError(key) from None\r [wsgi:error] KeyError: 'DB_NAME'\r } -
Change behaviour of help text in django form globally
I want to take advantage of the default help text in django, but I don't like the way it's handled. I want to have: <tr><label>djangolab</label><input>djangoinput</input><span>djangohelp></span><span class='onhovershowhelp'>?</span> The last element is not provided by default. CSS on hover on '?' will change visibility for the help text span from hidden to visible. I want things to work out of the box so '{{form}}' will display as I want for any model form. So I want globally: Help text span by default with some attributes(z=1, hidden) Add another span to form row. I don't want to do this for every model form/field etc, use loops in the template and manually build this etc... -
django CVB: get current user in a form
I need to perform a form validation in wich current user is involved. I know how to do it but using FBV approach. Could be something like: first declare the __ init __() method: def __init__(self, user, *args, **kwargs): self.user = user super(MyFormClass, self).__init__(*args, **kwargs) so now I can use the self.user in any validation method. Later in a view method I could: if request.POST: form = MyFormClass(request.user, request.POST) My question: How can I do the same but using CBV: Currently I'm using the CreateView generic, and the form_class attr: class MyModelCreate(CreateView): model = MyModel form_class = MyFormClass How can I instantiate MyFormClass with the current user using this way. -
The relation between a model and it's form in Django, and user authentication
I'm migrating something from an old PHP/apache server to Django. I'm a bit stumped with the 'ModelForm'. As far as I understand, a "Model" is the abstraction for persistent elements in my website/server - specifically this is something stored physically, say in a database, and defines the fields (read columns) in the DB. I started moving the authentication part of the site, and discovered models, and specifically the User model (I made an empty User inheriting AbstractUser just in case I will ever need to extend things). Now I want to create a simple two field form, to authenticate login. The form: Username (which is a field of User, by default) Password (Which is not). Even the 'Username' needs a redefinition in the model form. So my questions: What is the advantage of the model form (over just a form)? - seems like you're redefining fields anyway, and obviously sometimes adding fields on top of the model. Specifically for authentication, I probably need to store my salted hash associated with the user somehow, compare my password using that and retrieve the user object. This is something I find very hard to find in the Django docs - they just have … -
Doesn't Django cache support Integers?
I am using PHP to populate my memcached, and Django to read the cache. I have made my custom make_key function in Django settings.py so that the key is same and Django doesn't modify it. def make_key(key, key_prefix, version): return key CACHE_HOST = "localhost" CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': CACHE_HOST + ':11211', 'KEY_FUNCTION': make_key } } Everything works fine while storing and retrieving strings to and from the cache. The issue came when I tried to store an integer value in memcache via. PHP using the following test snippet. $host = "localhost"; $port = "11211"; $memObj = new Memcached(); $memObj->addServer($host, $port); $memObj->set('sample_key', 123); If I query the above key directly from the cache using telnet localhost 11211, I am able to see the value. But, when I do it from Django, I get None. Following is my Django test snippet. from django.core.cache import cache print(cache.get('sample_key')) # prints None Now, if I set the key in Django, then I am able to get it as well in Django. cache.set('sample_key', 123) print(cache.get('sample_key')) # prints 123 Till this point, it was concluded that I can set the cache as integer in Django and get it in Django, PHP and Telnet, … -
how to write get and post test methods for views in django?
I'm new to Django's testing and trying to write test functions for views, but I don't get the whole test view thing, I've seen a lot of examples but it seems to be to difficult, I need an example on something I wrote to get the idea. here's a function I want to test its post and get: def ForgetPasswordRegistry(self, request): forgetpassword = True if request.method == 'GET': if 'UserID' in request.session: forgetpassword = False return request, forgetpassword elif request.method == 'POST': email = request.POST['email'] if self.IsUserExist(email): forget = models.ForgetPasswordRegistry() forget.UserID = self.GetUser(email) forget.Access = 1 session = random.randint(999999999999999, 9999999999999999999999999999999999) forget.Session = str(session) link = 'http://127.0.0.1:8000/home/resetpassword/' + forget.Session self.SendEmail('Reset-Password', link, [forget.UserID.Email]) forget.save() FeedBack = ' Check Your Mail You Got A Recovery Mail' AlertType = 'alert-success' return request, AlertType, None, FeedBack, None, None else: AlertType = 'alert-danger' ModalFeedBack = 'This Email Dose Not Exist' EmailErrors = 'This Email Dose Not Exist' return request, AlertType, forgetpassword, None, EmailErrors, ModalFeedBack -
Remove absolute path while uploading file on S3
I am trying to upload file on S3 in my bucket, using following code which is working absolutely fine. #!/usr/bin/python import os import boto import boto.s3.connection from boto.s3.key import Key from boto.s3.connection import S3Connection from datetime import datetime try: conn = boto.s3.connect_to_region('us-east-1', aws_access_key_id = 'AKXXXXXXXXXXXXA', aws_secret_access_key = 'cXXXXXXXXXXXXXXXXXXXXXXXXX2', calling_format = boto.s3.connection.OrdinaryCallingFormat(), ) print conn filename = '/home/rahul/GitDjangopostgres/AWSNewView/company/ExtraPaymentDocuments/Argus_ATM_e_surveillance/Gujarat/Ahmedabad/P3DCAM04/cecb834f-ae85-49e3-b8a1-a6nC^U)3GcZ)M62d643aa7-d047-498c-bf59-8__Invoice (7).pdf' bucket = conn.get_bucket('bucketName', validate=False) key_name = filename print "file to upload",key_name secure_https_url = 'https://{host}/{bucket}{key}'.format( host=conn.server_name(), bucket='bucketName', key=key_name) print "secure_https_url",secure_https_url k = bucket.new_key(key_name) mp = k.set_contents_from_filename(key_name) print "File uploaded successfully" except Exception,e: print str(e) print "error" Now the problem is as my file name is '/home/rahul/GitDjangopostgres/AWSNewView/company/ExtraPaymentDocuments/Argus_ATM_e_surveillance/Gujarat/Ahmedabad/P3DCAM04/cecb834f-ae85-49e3-b8a1-a6nC^U)3GcZ)M62d643aa7-d047-498c-bf59-8__Invoice (7).pdf', It's creating hierarchical bucket and storing my file. so I am getting file path as https://s3.amazonaws.com/bucketName/home/rahul/GitDjangopostgres/AWSNewView/company/ExtraPaymentDocuments/Argus_ATM_e_surveillance/Gujarat/Ahmedabad/P3DCAM04/cecb834f-ae85-49e3-b8a1-a6nC^U)3GcZ)M62d643aa7-d047-498c-bf59-8__Invoice (7).pdf.I want to change this hierarchy to https://s3.amazonaws.com/bucketName/ExtraPaymentDocuments/Argus_ATM_e_surveillance/Gujarat/Ahmedabad/P3DCAM04/cecb834f-ae85-49e3-b8a1-a6nC^U)3GcZ)M62d643aa7-d047-498c-bf59-8__Invoice (7).pdf. Is there any option to do it with boto OR should I go with python, because to upload file on s3 it requires absolute path of the file, As I am using Django and this is my celery task. -
Django Custom Interger Field validation error
I have a Custom Interger Field thats inherited using models.IntegerField CustomInteger class CustomIntegerField(IntegerField): def __init__(self, *args, **kwargs): self.readonly = readonly self.db_validator = db_validator self.validator_func = None super(CustomIntegerField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(DGIntegerField, self).deconstruct() kwargs = delete_custom_fields(**kwargs) return name, path, args, kwargs When I try to run the validations over the value there is unorderable type error # call all the validator functions for validator in field_obj.validators: try: validator(value) except ValidationError as e: print(e) Error: File "python35/root/usr/lib/python3.5/site-packages/django/core/validators.py", line 355, in compare return a < b Any help is much appreciated. Thank you -
django - CreateView - How to show a particular option as selected in dropdown
I have model as show below. class ProductGroup(models.Model): name = models.CharField(max_length=30,null=False, blank=False) category=TreeForeignKey('category.Category', null=False,blank=False) I have a CreateView as class CreateProductGroup(CreateView): model = ProductGroup fields = ['name', 'category'] My url pattern for this view is url(r'^create-group/(?P<pk>[0-9]+)/$', views.CreateProductGroup.as_view(), name='create_group'), I'm passing the category_id through url from the category_detail.html page as <a href="{%url 'create_group' object.id %}">Create product group</a> Here's my form <form method="post"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary"> Submit </button> {% endbuttons %} </form> Now, how do I show the category corresponding to the id in the url as selected in the form? -
Django Taggit cant save through admin
I am having a small issue with django admin and django taggit, when i try to save tags through django admin save_model function in my ModelAdmin class it saves the tagged element and then removes it or overwrites the element later on. There is no error with the code it just overwrites the entry later on with the value for tags in forms. I want to be able to add tags through the ModelAdmin class as i am fetching the keywords through the meta content of the link present in the model Content_Master. The get_metadata function is returning me meta keywords from the url given. Any help on this would be a big help. Thanks ! Models.py class Content_Master(models.Model): ... content_link = models.URLField(default=None, null=True, blank=True,unique= True) tags = TaggableManager(blank=True) Admin.py def save_model(self, request, obj, form, change): keyword = get_metadata(identifier = obj.content_link) obj.save() artic = Content_Master.objects.filter(content_title = title,published_date = time).values('content_id') art1 = artic[0] art = art1.values()[0] co = ContentType.objects.get(model="content_master") if keyword is not None: tagg = keyword.split(',') #print tagg for taggs in tagg: tag, created = Tag.objects.get_or_create(name = taggs) tagged = TaggedItem(object_id=art, tag=tag,content_type=co) #print tagged tagged.save() -
Run server by uWSGI for tests
I need to run a django server for some testcases. Is there any possibility to run server by uwsgi inside setUp() method and close it after tests? I tried to find some solution, but there's only information about how to run server by Linux terminal.