Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django cms add own model in admin panel
I made new app named "pricing"(manage.py startapp pricing). Frontend works fine. Now i want to add extra field in my django-cms admin, where user can store,change,add new values in Db for this app. With few words: I want to register model from my app to django-cms admin.I want to appears at bottom of admin page. mycms: mysite static templates **pricing(my app) templates admin.py models.py test.py views.py** cms_plugins.py forms.py models.py settings.oy urls.py views.py pricing app models.py from django.db import models # Create your models here. class Post(models.Model): introduction = models.CharField(max_length=200) offer_option = models.TextField() prop_one = models.TextField() prop_two = models.TextField() prop_three = models.TextField() price = models.TextField() period = models.TextField() def __str__(self): return self.offer_option views.py from django.shortcuts import render from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.all() return render(request, 'post_list.html', {'posts': posts}) admin.py from django.contrib import admin # Register your models hefrom django.contrib import admin from .models import Post admin.site.register(Post) -
Rendering PDF documents in bulk in Django
I need to generate a whole heap (~200) of PDF docs through Django and am looking for suggestions (or a library) to do this. There needs to be a view for each individual document, but will periodically need to download all of the pdfs generated by this view from a particular filter. I can see these possible approaches: Generate a single document - this is easy, but I would prefer individual documents Generate one document with a 'download' content-disposition, then redirect to the next one (not sure if this will work for 200 docs?) Generate/cache all docs on the server in a background task, then provide a zip-file link, or save to an external storage such as Google Drive. For the third option, what PDF libraries are well suited to provide both programmatic rendering in a background task, but also make it easy to view a single document on-demand? Any other thoughts? -
How to convert a text keys into hex in Django and viceversa?
I am trying to save a long text in hex format in Django database. This are some secret keys. Also at some point I want to convert them to text again. def import_keys(request): if request.method == "POST": secrets = request.POST['text_file'] some = secrets.encode("hex") Keys.objects.create(hexa=some) -
Django Celery Beat admin updating Cron Schedule Periodic task not taking effect
I'm running a site using Django 10, RabbitMQ, and Celery 4 on CentOS 7. My Celery Beat and Celery Worker instances are controlled by supervisor and I'm using the django celery database scheduler. I've scheduled a cron style task using the cronsheduler in Django-admin. When I start celery beat and worker instances the job fires as expected. But if a change the schedule time in Django-admin then the changes are not picked up unless I restart the celery-beat instance. Is there something I am missing or do I need to write my own scheduler? -
Django widget does not get constructed in ModelForm
I am trying to use the chosen jQuery plugin with django, so I created this widget: class ChosenWidget(widgets.Select): class Media: css = { 'all': ( 'sub/staticfull/css/plugins/chosen/chosen.css', ) } js = ( 'sub/staticfull/js/jquery-2.1.1.js', 'sub/staticfull/js/plugins/chosen/chosen.jquery.js', ) def render(self, name, value, attrs=None, choices=()): super(ChosenWidget, self).render(name, value, attrs=attrs) return rendered + mark_safe(u''' <script> $(document).ready(function () { $('#id_%(name)s').chosen() }) </script>''' % {'name': name}) and I am trying to use it in a generic CBV: class DomainUpdateForm(forms.ModelForm): class Meta: model = Domain fields = ['goal', 'lead_person', 'rank', 'type', 'sets'] widgets = { 'sets': widgets.ChosenWidget(), } class DomainUpdate(UpdateViewParent): form_class = DomainUpdateForm model = Domain The widget works except select element don't get multiple="multiple" and initial values are not there/selected. Seems like widget did not get constructed, as if it was the default widget. What am I missing? -
How to deploy Django app on Ubuntu when using Gitlab
I have create a simple Django application, then I have commit and push to Gitlab. Finally I would like to install that application on my "production server" which is running ubuntu so from that server terminal I run the command: git clone https://domain.com/path/to/git I cannot find my python code among the file cloned. What is the correct way to get the python code from the gitlab repository? -
Django models ForeinKey to abstact class
I'm making simply rpg browser game and I want to do this: #Basic class class AbstractClass(models.Model): health = models.IntegerField(default=10) mana = models.IntegerField(default=10) And I have few profession class like class WarriorClass(AbstractClass): strength = models.IntegerField(default=20) intelligence = models.IntegerField(default=10) class MageClass(AbstractClass): strength = models.IntegerField(default=10) intelligence = models.IntegerField(default=20) And in UserProfile model class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile' ) profession = #??? And I don't know what should I do in profession field. I want to something like ForeingKey (but during creating new instance I want to specify to which class (mage or warrior) should be this ForeignKey. How can I do this? Or maybe you guys have bettere idea to do mini system like this? Best -
I got a postgresql db that works but on host/admin (in the browser) i get a no such table : auth_user
i'm using django with my postgresql database. When i use manage.py makemigrations and migrate everything works fine. I can create objects in the shell and save them. However when i try to get to the admin page on my browser and log in as a superuser, i get a no such table : auth_user error I saw this in the error page : "Exception Location: /usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py in execute, line 450 Python Executable: /usr/bin/python" It seems like the admin page is using a sqlite3 db oO I didn't find a solution on the internet yet -
How can i access this JSON data in Django?
Code i used in fetching the data url = 'https://api.some-random-url.com/users/amarlearning' serialized_data = urllib2.urlopen(url).read().decode("utf-8") data = json.loads(serialized_data) Returned JSON [ { id: "4859421681", type: "IssueCommentEvent" }, { id: "4859421681", type: "IssueCommentEvent" }, { id: "4859421681", type: "IssueCommentEvent" } ] Now In django Template i am doing this {{ data[0]['type'] }} Getting Template error, while i was accessing Json data in Django template! -
Django forms - input boxes not rendering in template
I can't get my form to show up on my rendered template. The submit button is there but nothing else. I have two forms, one works fine its the EstimateForm I can't get to show. This is the template <form role="form" action="" method="post" class="contact-form" style="margin-top: 25px"> {% csrf_token %} {{ estimate_form.as_p }} <button type="submit" class="thm-btn">Submit</button> </form> This is what gets rendered <form role="form" action="" method="post" class="contact-form" style="margin-top: 25px" novalidate="novalidate"> <input type="hidden" name="csrfmiddlewaretoken" value="lfudMn6U8TBJ2czhZM4UZTINnP6xoLZs"> <button type="submit" class="thm-btn">Submit</button> </form> Forms. py class ContactForm(forms.Form): contact_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Name*'})) contact_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Email*'})) contact_phone = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Phone Number*'})) content = forms.CharField( required=True, widget=forms.Textarea(attrs={'placeholder': 'Your comments'}) ) class EstimateForm(forms.Form): contact_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Name*'})) contact_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Email*'})) contact_phone = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Your Phone Number*'})) def __init__(self, *args, **kwargs): super(BottomForm, self).__init__(*args, **kwargs) self.fields['contact_name'].label = "" self.fields['contact_email'].label = "" self.fields['contact_phone'].label = "" views.py def contact(request): form_class = ContactForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') contact_phone = request.POST.get( 'contact_phone' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = Context({ 'contact_name': contact_name, 'contact_email': … -
Get Django Project requirements.txt in Pycharm
I'm trying to get, without success, the requirements.txt from the virtual environment I created in Pycharm for a Django Project. My Pycharm version is 2016.2, Django 1.10.3 and Python 3.5.1. First attempt: Using Python Console - Didn't work because it automatically runs the Django shell instead. I've even tried changing the starting script in the Settings but the Django console is always opened instead of the Python one. Second attempt: Using the Terminal - Didn't work because I can't workon the virtual environment (it simply doesn't exist for the terminal) Question: How can I get the Python terminal (where I can do pip freeze)? or How can I do workon env_name when lsvirtualenv gives me no environments? -
Delete Django Migrations
I changed databases from mysql to postgre. Since there was no data in teh db yet, I just deleted the migrations folders for each of the apps. When I ran makemigrations afterwards though, I got this error: /theme/admin.py", line 2, in <module> from models import theme, theme_file ImportError: No module named 'models' Everything worked fine before, nothing changed in the code other than the migrations folders being cleaned. Any ideas? -
Integrate Google Maps API in django template
I have a query returning long/lat parameters of cities and would like to display a map in the template.. Following Google instructions, I cannot understand where to paste the javascript code. FollowingThis is how I did: Created the map div in the html template (extended from base.html) Pasted the scrpit with API key in the javascript.html template and added the javascript script in a map.js file in the static folder.. Console shows: "initMap is not a function" Can anyone help? -
django - how to pass datetime arguments to forms construct
i want to filter serve_date field in Reserve modelform. when run this form, return: expected string or buffer class Reserve(forms.ModelForm): food_name = forms.ModelChoiceField(queryset=Food.objects.all()) def __init__(self, year=None, month=None, day=None, serve_date=None, *args, **kwargs): super(Reserve, self).__init__(*args, **kwargs) self.year = year self.month = month self.day = day self.serve_date = serve_date date_stamp = time.strptime(serve_date,"%Y%M%d") serve_date = datetime.date(*date_stamp[:3]) self.fields['food_name'].queryset = Food.objects.filter( serve_date__year = year, serve_date__month = month, serve_date__day = day) class Meta: model = Reservation fields = ('food_count', 'food_name') Food model: class Food(models.Model): class Meta: verbose_name = "Food" verbose_name_plural = "Foods" def __unicode__(self): return self.food_name food_name = models.CharField(verbose_name="Food Name", max_length=50) price = models.CharField(verbose_name="Food Price", max_length=50) serve_date = models.DateTimeField(verbose_name="Serve Date") -
how to make forms fields attribute required to depend on selected button value
I have a template with three radio buttons. I want to set fields A and B required=Ttrue only if radio button has value 1. If the radio button has value 2 I want to set required=True for field C. Here is the code: def clean(self): #TODO this requires a proper validation cleaned_data = super(UpdateForm, self).clean() selected_radio_button= int(cleaned_data.get('selected_radio_button')) if selected_radio_button == 1: self.fields['A'].required = True self.fields['B'].required = True elif selected_radio_button == 2: self.fields['C'].required = True It dosent work. But I hope that you get my idea. -
Raspberry Pi and Django - Background check GPIO Button
I'm having troubles to get this thing work. Basically i have my raspberry, with apache and django running good, in my views i can turn on and off a led using gpiozero, i can do pretty much every output thing i want with gpio pins. But there is this thing i can't do: How to get input from gpio pins? I tried setting up Celery but there are 2 problems, i can't make it work how i want (after 3 days of tests looking 10 different guides, even official ones) and it doesn't do exactly what i want. Celery can do background process only when they are called in a django view. What i want to do is having a background process that run 24/24 that watch pin input activity. Simple example: When the button connected on gpio 23 is pressed, change a value in a django model or turn on another gpio pin. Someone with a hint? Thanks all! -
Django filter against list with and
So what im trying to do is filtering against a list that comes from the queries and returning the possible options. I got three models: class Category(models.Model): title = models.CharField(max_length=60, unique=True) class Colors(models.Model): title = models.CharField(max_length=40, unique=True) class Post(models.Model): title = models.CharField(max_length=40) colors = models.ManyToManyField(Color) category = models.ForeignKey(Category) is_active = models.BooleanField(default=True) Now what I want to do is following: Get all Posts where is_active == True Get all Posts where colors are contained in queries Get all Posts where category is same as the one in query My attempt looks like this: # to be able using multiple values like ?color=red&color=blue&color=yellow queryparams = dict(request.query_params.lists()) colors_list = [] categories_list = [] if 'color' in query_params: colors_list = query_params['color'] if 'category' in query_params: categories_list = query_params['category'] posts = Post.objects.filter(is_active=True) if colors_list: for color in colors_list: posts = posts.filter(colors__title=color) if categories_list: for category in categories_list: posts = posts.filter(category__title=category) colors_options = posts.order_by('colors__title').values_list('colors__title', flat=True).distinct() categories_options = posts.order_by('category__title').values_list('category__title', flat=True).distinct() The options part currently doesnt work how I would like it to do. Lets say I got 5 objects with following colors: black, blue, white, yellow black blue, red, white red, white, yellow black, yellow If I would search with ?color=red&color=white it should give me following options: … -
can we pass array/list to partial views in django? python
I know we can pass variables to partial views but are we able to pass list? I know we can pass variables in this way {% include "partials/pickUp-Order-Form.html" with form="form" %} I tried passing list like this {% include "partials/pickUp-Order-Form.html" with form=["list", "test"] %} this wouldn't work though. I searched up and there doesn't seem to have such thing in documentations. -
stripe api not picking my live key in settings
I have set up a model in django code is: #Stripe class UserStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) stripe_id = models.CharField(max_length=120) def __unicode__(self): return str(self.stripe_id) def get_or_create_stripe(sender, user, *args, **kwargs): try: user.userstripe.stripe_id except UserStripe.DoesNotExist: customer = stripe.Customer.create( email = str(user.email) ) new_user_stripe = UserStripe.objects.create( user=user, stripe_id = customer.id, ) except: pass user_logged_in.connect(get_or_create_stripe) I have changed my api key to the live code in settings and even deleted the old test api key in stripe. But the app is still using the old api and i am getting the following error all the time. AuthenticationError at /accounts/login/ Expired API Key provided: sk_test_********************IddZ Request Method: Django Version: 1.8.4 Exception Type: AuthenticationError Exception Value: Expired API Key provided: sk_test_********************IddZ Exception Location: /app/.heroku/python/lib/python2.7/site-packages/stripe/api_requestor.py in handle_api_error, line 163 Python Executable: /app/.heroku/python/bin/python Python Version: 2.7.12 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python27.zip', '/app/.heroku/python/lib/python2.7', '/app/.heroku/python/lib/python2.7/plat-linux2', '/app/.heroku/python/lib/python2.7/lib-tk', '/app/.heroku/python/lib/python2.7/lib-old', '/app/.heroku/python/lib/python2.7/lib-dynload', '/app/.heroku/python/lib/python2.7/site-packages', '/app/.heroku/python/lib/python2.7/site-packages/setuptools-25.2.0-py2.7.egg', '/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg'] Server time: Sun, 13 Nov 2016 17:25:32 +0000 Any ideas: -
Django display and style model data
The problem is, i would like to display the data as in the picture below: https://camo.githubusercontent.com/59f8d2f58b1c39886cf042a21fd59a3f7aa33a2e/687474703a2f2f692e696d6775722e636f6d2f394978324362522e706e67 So that there will be a picture and some details under it. My model looks like this: class Member(models.Model): image = models.ImageField(upload_to='images') title = models.CharField(blank=True, max_length=150) firstname = models.CharField(max_length=50) lastname = models.CharField(blank=True, max_length=50) It should be ordered by the firstname and I will also need a pagination later. I would very appreciate some help with the template! -
Django Automatic database routing doesn't working
I follow doc form django official below https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#automatic-database-routing I try the Automatic database routing. my setting is like that #settings.py DATABASES = { 'default': {}, 'blog': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testdjango', 'USER': 'dany', 'PASSWORD': '****', }, 'zipcode': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'zipcode', 'USER': 'dany', 'PASSWORD': '****', } } DATABASES_ROUTERS = ['blog.router.ZipcodeRouter'] blog/router.py class ZipcodeRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'zipcode': return 'zipcode' return 'blog' def db_for_write(self, model, **hints): if model._meta.app_label == 'zipcode': return False return 'blog' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'zipcode' or obj2._meta.app_label == 'zipcode': return False return 'default' def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'zipcode': return False return True blog/models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title zipcode/models.py class Gyeonggi(models.Model): new_zipcode = models.CharField(max_length=20) city = models.CharField(max_length=20) ... old_zipcode = models.CharField(max_length=10, blank=True, null=True) zipcode_code = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'gyeonggi' Now I try on QuerySet form python manage.py shell from zipcode.models import Gyeonggi Gyeonggi.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File … -
Decoding an image (64 bit string) sent from Swift with Python?
I'm trying to take an image with Swift, encode a base64 string, send it to a Django app, and recreate the image from that. However, all the images I've had have been unusable. Here's my Swift code: let imageData = UIImagePNGRepresentation(image) let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) let postString = "image=" + base64String request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) And here's my Python code: base64_data = request.POST.get('image') with open("melanie/images/%s.jpg" % image_name, "wb") as img: img.write(base64_data.decode('base64')) Can anyone help me figure out where I'm going wrong? -
Error shows when opening saved image in django admin
I am facing some very basic issue. I saved some detail in my django model including a profile picture. When i open django admin then i can saw i link for the image which i have saved.But when i click on that link it show me error.My image is not founding. How can i resolve the issue. settings.py STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "staticfiles"), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') link showing me in django admin media/media/ind_kQRDi6b.jpg when i hit enter to open this this image it hit 127.0.0.1/8000/media/media/ind_kQRDi6b.jpg And error show Page not found -
Data processing is very slow in Django
I am actually quite new for web application development. Now I want to build a web service to process some geographic vector data in real-time. Before I started to develop that web app, I wrote a Python script to do that data processing, and the test shows that the processing usually takes 0.1-2 sec. Afterwards, I moved the codes of that processing in my web app's service side which is in the Django framework in Python, and I put that process in a view, and then when a uses opens that view in web browser, the code of that process would run and send the result to client-side. However, I found this process in the service side unexpectedly took around 10 mins. Therefore, my question is why that process becomes so slow when it is moved into the service side's Django framework. I would be very grateful if someone could help me out. -
How to create 3 way ManyToMany relationship django
Need to model the relationship between servers, applications, and server role, in django admin. Server can have one or many applications An application can be hosted on one or many servers A Server has one or many roles for an app (DB server role, WEB server role, etc.) How can I create the proper relationship for this? Here is what I am thinking. class Application(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Server(models.Model): name = models.CharField(max_length=200) apps = models.ManyToMany('Application', related_name='servers') class ServerRole(models.Model): name = models.CharField(max_length=200) servers = models.ManyToMany(Server, related_name='serverrole')