Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I use plain Python code or Celery? Django.
I have a heavy function (a lot of calculations are done) which outputs a individual number for each user in my Django project. This number changes just a little over time so to minimize the server load I thought about running the function once a day, save the output and just reference the output. I know that these kinda things are usually handled with Celery but the package requires a lot of site packages and extra modules so I thought about writing a simple function like: x0 = #last.time function was called x1 = datetime.now if x0-x1 > 1 day: def whatever(): .... x0 = datetime.now return .... I like to keep my code clean and not to install Packages which are not really required so I would like to know if there are any downsides by "just" using Python or any gain when I would do that with Celery. The task does not need to be asynchronous so I don't care about that. Is there a clear "Use case" when Celery should be used and when not? Is there a performance loss/gain? I hope somebody can explain that properly. -
Implement Django __iin custom lookup
I read the Django documentation on custom lookups, but failed to figure out how to implement a case-insensitive __in lookup. Anyone who can help? I'm on Django 1.10 with a Postgresql database. -
Django FileBrowseField upload form
I have an Artwork and ArtworkPhoto model in Django. Artworkphoto has an FK to the Artwork and stores some additional data on the photo. class ArtworkPhoto(models.Model): title = models.CharField(max_length=200, verbose_name='Omschrijving', blank=True) photo = FileBrowseField("Image", max_length=200, directory="artwork/", extensions=[".jpg", ".png"], blank=False, null=False) artwork = models.ForeignKey(Artwork, null=False, verbose_name='kunstwerk') Every Artwork has X photos, all working fine. Now I want to provide authenticated visitors with an upload form to add an artwork and photo's. How can I save a posted file to the ArtworkPhotoModel? It's a Grapelli FileBrowser > Filebrowsefield ... Thanks, i'm a bit stuck here. ... -
JQuery/Django Syntax error
I know there is some dumb error I'm missing. Pycharm/Brackets hasn't been able to help, and I've combed it a dozen times. The idea is when someone clicks on a reservation slot (slot), they can either reserve it, clear it, or be blocked because someone already has it. The error returned is "SyntaxError: missing : after property id" for line 41, which is "console.log()". I've been reading and it's probably a syntax error elsewhere, but I'm stumped. #views.py @ensure_csrf_cookie def reserve(request): if request.is_ajax(): pk = request.POST['pk'] slot = Event.objects.get(pk=pk) user = request.user if slot.is_reserved == True: if user == slot.teacher: slot.is_reserved = False slot.teacher = None slot.save() result = "clear" else: result = "blocked" else: slot.is_reserved = True slot.teacher = user slot.save() result = "reserved" result = {'result': result} return HttpResponse(json.dumps(result, cls=DjangoJSONEncoder)) //main.js function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajaxSetup({ beforeSend: … -
Heroku Internal Server Error No error in log
I am trying to push to heroku but I am receiving internal server error. My host in settings.py ALLOWED_HOSTS = ['127.0.0.1',".herokuapp.com"] I have no idea where to go from here or where should i check? 2017-08-20T14:16:18.985003+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath omw omw.wsgi` 2017-08-20T14:16:21.496816+00:00 app[web.1]: [2017-08-20 14:16:21 +0000] [4] [INFO] Starting gunicorn 19.6.0 2017-08-20T14:16:21.497287+00:00 app[web.1]: [2017-08-20 14:16:21 +0000] [4] [INFO] Listening at: http://0.0.0.0:50026 (4) 2017-08-20T14:16:21.497414+00:00 app[web.1]: [2017-08-20 14:16:21 +0000] [4] [INFO] Using worker: sync 2017-08-20T14:16:21.502041+00:00 app[web.1]: [2017-08-20 14:16:21 +0000] [9] [INFO] Booting worker with pid: 9 2017-08-20T14:16:21.567640+00:00 app[web.1]: [2017-08-20 14:16:21 +0000] [11] [INFO] Booting worker with pid: 11 2017-08-20T14:16:22.694603+00:00 heroku[web.1]: State changed from starting to up -
django admin/options.py TypeError: 2 options needed, 3 given
I needed some custom logic to happen before deleting a pages model, so I overloaded the delete() method. (I know this is bad form. I fixed it later, but it's important to express how I got into this mess) With something like this: def delete(self, *args, **kwargs): super(Pages, self).delete() Unfortunately, this caused the following TypeError when I tried to delete the page via the admin interface: delete_model() takes 2 positional arguments but 3 were given I decided that I needed to do things properly, and so I deleted the delete method overload, and implemented pre_delete logic via the following signal handler: @receiver(pre_delete, sender=Pages) def handle_page_delete(sender, **kwargs): obj = kwargs['instance'] if(obj != None): tmp1 = obj.prev_id tmp2 = obj.next_id if(tmp1 != None): tmp1.next_id = tmp2 obj.prev_id = None if(tmp2 != None): tmp2.prev_id = tmp1 obj.next_id = None I followed best practices by putting the handler in a signals sub-module and by registering it via ready() in an overloaded AppConfig in apps.py. Unfortunately, I still got the same error: TypeError delete_model() takes 2 positional arguments but 3 were given I then re-implemented the overloaded delete function as a stub, thinking that maybe I just needed to put the proper options in. So, … -
Django LookupError: App 'accounts' doesn't have a 'User' model
After upgrading from Django 1.10 to 1.11, I've been receiving an issue when doing just about anything. I can't start my server, nor run manage.py. Before upgrading, I did not receive this issue so I am not sure what's changed since then that would cause this issue. I've also already tried deleting the database, nothing's changed. My settings.py AUTH_USER_MODEL/INSTALLED_APPS: AUTH_USER_MODEL = 'accounts.User' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'forum.apps.ForumConfig', ] My User model: class User(AbstractUser): profile_picture = models.ImageField(null=True, blank=True) birth_date = models.DateField(null=True, blank=True) The error: > Failed to get real commands on module "CsForum": python process died with code 1: Traceback (most recent call last): File "C:\Users\Elian\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 169, in get_model return self.models[model_name.lower()] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Elian\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\__init__.py", line 193, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "C:\Users\Elian\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 205, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "C:\Users\Elian\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 172, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'accounts' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2017.2.1\helpers\pycharm\_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "C:\Users\Elian\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", … -
Django: How to create a record in different app/model post saving the data in current model
Following are my apps and respective models: Project name: django03 app: home home/model.py from __future__ import unicode_literals from django.db import models from django.conf import settings # Create your models here. User = settings.AUTH_USER_MODEL HOME_TYPE = ( ('1','1'), ('2','2'), ('3','3'), ) class Home(models.Model): home_owner = models.ForeignKey(User,null=False, verbose_name='Owner') hometype= models.CharField(max_length=100, null=False, default=1, choices=HOME_TYPE, verbose_name='Home Type') licenseid= models.CharField(max_length=200, null=False, unique=True, verbose_name='License ID') archive = models.BooleanField(default=False) def __str__(self): return self.licenseid app: furniture furniture/model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models # Create your models here. User = settings.AUTH_USER_MODEL FURNITURE_DATA_IMPORT_SOURCE= ( ('0', '0'), ('1', '1'), ('2', '2'), ) class Furniture(models.Model): furniture_owner = models.ForeignKey(User, verbose_name='User') furniture_imported_via = models.CharField(max_length=200, default="0", null=False, choices=FURNITURE_DATA_IMPORT_SOURCE, verbose_name='Source of import') furniture_title = models.CharField(max_length=100, null=False, verbose_name='Furniture title') furniture_description = models.TextField(max_length=250, verbose_name='Furniture description') archive = models.BooleanField(default=False) def __str__(self): return self.furniture_title app:mappings mappings/model.py from __future__ import unicode_literals from django.db import models from home.models import Home from furniture.models import Furniture class HomeFurnitureMapping(models.Model): home = models.OneToOneField( Home, on_delete=models.CASCADE, null=False, unique=True, verbose_name='Home' ) furniture = models.OneToOneField( Furniture, on_delete=models.CASCADE, null=False, unique=True, verbose_name='Furniture' ) app: furnitureupdates furnitureupdates/model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from mappings.models import HomeFurnitureMapping # Create your models here. class … -
Printing a PDF file in Django
I want to create something in my Django project that physically prints a PDF file in the FileField of a model object onto paper. Like so: class PDF(models.Model): pdf = models.FileField(upload_to='pdffiles/', blank=True, null=True} The main thing I want to do is make a link that creates a popup using Javascript that contains an input field where the user puts the name of the PDF from the object's FileField and a button that says "Print" that triggers the physical printing function (including opening the Print Dialog Box). Am I supposed to use forms or views in order to make this function, and if I'm supposed to use Javascript to activate the printing function, how would I do it? Thanks. -
Django - Login required redirect url
If the user is not logged-in, I want it to redirect to the admin page and when the user logs in, he should be redirected to the previous url. This is how I'm doing:- LOGIN_URL = '/admin' LOGIN_REDIRECT_URL = '/admin' The user does get redirected to admin page but after logging in, the admin dashboard is open, not the next url. That's because the url is not exactly what django is expecting. This is how the url looks like. http://127.0.0.1:8000/admin/login/?next=/admin/%3Fnext%3D/movies/fav%253Fpage%253D1 What am I missing? -
Using Django, how can I detect an admin in my javascript?
I have functions in my JavaScript which I would not like to be available to normal users, and only to admins/staff. Note: I'm not trying to disable them for security, but only for user experience. Ideally I can create a boolean variable which is true/false depending on whether the request user is staff or not, but how would I set this boolean? -
I'm trying to integrate disqus in my project but ended with error
the error I've got is : RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. My setting file is like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] SITE_ID = 1 DISQUS_API_KEY = 'kLA0JWWljFwKTHvSym2oSRIlBSDCZZmReyx9NeIzPz48rtwS6Ew2vVewmZgupsea' DISQUS_WEBSITE_SHORTNAME = 'foobar' -
Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279
** Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279** I am getting this error when i am installing mysqlclient or mysql-python by pip install mysqlclient i have updated everything and not using any of the visual studio produsct using sublime text please help me ! -
Django template - including template that doesn't exists
I just deployed a django app that worked fine on my local machine. After deploying it I noticed that some pages do not work any longer. The pages seem to not include the header although the header file include is present in the template files and has not changed: {% include 'app/partials/header.html' %} In the rendered HTML response the part where header.html contents should appear is just empty. I tried the following to identify the issue: I checked the log files: No error I reloaded apache and cleared all caches I checked the 'header.html's contents I checked the 'header.html's permissions I reuploaded the 'header.html' I RENAMED the 'header.html' This is where it becomes curious, because the page still loaded (without the header.html contents) but didn't return any errors. On my local machine django raises a TemplateDoesNotExists error when I rename the header.html file (which ist the expected behaviour). The server seems to simply ignore the "include" tag - otherwise an error should be thrown. The included footer.html on the same site work fine. Any ideas where to investigate further? I simply cannot imagine any reason for this behaviour. -
MemoryError when passing big QuerySet from Views to Template (Django, PostgreSQL)
I'm building a GIS-related web application, and the way it displays the contents of the database on a map is pretty straightforward: the view collects several (currently 122) GeoJSON files and passes them to the template. The template iterates all of them and displays them (using Leaflet). However, I cannot manage to make it work, as every attempt results in a Memory Error. The database I'm using is a PostgreSQL one, in case it helps. I'm also using a TextField in the model, is it possible that to be source of the issue? Any advice will be much appreciated :) The view: geodata = GeojsonData.objects.filter(connection = my_con).iterator() view = "map" return render(request, "map.html", {'geojsonData': geodata}) The template: {% for dat in geojsonData %} {% with dat.name as name %} {% with dat.geodata as gj %} {{gj}} L.geoJSON(name).addTo(map); {% endwith %} {% endwith %} {% endfor %} The model: class GeojsonData(models.Model): name = models.CharField(max_length=2000, unique=True) connection= models.ForeignKey(Connection, related_name='Connection', default=1) geodata = models.TextField() The traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/map/1/ Django Version: 1.11.4 Python Version: 3.6.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.myappConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. … -
How can I make a specific login for specific group with Django's `authenticate()`?
Hello I have been looking through the documentation in https://docs.djangoproject.com/en/1.11/topics/auth/default/#authenticating-users. However, it shows only how to authenticate all User. I have grouped some my User now I want only specific User to login in a specific form. How can I achieve that? Additionally, when should I use Permissions and when should I use Groups? -
Django, capturing client IP getting
I am trying to capture a client IP and store that into a log in my database, I have tried using packages like ipware but I am still getting the same error when I run my application File "/Users/abdul/Documents/tutorial/drftutorial/urls.py", line 2, in <module> from . import views File "/Users/abdul/Documents/tutorial/drftutorial/views.py", line 24, in <module> class UserCreateView(generics.CreateAPIView): File "/Users/abdul/Documents/tutorial/drftutorial/views.py", line 27, in UserCreateView ip=get_client_ip(request) File "/Users/abdul/Documents/tutorial/drftutorial/views.py", line 17, in get_client_ip x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') AttributeError: 'module' object has no attribute 'META' I believe the error Is happening because I am not accessing the request method properly, I am using Django-restframework and the tutorial I followed did not pass the request object when calling the view. here is my code: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip class UserCreateView(generics.CreateAPIView): action = 'User registered' response1 = 'Success' ip=get_client_ip(request) print ip if ip is not None: ip="could not get IP" else: print(" got the IP!") print (" I am here!") Logadd(action,response1,ip) serializer_class = UserSerializer -
why '^(?[0-P<id>9]+)/$' is not a valid regular expression in django?
i just created a new different url and view.after that this error is showing.. the newly created url and views are the following url(r'^$',views.DeleteContent,name="delete"), View : def DeleteContent(request,id): if not request.user.is_authenticated(): return redirect('accounts:login')` todo = get_object_or_404(ToDo, id=id) todo.delete() return render(request,"index.html") -
send ajax to a django application from static html with CSRF
I want to submit a form in an HTML static page and send the data to a django application, using JQuery $.ajax function. How can I add a CSRF token to the form to be accepted by Django? -
Django models: Fields name clashes
I am facing an error in one of my Django practice projects. Following are my apps and respective models: Project name: django03 app: home home/model.py from __future__ import unicode_literals from django.db import models from django.conf import settings # Create your models here. User = settings.AUTH_USER_MODEL HOME_TYPE = ( ('1','1'), ('2','2'), ('3','3'), ) class Home(models.Model): home_owner = models.ForeignKey(User,null=False, verbose_name='Owner') hometype= models.CharField(max_length=100, null=False, default=1, choices=HOME_TYPE, verbose_name='Home Type') licenseid= models.CharField(max_length=200, null=False, unique=True, verbose_name='License ID') archive = models.BooleanField(default=False) def __str__(self): return self.licenseid app: furniture furniture/model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models # Create your models here. User = settings.AUTH_USER_MODEL FURNITURE_DATA_IMPORT_SOURCE= ( ('0', '0'), ('1', '1'), ('2', '2'), ) class Furniture(models.Model): furniture_owner = models.ForeignKey(User, verbose_name='User') furniture_imported_via = models.CharField(max_length=200, default="0", null=False, choices=FURNITURE_DATA_IMPORT_SOURCE, verbose_name='Source of import') furniture_title = models.CharField(max_length=100, null=False, verbose_name='Furniture title') furniture_description = models.TextField(max_length=250, verbose_name='Furniture description') archive = models.BooleanField(default=False) def __str__(self): return self.furniture_title app:mappings mappings/model.py from __future__ import unicode_literals from django.db import models from home.models import Home from furniture.models import Furniture class HomeFurnitureMapping(models.Model): home = models.OneToOneField( Home, on_delete=models.CASCADE, null=False, unique=True, verbose_name='Home' ) furniture = models.OneToOneField( Furniture, on_delete=models.CASCADE, null=False, unique=True, verbose_name='Furniture' ) app: furnitureupdates furnitureupdates/model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db … -
Django multiple admin modifying the same databases
i'm a total noob in django and just wondering if it's possible for an admin doing a same thing at the same time ? the only thing i get after looking at the django documentation is that it is possible to have two admins, but is it possible for the admins to do a task in the same databases at the same time ? thanks for any help -
Django-registration: How to allow user delete their account?
I have a simple website where users can register in order to have access to private content and to receive a newsletter. I have used django-registration for user registration and authentication, and used some HTML templates from here. The whole system is working (login, logout, password recovery, etc.) but I realized that user cannot delete their account from the website. Is there a plugin designed for this, or how to extend the registration classes to do that? By deleting, I'd prefer a real suppression, not just making the user inactive. -
Django - invalid literal for int() with base 10: '''
invalid literal for int() with base 10: ''' is the error that is occuring Hi there, more django fun! So in essence I am recieving this error whilst trying to update my database to register pcap files. Following is the line on which the error occurs Pcaps.objects.update_or_create(filename=pcapname, filehash=malwarehash, uuid=uuid) Here is the model into which it is inserting. class Pcaps(models.Model): filename = models.CharField(max_length=100, default='') datetime = models.DateTimeField(default=datetime.now, blank=True) filehash = models.ForeignKey(Malwares) uuid = models.ForeignKey(System) Any pointers in the right direction would be appreciated. -
python convert emoji to HTML decimal
I have a django application that consumes the twitter public API. The tweets the application received contains some emojis and I want to convert it into HTML decimal equivalent. Searching for python emoji I found two libraries (emoji_unicode, pyemoji). I am using the two libraries as following to get the decimal value of the emoji included in tweet body; import emoji_unicode, pyemoji def emoji_callback(e): t = pyemoji.encode(e.unicode).replace('\\u','') return "&#%s;" % str(int(t, 16)) emoji_unicode.replace(u'Time to ⛽ ',emoji_callback) The previous example works fine but for some other emojis it did not work and it throws an invalid literal for int() with base 16 exception. For example the below code does not work. emoji_unicode.replace(u'Time to 🌄',call) Questions 1- Is there a simpler way to get the HTML decimal of the emoji in the tweet body instead of what is implemented here? 2- If no, how could I solve that exception and get the code working for all emojis? -
Django to_field not working
I have two tables RoomPriceDetails and HotelDetails. RoomPriceDetails has a foreign key which I want to point to the primary key field named hotel_id of HotelDetails. I used to_field attribute for this, but it seems I am going wrong some where. It shows me error like ValueError: invalid literal for int() with base 10: 'BMH-1' when I try to add the hotel_id 'BMH-1' in RoomPriceDetails. 'BMH-1'is a hotel id in HotelDetails. If I am wrong what is the best way to make my foreign key to point to my hotel_id field in HotelDetails to accept those values. My models: class RoomPriceDetails(models.Model): room_type = models.CharField(max_length=255, primary_key=True) hotel = models.ForeignKey(HotelDetails, to_field='hotel_id') price_per_day = models.PositiveIntegerField(default=0) class HotelDetails(models.Model): hotel_id = models.AutoField(primary_key=True, db_column='hotel_id') name = models.CharField(max_length=255) email = models.CharField(max_length=255) reg_no = models.CharField(max_length=255) contact_no = models.CharField(max_length=10) owner_name = models.CharField(max_length=255) owner_email = models.CharField(max_length=255) owner_contact_no = models.CharField(max_length=255) address = models.CharField(max_length=400) city = models.CharField(max_length=255) state = models.CharField(max_length=255) pincode = models.CharField(max_length=6)