Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is having the SECRET KEY in an environment variable better than having it in an untracked settings file?
In a scenario where the project's settings.py file is split into base, development, and production, and only the base file is tracked in VCS. Is it a problem if the SECRET_KEY is hard-coded in the production settings file. Or will having it in an environment variable a better choice? If so, why? Is having it pulled from the system somehow more secure than written in plain text inside the file? -
How do I create an instance of a model in views.py?
I'm sorry if this is a stupid question, but I'm having trouble finding out how to create a new instance of a model inside the views. Referencing this question, I tried doing foo = FooModel() save() but I got a NameError: name 'save' is not defined. I then tried bar = BarModel.objects.create() but got AttributeError: 'Manager' object has no attribute 'Create'. Am I not understanding something very trivial? Maybe those commands are just for the command line? In that case, how do I create new objects, or filter them, etc... from code? -
Django: Queryset not saving changes to value?
Here, result is a Queryset. I am going through it and updating the value for it's price attribute to match what I get from the price_map.price value in my second query to Product.objects. This works and updates the prices accordingly. Until it goes into the .order_by method. Then, all of the values of price return to what they originally were. if sort_by in valid_sorts: for item in result: retrieved_item = Product.objects.get(name=item.name).get_pricing_info(self.request.session.get('visitors_country')) if retrieved_item['price_map'] is None: print 'we got a none here! ', item.name else: item.price = retrieved_item['price_map'].price if sort_by == 'highlow': result = result.order_by('-price') elif sort_by == 'lowhigh': result = result.order_by('price') elif sort_by == 'newest': result = result.order_by('-date','-price') elif sort_by == 'relevancy': pass If I add in some print statements for just before and just after the .order_by call, here is the output I get: Just before the order! 79.99 119.99 99.99 69.99 119.99 89.99 69.99 69.99 99.99 44.99 599.99 599.99 69.99 69.99 69.99 69.99 249.99 799.99 119.99 139.99 199.99 249.99 139.99 149.99 139.99 69.99 139.99 199.99 69.99 29.99 0.0 139.99 34.99 54.99 119.99 149.99 69.99 69.99 89.99 119.99 119.99 149.99 149.99 1699.99 69.99 249.99 39.99 39.99 39.99 599.99 999.99 199.99 49.99 119.99 119.99 249.99 99.99 99.99 199.99 69.99 99.99 … -
How to make a subcategory belong to a specific category in Django
I have a little problem with display subcategories belongs only in specific categories. For example: I have a categories: Business, Factory, Health ... and after I can add subcategories for example Own Company in category Business. In this case if I choose category Business I need to have only visible subcategories belongs to this category. How to make it? This is my code. models.py from django.db import models from slugify import slugify class Kategoria(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Nazwa kategorii') slug = models.SlugField(verbose_name='Adres SEO') class Meta: verbose_name_plural = 'Kategorie' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Kategoria, self).save(*args, **kwargs) def __str__(self): return self.name class Subkategoria(models.Model): category = models.ForeignKey('Kategoria', related_name='subkategoria', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Kategoria główna') name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Subkategorie' def __str__(self): return self.name class Strona(models.Model): name = models.CharField(max_length=250, verbose_name='Nazwa strony') slug = models.SlugField(verbose_name='Adres SEO') www = models.CharField(max_length=200, verbose_name='Adres strony', unique=True) content = models.TextField(verbose_name='Opis') category = models.ForeignKey('Kategoria', verbose_name='Kategoria', on_delete=models.CASCADE) subcategory = models.ForeignKey('Subkategoria', verbose_name='Subkategoria', on_delete=models.CASCADE) publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name_plural = 'Strony' def __str__(self): return self.name -
Am I able to create a form that is able to add a new django.contrib.auth User without logging in to the admin panel?
Have created a form but unsure if is right and also unable to add a user, it will show TypeError/ This is how the form I want it to look like The following is my coding: class Form_Add_User(forms.Form): name=forms.CharField(label="Name", max_length=50) dateofbirth=forms.DateField(label="Date of Birth", widget=forms.widgets.DateInput(format="%m/%d/%Y")) contactnum=forms.CharField(label="Contact Number", max_length=9) def adduser(request): if len(request.POST)>0: form=Form_Add_User(request.POST) if(form.is_valid()): name=form.cleaned_data['name'] dateofbirth=form.cleaned_data['dateofbirth'] contactnum=form.cleaned_data['contactnum'] new_user=User(name=name,dateofbirth=dateofbirth,contactnum=contactnum) new_user.save() return redirect('/adduser') else: return render(request,'adduser.html',{'form':form}) else: form=Form_Add_User return render(request,'adduser.html',{'form':form}) -
TypeError when creating a new user
After following this tutorial to create a signup view, I have encountered an error. Here is the view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.is_active = False new_user.save() current_site = get_current_site(request) subject = "Activate your DC-Elects account" message = render_to_string('registration/account_activation_email.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(used.id)), 'token': account_activation_token.make_token(user), }) new_user.email_user(subject, message) return reverse('elections:account_activation_sent') else: form = SignUpForm() return render(request, 'registration/signup.html',{ 'form': form, }) Here is the extended user model: class Profile(models.Model): UserID = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = (("M","Male"), ("F","Female")) Gender = models.CharField(max_length=1, choices=GENDERS) UserTypeID = models.ForeignKey(UserType, on_delete=models.PROTECT, blank=True, null=True) ProfilePicture = models.ImageField(default='default_profile.png', upload_to="imageposts/") EmailConfirmed = models.BooleanField(default=False) # For student number, can you have choices - Teacher or input()? @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Everything goes fine when filling out the form as the user, but when I submit the form, I get this error: Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\cbuch1800\Coursework\mysite\elections\views.py", line 325, in signup new_user.save() File "C:\python\lib\site-packages\django\contrib\auth\base_user.py", line … -
Javascipt error Uncaught SyntaxError: Unexpected identifier
I am making a website using HTML5 Javascript and Django 1.8 , Python 3.5 and I am getting the following error Uncaught SyntaxError: Unexpected identifier class User { constructor(nothing) { //doNothing } function myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2 } function afunc() { var mydata = "kk"; return (mydata); } } var abc = new User(); var kk = abc.myFunction(1, 2); console.log(kk); -
Django: how to fully decouple apps when it seems they are coupled?
Note: I am not a proper python programmer... but I use python extensively. I do things like write classes with inheritance, use iterators and comprehension, etc. My point is that I do not have a full grasp of the language, e.g. what exactly constitutes an python object, why __init__.py is needed other than to specify a module, etc. In relation to Django, I have written multi-app sites (with the help of S.O.) and have really enjoyed Django's templating system, blocks, and how they can be nested. Now are my apps fully decoupled and reusable? That this is subject of this post. I state this disclaimer because a lot of the Django resources seem to assume that one knows these things. This makes understanding some of the documentation and S.O. questions difficult for a person who is just an (subpower)-user. So please answer this question with that in mind. Question These questions are inspired by both the question When to create a new app with startapp in django? by @håkan and the answer given by @antti rasinen which links to James Bennett's 2008 PyCon presentation A few key points from Bennett's presentation are: sites are a collection of apps an app … -
Django app : unit tests because of django.db.utils.IntegrityError
On a Django 2.0 project, i have the following issue on my unit tests and I can't find the cause. I am implementing a model which tracks any change on another model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Investment(models.Model): """the main model""" status = models.IntegerField() class InvestmentStatusTrack(models.Model): """track every change of status on an investment""" investment = models.ForeignKey(Investment, on_delete=models.CASCADE) status = models.IntegerField() modified_on = models.DateTimeField( blank=True, null=True, default=None, verbose_name=_('modified on'), db_index=True ) modified_by = models.ForeignKey( User, blank=True, null=True, default=None, verbose_name=_('modified by'), on_delete=models.CASCADE ) class Meta: ordering = ('-modified_on', ) def __str__(self): return '{0} - {1}'.format(self.investment, self.status) @receiver(post_save, sender=Investment) def handle_status_track(sender, instance, created, **kwargs): """add a new track every time the investment status change""" request = get_request() # a way to get the current request modified_by = None if request and request.user and request.user.is_authenticated: modified_by = request.user InvestmentStatusTrack.objects.create( investment=instance, status=instance.status, modified_on=datetime.now(), modified_by=modified_by ) Most of my unit test fails with the following traceback Traceback (most recent call last): File "/env/lib/python3.6/site-packages/django/test/testcases.py", line 209, in __call__ self._post_teardown() File "/env/lib/python3.6/site-packages/django/test/testcases.py", line 893, in _post_teardown self._fixture_teardown() File "/env/lib/python3.6/site-packages/django/test/testcases.py", line 1041, in _fixture_teardown connections[db_name].check_constraints() File "/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 235, in check_constraints self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') File … -
Hide a field in a Django admin inline editor
How do you include a hidden field in an inline editor? This question suggests using form.fields['field_name'].widget = forms.HiddenInput() for an admin form, but what do I do for an inline? -
create a input box on a app using django
I am tasked with a project of creating an app with python. We have decided to use django for this purpose. Basically, I need to create an app where users can go on to a website, type their names, addresses and get the required information about their historical product purchase. Now, I am using mariadb in python to query the names. The function I created successfully gets the users name using some name matching algorithm and gets their required information. If the user misspells his/her name, the program also outputs suggested names that match what the user implied. Hence, if the user clicks on his/her name, he will get all historical purchase history for that user. I managed to use django to create a basic website. But, I want to create input boxes where users can put in their info. Do I actually go to models.py in django and create a names model? Also, is an administrative site required for this purpose? Thanks -
Django: How to show image path after saving a form?
I have a simple form with a CharField, ImageField and a TextField. When I enter text, pick an image and save the form like so: def item_new(request): if request.method == "POST": form = ItemForm(request.POST, request.FILES) if form.is_valid(): form.save() a new instance of my model with the image is saved. But in the form on my site it now says "no file selected" in the ImageField, whereas the entered text in the other fields is shown. So, how can I make it show the path of the selected file instead? -
how to redeploy django web app in docker, nginx with ssl without rebuilding or restarting container?
I am wondering if it's possible to redeploy django web app in docker, nginx with ssl without rebuilding or restarting container? I am kind of new to docker, however I feel the pain to use it. Docker looks over engineered, and wasted too much time to build and restart container. Can any one share the light on your experience? what is the good way to make it work. Currently I have the following container running and it works well. $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 74bf4112452a nginx_proxy "/bin/bash /start.sh…" 18 hours ago Up 18 hours 443/tcp, 8001/tcp, 0.0.0.0:11001->11001/tcp nginx_proxy-dev f91c7b12bbc1 myproject "/bin/bash run_mypro…" 18 hours ago Up 18 hours 0.0.0.0:32771->9000/tcp myproject-dev 21dbbb07384d nginx_balancer "nginx -g 'daemon of…" 18 hours ago Up 18 hours nginx_balancer-dev 31a5ee018f57 memcached "docker-entrypoint.s…" 18 hours ago Up 18 hours 11211/tcp my-memcache-dev -
How to fix Django AWS EC2 Gunicorn ExecStart ExecStop end error?
I am trying to point my AWS Route 53 Domain to my EC2 IPv4 Public IP for my Django app, but I'm running into some gunicorn issues. The strange thing is that I am getting gunicorn wsgi bind success, but yet it doesn't work. I've already created a record set on Route 53. Error: gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing. See the full systemctl_status Error Settings.py: ALLOWED_HOSTS = ['174.129.45.220', 'travelbudapp.com'] Please see FULL code links as .txt files: Full gunicorn.service file Full nginx file: gunicorn_bind success: I tried to make it as convenient as possible. I really need to get this app running a.s.a.p. -
How to run code a single time on django channels server startup?
Django 1.7+ has AppConfig.ready (docs), however it seems to be running multiple times with Django Channels. How can I ensure that the code runs exactly once, even with multiple workers? I'm searching for a solution that works both with the dev server and with daphne. Here is something I want to achieve: from django.apps import AppConfig from channels import Channel class MyAppConfig(AppConfig): name = 'myapp' def ready(self): # if thisIsTheFirstWorker: Channel('mychannel').send({ 'text': 'message to be sent only once', }) -
django in one queryset all and filter methods
I trying display in django app, in view last 5 item and also this items which has is_home set on True. Please hint if this is 'nice' and correct way: My model: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() is_home = models.BooleanField(default=False) My query in view: context['event_list'] = Event.objects.filter(Q(Event.objects.all()) | Event.objects.filter(is_home=True))[:5] -
Postgresql or mongoDB for Django
I am willing to work on a project, in which I have a database (xlsx files), and I want to migrate it to a nosql database in order to visulize the data in plots, and then integrate it in a django website using plotly to make the graphs. My question is, is it better to migrate to a nosql database knowing that files will be added daily, or just use a sql one like postgresql? And which is better to do the job, mongoDB or Postgresql ? NB : I ve read an artical about this, and it recommand NOT to use MongoDB in Django and I don't know whether to believe this or not. -
Celery Worker not Inheriting Settings from Django App
I am developing a django app that has to process large spreadsheets that users upload - so naturally I turned to celery and rabbitmq. I successfully setup the environment and the task completes in the background successfully except for one issue: I use an environment variable in a db router class to determine which database to use (i.e. production vs staging vs dev): lass DbRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'auth': return 'auth' elif model._meta.app_label == 'admin': return 'auth' elif model._meta.app_label == 'contenttypes': return 'auth' else: environment = environment = os.environ['BH_ENVIRONMENT_NAME'] if environment == "staging": return 'staging' if environment == "production": return 'production' def db_for_write(self, model, **hints): if model._meta.app_label == 'auth': return 'auth' elif model._meta.app_label == 'admin': return 'auth' elif model._meta.app_label == 'contenttypes': return 'auth' else: ########################################### #This is where django raises the exception# ########################################### environment = os.environ['BH_ENVIRONMENT_NAME'] if environment == "staging": return 'staging' if environment == "production": return 'production' def allow_migrate(self, db, app_label, model_name, **hints): return True which works just fine in the regular django thread; however, when the background task attempts to use the db router I get the following key error (which seems to imply that os.environ dictionary is not available to the worker thread?): … -
Django Admin page error with MySQL
I have some issue with connecting my Django 2.0 with MySql: When I am checking my localhost on xampp server locally, it looks data entered and connected with my project but the below is the error that showing when I want to see my admin page: ProgrammingError at /admin/ (1146, "Table 'scdemployees.django_session' doesn't exist") Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.2 Exception Type: ProgrammingError Exception Value: (1146, "Table 'scdemployees.django_session' doesn't exist") Exception Location: C:\Users\Janahi\venv\Django_me\lib\site-packages\MySQLdb\connections.py in query, line 277 Python Executable: C:\Users\Janahi\venv\Django_me\Scripts\python.exe Python Version: 3.6.3 Python Path: ['C:\\Users\\Janahi\\PycharmProjects\\Django_me', 'C:\\Program Files\\JetBrains\\PyCharm 2017.3\\helpers\\pycharm', 'C:\\Users\\Janahi\\PycharmProjects\\Django_me', 'C:\\Users\\Janahi\\venv\\Django_me\\Scripts\\python36.zip', 'C:\\Users\\Janahi\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Janahi\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Janahi\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Janahi\\venv\\Django_me', 'C:\\Users\\Janahi\\venv\\Django_me\\lib\\site-packages', 'C:\\Users\\Janahi\\venv\\Django_me\\lib\\site-packages\\setuptools-28.8.0-py3.6.egg', 'C:\\Users\\Janahi\\venv\\Django_me\\lib\\site-packages\\pip-9.0.1-py3.6.egg'] Server time: Fri, 16 Feb 2018 15:04:28 +0000 -
Adding header with value django cores
According to the django-cores documentation in order to add custom headers you add: CORS_ALLOW_HEADERS = default_headers + ('my-custom-header',) To your settings.py, question is how do you add my-custom-header along with it's value to settings.py. -
Should I go with Django/mongoDB or PHP (Laravel) /mongoDB or any other languages?
I need to create a scalable backed system for my sales team that have more than 50 millions data. Also having multiple heavy (8 million) csv operations (upload). Should I go with Django/mongoDB or PHP (Laravel) /mongoDB or any other languages? -
Django 1.11.9 and PosgreSQL10 on Docker makes duplicated tables
Today I got a weird behaviour. I am not sure this problem comes from AWS EC2 or Django itself. Today AWS shows me significant lack and poor performance. I use PostgreSQL10 on Docker And what should I do with replicated tables? I can not Drop it. I had tried. -
AJAX DJango Get files from multiple file field
I'm doing multiple file upload with AJAX and DJango and I have problem. How to get files from field input and push them to data ? HTML: <form id="add_photos" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file[]" multiple id="files"> <input type="submit" name="submit" value="Submit" /> </form> JS: function formSubmit(e) { e.preventDefault(); $.ajax({ method: 'POST', data: form.serialize(), url: '.', success: function(data) { console.log(data); }, error: function (data) { console.log(data); } }); } -
Ajax POST request from Chrome extension to django fails with 400
I have a Django REST API running on Nginx + Gunicorn on my server (an AWS instance) and I'm trying to call this API from a Chrome extension using Ajax. I can't make it work. The API itself seems to work fine – I can make a similar request with cURL and it works fine. However, when I try to do it from the extension, I'm getting 400 error. There is no authentication at the moment, both the website from which I'm calling and the Django app run on https (at first I thought this might be a problem), I added both of them to permissions in manifest.json. My call (from background.js) looks like this: $.ajax({ type: "POST", crossDomain: true, cache: false, url: 'https://**************/', data: JSON.stringify(collectedData), success: function(data, textStatus, xhr) { collectedData = []; server_response = xhr.status; }, error: function(xhr, textStatus, error) { server_response = xhr.status; }, dataType: "json" }).always(function(){ sendResponse({ status: server_response }); }); I'm running out of ideas. What am I doing wrong? -
400: Bad Request when retrieving Request Token from Twitter API
I'm working on a Django application which retrieves some data from Twitter, and I need to work with requests manually since it's for an exam whose main focus is for us to learn how to work with network protocols such as HTTP. So please don't suggest me to use a wrapper. My issue is that whenever I try to request the initial request token (with a POST request that is referenced in this doc and also here), I receive a 400: Bad Request and I have no clue what could be causing it. It may be that while working with urllib I don't manage to make the POST request as I wanted, even though in my opinion it should be alright. Here's my code to handle the request to "sign in with Twitter": def sign(request): url = 'https://api.twitter.com/oauth/request_token' #I store consumer key, consumer secret and callback url in a txt dir_path = path.dirname(path.realpath(__file__)) with open(path.join(dir_path, 'credentials.txt'), 'r') as TweetCred: creds = TweetCred.read().split(linesep) oauth_consumer_key = creds[0].split()[1] oauth_callback = creds[1].split()[1] consumer_secret = creds[2].split()[1] oauth_nonce = ''.join(SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(32)) #Desperate to understand what could be causing the error, I tried to use an integer timestamp sinceit was integer in …