Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Static Precompiler not compiling files?
Django static precompiler does not seem to be working with scss files for me. I already checked if i had the compiler installed and my settings for django are are follows INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'static_precompiler', 'cms', ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'static_precompiler.finders.StaticPrecompilerFinder', ) STATIC_URL = '/static/' STATIC_ROOT = "static" and i am calling the same from django template as follows {% load compile_static %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spacemailer</title> {% block seo %} {% endblock %} <link rel="stylesheet" href="{% static 'style/main.scss' | compile %}" type="text/css" media="all" /> </head> <body> {% block body %} {% endblock %} </body> </html> There are no errors whatsoever. The output is the same scss file with no compilations being made. Can someone point out what am i doing wrong with the same ? or some alternatives that will support compiling scss as well as coffee scripts -
why when using the tag AMP or ⚡, the server django load four times or more, and when deleting this tag only load one time?
picture with the tag AMO picture without the tag AMP -
Unable to get environment variables inside django settings?
I defined my environment variables inside env/bin/activate and the following came out from the output when i activated them debug="True" secret="RI4MgORxGb4c6zhotTHSNXc54lz1IWGbIoETfmj2VB99sPNlk9YMcg4b6qyX" using echo in zsh. Now that tells me that the environment variables are set properly. I am getting the same inside django settings using DEBUG = True if os.environ.get("debug") == "True" else False The problem comes when i run python manage.py runserver which is unable to find those variables as opposed to env debug='True' python manage.py run server which works fine in debug mode and production depending on environment variables. What am i missing over here ? is this something because of using zsh shell or am i getting the variables wrong way somehow ? -
Object of type 'CombinedExpression' is not JSON serializable
I've set a like/dislike function for comments in my app but when user clicks on like or dislike for the first time it gives me error which I noted in the title. but this happens just in the first time and if user clicks on like or dislike again it works completely fine. what is "CombinedExpression" anyway? my views.py: @login_required(login_url='/accounts/login/') def like(request, comment_id): comment = get_object_or_404(Comments, pk=comment_id) if request.POST: # handling like or dislike if request.is_ajax(): return JsonResponse({'cmplus':comment.cmpvote, 'cmminus':comment.cmmvote}) return HttpResponseRedirect(my reverse return) for the record I have to say cmpvote and cmmvote are the number of like and dislikes of a comment and are integers with default of 0. -
Sparkpost help, incase anyone had the same error
I recently added sparkpost as a transactional email service for one of my django apps. After setting up SMTP, it worked locally but failed in production. I sieved through the configuration process over and over again but kept getting 550 5.7.1 auth error However after pip installing it and adding SPARKPOST_API_KEY = config('SPARKPOST_API_KEY') EMAIL_BACKEND = 'sparkpost.django.email_backend.SparkPostEmailBackend' to my production settings, everything worked. Note: API key settings will be different SMTP API and Email API, you need to give as many permissions as you deem possible to the specific API Key. I hope this helps and saves someone time, because it took quite a while for me to figure out what was wrong. -
Difference self, object, and request in Django?
Can somebody explain the difference among and when to use self, object, and request in Django? -
Python/djando external API integration mapping/UI recommendations/suggestions
I am working on building a tool that I will be tying in to a multitude of external APIs. I was wondering if anyone had any suggestions for a a user mapping tool that allows a user from the front end to add mappings that ultimately result in the JSON payload being built dynamically from the users inputs. I am relatively new to Python and Django but built something similar on a different stack and would prefer not to reinvent the wheel if I do not need to. I've already leveraged Django-tables2 and Django-filters which are excellent tools. In my mind, I would envision building models to house the mappings and then would use Django's version of reflection/introspection to then build the payload and then would similarly deserialize the response and do the same to update the records. Then I would use some sort of schedulers and/or dynamic signals (not sure if this exists yet) to determine when the outbound calls are executed. Again, relatively new to Python and Django, and would really appreciate any recommendations on existing tools or at least feedback on whether I am on the right track if I do build this out from scratch. Attached … -
Django custom user profile and LDAP flags mapping
I'm using a custom user profile in my project and have an extra user flag, that I would like to fill in depending on user LDAP groups. Searched through documentation and forums, but can't find a clear explanation on how this should be done. In general LDAP authentication works ok and standard django user flags are working, but I can't seem to map my field in settings.py the same way. app.py: class Profile(models.Model): user = models.OneToOneField(User) is_engineer = models.BooleanField(default=False) . . . settings.py: AUTH_LDAP_USER_FLAGS_BY_GROUP = { <django user flags>..., "profile.is_engineer": "cn=group,ou=MG,ou=group,o=company,c=an", } Also I have a custom authentication backend where I could check user's group, but again not sure what is the best practice for that. Thank you very much for your advice -
Print an object's URL in Django
OK, I think this is actually simpler than I'm making it, but I can't figure out what to search for in the django documentation. Here's what I need to do. I'm about to run a script (using the writing custom django-management commands guide) which will add a whole bunch of records to my database. A mass import of all the student data. After I create these 130 new records, I need to create a QR code for each of them. I've found several QR code generator sites, but that's slow as hell and the school won't pay for me to sign up for the ones that come with mass QR code generation. No problem, this is Python. Batteries included! I have the qrcode module installed, but what I don't understand is how I can get the URL after it creates the object. I know which view I want (the relative url is /awards/student//). I know that in the HTML template language, that {% url 'StudentHome' student.id %} gets me that url. Can I access that from the command line and pass it to qrcode, which would then generate and save the qrcodes as png files? -
Error in Running Server using python with django framework
I'm a beginner in programming and my first project is creating a website using python with django framework as the back-end.However on trying to run the server. I was getting the following error. So can someone please explain? (myvenv) C:\Users\Rohan Jain\venvi>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001FACC183378> Traceback (most recent call last): File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Rohan Jain\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen … -
Django Model Filter with category/items
sorry for my bad english, first the models: class Book_Recipes(models.Model): author = models.ForeignKey(User,to_field='username', on_delete=models.CASCADE) name = models.CharField(max_length=100) class Meta: unique_together = ("author", "name") class Recipe(models.Model): author = models.ForeignKey(User,to_field='username', on_delete=models.CASCADE) Book_R = models.ForeignKey(Book_Recipes, on_delete=models.CASCADE,null=True) name = models.CharField(max_length=100) class Meta: unique_together = ("author", "name", "Book_Recipes") I want to achive some like this in views Book of salsa: *Salsa 1 Salsa2 Book of Chees: Cheese 1 By author: What i"m doing now is me = models.User.objects.get(id=0) myRecipes = models.Recipe.objects.get(author= me) In this way if i past the variable myRecipes in context like {"Rec",myRecipes} {{% for item in REC %}} {{item.Book_R.name}} {{item.name}} {{% ENDFOR %}} In that way i"m printing all the times the book_recipe of the recipes. It look like it should be a two "FOR" and the query could be a first query searching the books of the author. And later do each query for each book, get all of that query_set data in array and do the doble loop. But that look a bad way (Inneficient) to achieve it. I appreciate if someone have a tip to achieve the organization more efficient. Thank your for all your help :) -
Model instance method saving image under wrong directory when editing existing object?
This is a tricky one for me unfortunately. I have a GalleryImage model that has a instance method, cropper, that takes the image uploaded to image field and crops it. Then basically does some things that I don't quite understand to crop the image and save it to crop_image field. Creating new objects everything works as expected but when I edit an existing object it saves the cropped image in the wrong directory. (very wrong). The directory ends up like this when editing existing object: https://gyazo.com/e9b2abcbfc997f911a1bf1e77d4566b6 Here is my code: class GalleryImage(models.Model): """Represents a "gallery image object" inside system.""" title = models.CharField(max_length=100) description = models.CharField(max_length=255) image = models.ImageField(upload_to='gallery/img/%Y/%m/%d', validators=[validators.val_img_exten]) crop_image = models.ImageField(upload_to='gallery/crops/%Y/%m/%d', validators=[validators.val_img_exten], blank=True, null=True) upload_date = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) REQUIRED_FIELDS = ['image','title'] def save(self, *args, **kwargs): crop_f, cr_io, n_name = self.cropper() self.crop_image.save(name=n_name, content=ContentFile(cr_io.getvalue()), save=False) return super(GalleryImage, self).save(*args, **kwargs) def cropper(self): if self.image: new_file = ContentFile(self.image.read()) new_name = (self.image.name.split('.')[0] + '_copy.' + self.image.name.split('.')[1]) new_file.name = new_name self.crop_image = new_file if self.crop_image: image = Image.open(self.crop_image) exten = self.crop_image.name.split('.')[1].lower() if exten == 'jpg': exten = 'jpeg' longer_side = max(image.size) hp = (longer_side - image.size[0]) / 2 vp = (longer_side - image.size[1]) / 2 c_img = Image.open(self.crop_image) crop = c_img.crop( ( -hp, … -
Use load static in django templates gets messy code
In my template, i use load static to load static files: {% load static %} <link rel="stylesheet" href="{% static 'css/default.min.css?t=227' %}" /> but in the browser html changed to this messy code: <link rel="stylesheet" href="/static/css/default.min.css%3Ft%3D227"> -
How do you format a queryset before returning to admin site for showing?
How do you format a queryset before returning to admin site for showing? Here class1 is passed to list_display in model admin class def class1(self,obj): return obj.class1_set.all() and returns and shows the unreadable, <QuerySet [<Class: Object>]> to the admin site. All classes already have an __str__override. -
Serve images with Django
I am serve my images from my web server django like this localhost:8000/media/images/foo.png, but my question is if I am sending the images is the correct way, I think it is not necessary to send the server, since I myself am the one who serves the photographs, any ideas? Something like this media/images/foo.png. In order that in the img tag of html this is a relative path and not a link. -
'AnonymousUser' object has no attribute 'profile'. - accessing to views by anonymous and authenticateds users
I have the following User schema: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) username = models.CharField(_('username'), max_length=30, null=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) objects = UserManager() USERNAME_FIELD = "email" def __str__(self): return "@{}".format(self.email) And I have the UserProfile class class UserProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile' ) According to previous models, one user have one userprofile. All right. I have some views that it is interesting that they can be accessed by both anonymous users and logged in users. When an logged in user access to view, this ask the profile data information and show them in the template When an anonymous user access to view, this should render the template, obviously without profile data information. This view is named article_detail and their small logic is the following: def article_detail(request, slug): user = request.user # I ask fot the profile user profile = user.profile queryset = Article.objects.filter(published_date__lte=timezone.now()) article = get_object_or_404(Article, slug=slug) return render(request, 'blog/article_detail.html', {'article': article,'userprofile':profile }) When an authenticated user access to this view, the data profile information is renderized, validating the profile = user.profile section code. This is O.K. But when an anonymous user access to this view I get … -
How can I have Django generate or change a DOM element?
I'm building a Django app and I would like to have a view/function add a line of html to the inner html of a specific div element with an id every time it is run. I know how to do this with Javascript but then I would need the view to run that script every time it runs. Is there a way to do this in the Python document? -
Accessing Django PROJECT_ROOT from Javascript
In my Django Settings file I define PROJECT_ROOT as dirname(realpath(file)). I want to access the PROJECT_ROOT from Javascript; how can I do that? -
The Wonderful Apps aren't loaded yet Error
I've searched SO and Google and can't find an answer to my problem. I've launched my virtualenv and ran this command in the terminal: python bin/process_messages.py and this error occurs: Stacktrace: Traceback (most recent call last): File "bin/process_messages.py", line 6, in <module> from xyz.models import get_sku File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/xyz/models.py", line 19, in <module> class Suppliers(models.Model): File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I thought it wasn't running django.setup so I added that to the script. Here is my code: #!/usr/bin/env python import os import django import boto3 from xyz.settings import SQS_QUEUE_NAME from xyz.models import get_sku __author__ = 'me' def check_django_environment(default_settings): # Environment setup for Django project files: os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) if not os.environ.get('DJANGO_SETTINGS_MODULE'): # Don't override settings if it is specified. os.environ['DJANGO_SETTINGS_MODULE'] = default_settings from django.conf import settings return getattr(settings, 'DEBUG', None) check_django_environment('repricer.settings') django.setup() # Get the service resource sqs = boto3.resource('sqs') # Get the queue queue = sqs.get_queue_by_name(QueueName=SQS_QUEUE_NAME) for message in queue.receive_messages(): print(message) if message.message_attributes is not None: print(message.message_attributes) #sku = message.message_attributes db_sku = get_sku(sku) print(db_sku) break -
NoReverseMatch error when creating new users through admin
In my django app, I've created a custom User model which extends AbstractUser. I updated the AUTH_USER_MODEL and registered it under the admin like so admin.site.register(MyUser, UserAdmin) I ran the migrations and then went under my admin page and saw it listed under the app's models. But when I tried created a new user from that page, it gave me this error. User class in models.py: class MyUser(AbstractUser): id = models.CharField(primary_key = True, unique = True, max_length = 50) Any ideas? -
Python/Django: converting mm/dd/yy DOB into YYYY-MM-DD
I'm using Python 3.5/Django 1.10 I have a DOB string in this format e.g. 9/20/56 On the other side I have a dob = models.DateField(.......... of a model that I'm trying to save. My goal is to convert the date above into 1956-09-20 to be put into the dob field in the model. Is there any function to do that without getting 2056 in the year? This is after all DOB. Those cannot be a future event... -
Django ID verification Database design
I have been struggling on this ID verification design for days, currently we already have a User table, now we want to add a new feature to verify user's driver license, user need to send their photo of their driver license (AWS S3 url) to backend and store. Admin will need to review and verify, once it is accepted, their driver license URL will be updated to User's table and we will send notification to user. If it is rejected, we will need to send notification and reasons to user. My question is, should we have a separate table to store verification status? or we can just add verification field into existing User table? how can we design database to realize this work flow? My initial thought is that creating another Verification table, once user send verification request, we create a new row in this table. If Admin accept it, we update the field of this row as "Accepted". Thanks. -
python django dict is not defined but actually it is
Code I'm working with: class Foo(View): def post(self, request): form_data = { 'form': UserRegistrationForm(request.POST), 'sex': request.POST['sex'], 'terms': request.POST['terms'], } if form_data['form'].is_valid(): user = form_data['form'].save(commit=False) user.is_active = False user.save() user.profile.sex = from_data['sex'] #raise err here user.profile.save() This throws name 'from_data' is not defined. Its weired for me, it doesn't work, and this does: user.profile.sex = request.POST['sex'] For someone who was used to code in C that situation is little funny and much annoying. -
Closest date calculations via Django annotation
I have a model that tracks project milestones. Here's the pseudo-code for its structure: class MilestoneEntry(): project = models.ForeignKey(...) meta = models.ForeignKey(...) entry = models.DateField(...) exit = models.DateField(...) class Project(): name = models.CharField(...) I have a set of project records (essentially a list of project IDs), and for each one, I want to find the closest entry or exit date, whichever is closest. So, for example, if project A has milestones that look like: entry exit MS-1 2017-06-01 2017-08-12 MS-2 2017-08-13 2017-10-01 The closest milestone to today (2017-08-11) for that project would be the exit date for MS-1. I'm aware that I will likely have to do this in two passes (one pass for entry dates, one pass for exit dates), then compare the two in my code. However, I haven't been successful in figuring out the ORM magic necessary to get the right query. If I try to annotate a MilestoneEntry query, I end up with bogus results: today = datetime.date(2017, 8, 11) qs = MilestoneEntry.objects.filter(project_id__in=[1,2]) qs = qs.filter(entry__gte=today) qs = qs.annotate(min_entry=Min('entry')) for x in qs: # Loop over the results ... bad results though What am I missing here? -
Django: Forms and Javascript
I found out that Django Forms and Javascript doesn't like each other a bit. How is it about? Is there any possibility to use JS? The problem which I found. I had a form on which some part is not required and I wanted to hide it and if user needs to fill it, he or she would have to check checkbox and hidden part will show. Easy right? But when I wrote JS part which shows/hide part of the form, the form didn't work, I mean, after clicking Submit button nothing was done... Anyone had same problem and maybe solve this issue?