Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For loop issue writing multiple lines to database
The for loop below has an issue when writing to the database. Only the first record is coming through, i believe it's because report_name_sc = reportlist is writing the query set to the database. How can I get it to write a single line for each report_id? checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) for i in checkedlist: requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title ,report_id = i, report_name_sc = reportlist, accesslevel_id = '7', phi = '1', access_beg_date = '2017-01-01', access_end_date = '2017-01-31') requestsave.save() -
loading staticfiles in django template causes server error 500
I have a base.html file extended by the index.html one. In base I load some static files in the section, and other in the bottom of the file. I am trying to use the template tag for loading static files: {% load static %} However, depending where I put it, this works or fails. When the tag is on the begining of the base (first line), this always does not work. It works only when it is on the body section of the base.html and on the begining (just after extend tag) of the index.html. Where is the correct place to put it ? Should it be called only once ? -
Django Image Grid Gallery
I am trying to setup a grid gallery in my Django website similar to pinterest.com. I have the following HTML code: <div class="row text-center text-lg-left"> <div class="col-lg-3 col-md-4 col-xs-6"> <a href="#" class="d-block mb-4 h-100"> {% for img in imgs %} <img src="/static/img/{{ img }}" class="img-thumbnail" alt=""> {% endfor %} </a> </div> </div> Here is my views.py def gallery(request): path = "C:/Users/fela/Pictures/" img_list = os.listdir(path) return render(request, 'gallery.html', {'imgs': img_list}) The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png). The expected result should be similar to pinterest, it should be next to each other to fill up the screen. I have tried using bootstrap 4 and bootstrap 3 with same results. -
decrypting token from url
i'm trying to create a url from with a token by combining an id and a date then create a url and send it to a mail. When clicking the link i should be able to decrypt and get the values. However i keep getting an cryptography.fernet.InvalidToken. I'm not sure what i'm doing wrong here? token generator class class ExpiringTokenGenerator(object): FERNET_KEY = Fernet.generate_key() fernet = Fernet(FERNET_KEY) EXPIRATION_DAYS = 1 def _get_time(self): """Returns a string with the current UTC time""" return datetime.utcnow().strftime('%Y-%m-%d %H-%M-%S') def _parse_time(self, d): """Parses a string produced by _get_time and returns a datetime object""" return datetime.strptime(d, '%Y-%m-%d %H-%M-%S') def generate_token(self, text): """Generates an encrypted token""" full_text = bytes(str(text) + '|' + self._get_time(), encoding='utf-8') token = self.fernet.encrypt(full_text) return token def get_token_value(self, token): """Gets a value from an encrypted token. Returns None if the token is invalid or has expired. """ value = self.fernet.decrypt(bytes(token.strip("/"), encoding='utf-8')) return value transaction_activation_token = ExpiringTokenGenerator() sending the email message = render_to_string('transaction_active_email.html', { 'email':serializer.data['user']['email'], 'domain':current_site.domain, 'uid': force_bytes(serializer.data['user']['id']), 'token': transaction_activation_token.generate_token(serializer.data['user']['id']), }) mail_subject = 'Gennemfør transaktion!' to_email = serializer.data['user']['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() view def activate_transaction(request, token): value = transaction_activation_token.get_token_value(token) print(value) redirect("/") -
Django ImageField save to locations
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error: views.py", line 90, in orderdetails settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found if request.method == 'POST': # Loop through our files in the files list uploaded if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)): os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid)) for image in request.FILES.getlist('files[]'): # Create a new entry in our database new_image = UploadedImages(client_order=client, image=image.name) # Save the image using the model's ImageField settings filename, ext = os.path.splitext(image.name) new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) new_image.save() If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid. if request.method == 'POST': # Loop … -
Trying to create user types: 'Client' and 'Employee'. Would like all users who register on site to be Clients, who see different page than employee
I'm reading through these docs on Django: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-user I'm just not sure which route to go. They suggest using a custom user model like so: from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass Doing so, what would the procedure be to make two different user types. Should I have something like this: class Client(AbstractUser): pass class Employee(AbstractUser): pass But then how would new registered users be 'clients' when they sign up? And how would I make it so they see a different part of the site than employees? Really, i'm just looking for some guidance in how I should approach this. Any help would really be appreciated! Thanks! -
Django ORM Annotate boolean field that defines is user member of a team
models.py from django.db import models class UserGroup(models.Model): members = models.ManyToManyField(User, related_name='members', through='UserGroupMember') class UserGroupMember(models.Model): user = models.ForeignKey(User) usergroup = models.ForeignKey(UserGroup) class Cohort(models.Model): user_groups = models.ManyToManyField(UserGroup) class Team(models.Model): cohort = models.ForeignKey(Cohort) members = models.ManyToManyField(User, related_name='team_members', through='TeamMembers', blank=True) class TeamMembers(models.Model): team = models.ForeignKey(Team) user = models.ForeignKey(User) Single user can be part of only one team within a cohort. I want to annotate the new field (boolean) which tells you is the user assigned to some team in the cohort, something like: User.objects.filter( members__cohort=cohort ).annotate( is_team_member=... ) I am using Python 2.7.13 and Django 1.9.8. Thanks. -
d3.json(url, callback) not working correctly with django
I have created a DJango/ReactJS site that is attempting to display an nv.d3.js pie chart. When i add the code to display the pie chart, passing the data array directly into the code, the pie chart displays on the site correctly. However, when i use d3.json(url, callback) to retrieve a json object from the url (served by Django views.py) and pass that as the data into the pie chart, i get an error. The nvd3 code is: createPieChart(){ const node = this.node nv.addGraph(function() { var chart = nv.models.pieChart() .x(function(d) { return d.label }) .y(function(d) { return d.value }) .showLabels(true); d3.select(node) .datum(getPieData()) .transition().duration(350) .call(chart); return chart; }) } the getPieData() function is: function getPieData() { // return (d3.json(url, function(error, rawData) { // if (error) { // console.log("error = " + error) // return; // } // else{ // return rawData; // } // } // ) // ) return [{"label": "R", "value": 822}, {"label": "H", "value": 1}]; } notice in the above snippet, i commented out the problematic code. what i return above works. now, if i go to the URL above that is served by Django, it returns the following data exactly like this in the browser (and in the … -
Dependency between fields in model using Factoryboy
I have a Django Model that I would like to test using Factoryboy. The issue here is that the fields depend on each other. class SearchPreferences(models.Model): min_age = models.PositiveSmallIntegerField(null=True) max_age = models.PositiveSmallIntegerField(null=True) In this case, max_age cannot be smaller then min_age. class SearchPreferencesFactory(DjangoModelFactory): min_age = FuzzyInteger(30, 90) max_age = FuzzyInteger(SelfAttribute('min_age'), 100) This is what I have tried to do, which should give me a value for max_age between min_age and 100, but what happens is a TypeError: TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'int' This makes sense to me, but I can't really figure out how to get this to work? Could someone explain what would be the best approach here? -
How to access request body when using Django Rest Framework and avoid getting RawPostDataException
I need to get the raw content of POST request body yet when I try to access request.body I'm getting an exception: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream I am aware that it is adviced to use request.data instead of request.body when using Django Rest Framework, yet for the purpose of validating digital signature I have to have the request body in a raw and "untouched" form, since this is what is 3rd-party signed and what I need to validate. Pseudocode: 3rd_party_sign(json_data + secret_key) != validate_sign(json.dumps(request.data) + secret_key) 3rd_party_sign(json_data + secret_key) == validate_sign(request.body + secret_key) -
Django: Is meaningful to replace standard template cached loader with memcached?
I am using recommended Django template cached loader to improve performance on production server. After investigation of loader source code and notice that loader do not use standard Django cache mechanism, but only saves compiled messages inside dictionary. Am I right that this dictionary is not shared between processes and threads? For instance if I running Django on Gunicorn in setup with 3 processed, each process 2 threads, each thread compiles and saves templates on their own? This can cause slower startup after server or process restart (using max_request directive in Gunicorn). Does it make sense to create custom template loader which use memcached for saving compiled templated and sharing between processes? -
on_delete error for Django
I'm currently doing some projects from a book called Python Crash Course by Eric Matthes. Currently, I'm doing lab 19.1 where I have to use previous code to make a Django project while changing some of his own code but ran into a problem. Every time I want to run this command >>>python manage.py makemigration blogs in return, I get this code TypeError: init() missing 1 required positional argument: 'on_delete' His original models.py code: from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." and my current code: from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Post(models.Model): """SThe post""" topic = models.ForeignKey(BlogPost) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'posts' def __str__(self): if len(self.text) >= 50: """Return a … -
How do you handle files in a django test
I have a model that has a file field and I've been more or less testing the model like so: def test_importing_file_and_processing(self): file_path = os.path.join(settings.BASE_DIR, 'myapp/tests/reports/test_input_file') report = IngestedFile( filename='test_file' ) report.document.save('test_file', File(open(file_path))) report.save() report.do_stuff() self.assertStuf.... Is there a "better" way to test the file? -
Celery auto retry not working
I'm trying to use celery to send and queue emails in a Django 1.11.4 app. In my DEV environment, using ./manage.py runserver 8000 The task runs and emails get sent. But if I try to break it, by changing the SMTP password in settings.py, things go bad. Here's the task: @app.task(name="email_foo", autoretry_for=(Exception,), default_retry_delay=30, retry_kwargs={'max_retries': 5}) def email_fooApp_task(ctx, subject, recipient_id): email_fooApp_simple(ctx, subject, recipient_id) I can see the email fail in the terminal: [2017-12-05 15:19:05,908: INFO/ForkPoolWorker-2] Task email_foo[6856f683-e86d-4b99-a77c-9edee586ba5e] retry: Retry in 30s: SMTPAuthenticationError(502, b'5.5.1 Unrecognized command. q12sm565712qtk.32 - gsmtp') And it appears to be rescheduled. But it never gets retried. It's in the schedule, as inspect scheduled shows: 'priority': 6, 'eta': '2017-12-05T20:19:35.871604-04:56', 'request': {'name': 'email_foo', 'args': "({'ical_date': '20170916T170000Z/20170916T180000Z', 'txt_body': 'From Bar, Rob\r\nfoo@bar.com', 'HOST_URL': 'http://127.0.0.1:8000', 'html_body': '<p>From Bar, Rob<br />\r\nrob@foo.bar</p>', 'recipient': 'Rob'}, 'Test Bad SMTP pwd', 1108756)", 'delivery_info': {'priority': 0, 'routing_key': 'celery', 'exchange': '', 'redelivered': None}, 'time_start': None, 'kwargs': '{}', 'acknowledged': False, 'worker_pid': None, 'type': 'email_foo', 'hostname': 'celery@foo.bar', 'id': '6856f683-e86d-4b99-a77c-9edee586ba5e'}} Any ideas?? -
Django multiple view functions for one page
I'm tring to make a page on my website where users can pick recipes of which the products are added to a newly created shoplist. However, there is a lot going on at the page and quite a lot of areas on the page need to be updated after selecting a recipe. So far the functionality of the page is: 1. Make a shoplist 2. Display relevant values to the user 3. Show a filtered list of recipes to the user on the basis of submitted values 4. Update the values on the page with values from the chosen recipes In the future I will need to implement even more functionality and I'm pretty sure that my code will become a mess if I leave it like this. I'll summarize my goals and current questions with the vies that I have made: A shoplist has to be made when the page is loaded. This shoplist is not visible to the user. Only a few values will be. I want to display the values 'budget' and 'dagen'. I have made a context for this which is now the same in both views. This is not good DRY code as I understand. … -
django test a templatetag which uses the request
I'm using a custom templatetag to calculate currency values, currency is choosen from a select element. when the user choose the currency he want work with I save the choosen currency in the session and refresh the page. a templatetag shows the value calculated for the choosen currency. in any template {% load currency %} {% set_currency request 156 %} in my_app/templatetags/currency.py from django.conf import settings from djmoney_rates.utils import convert_money register = template.Library() @register.inclusion_tag('includes/price.html') def set_currency(request, price): # currency_session could be 'USD', 'EUR' ... currency_session = request.session.get(settings.CURRENCY_SESSION_KEY, settings.DEFAULT_CURRENCY) money = convert_money(price, settings.DEFAULT_CURRENCY, currency_session) return {'amount': '%d' % money.amount, 'currency': money.currency} includes/price.html is just <span class="amount">{{amount}}</span> <span class="currency">{{currency}}</span> Now I'm wondering the way to test this templatetag, how to pass the request, and how make session to exists in that request. -
*10 upstream timed out (110: Connection timed out) while reading response header from upstream with uwsgi
I currently have a server setup with nginx and uwsgi with django This error doesn't happen until I try to change my rds instance my fully error message is *10 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: xxx.xxx.xxx.xxx, request: "GET /load/ HTTP/1.1", upstream: "uwsgi://unix:/tmp/load.sock", host: "example.com", referrer: "https://example.com/" I was using aws rds (postgres) which works perfectly fine. The only change I made is changing from regular postgres service to aurora postgres I didn't upgrade the db, from regular to aurora. I created a new aurora postgres. I got everything setup...changed host and everything in my django db setting. runserver locally works fine. It does connect to db with read and write. Works perfectly. But when I deploy to server, open up my domain. Anything ui related looks fine but db related, NO. Took awhile then of course the 504 gateway timeout. I went to checkout the nginx error log. That's the error message I found. Googled, tried a few settings other stackoverflow posts suggested such as addingsingle-interpreter = true into uwsgi.ini file. No luck. Can someone please give me an idea where I should look into for this problem? Thanks … -
Django default site - migrations
How I set up Django default site (name + domain)? Docs and answers here suggest to use data migrations but that doesn'work in case you just run migrate on newly create database where all migrations run at once. Why? Simply because Site model is not available when I call get_model() method in my data migration. I've tried to use fixtures but Django starts auto_increment site table value from SITE_ID in your settings so you can't simply ignore ID 1 (the example.com) and just add your custom domains to fixtures and set the ID in settings - like SITE_ID = 2. The question is how I set up/override Django default "example.com" site so I can run all migration at once against production database and have my domain set up? -
make query to table (django_migrations)?
I need to write in table django_migrations for that I am using: fix_migration.py from django.db import connection from django.db.migrations import recorder recorder.MigrationRecorder(connection).record_applied("registro_movimientos", "0001_initial") I am applying that via python manage.py runscript fix_migration.py but I need check first if that migrations was applied before , some like that: query = django_migrations.filter(name=0001_initial, app="registro_movimientos") if not query: recorder.M .... thanks . -
Django 2.0 path error ?: (2_0.W001) has a route that contains '(?P<', begins with a '^', or ends with a '$'
I'm new to Django and am trying to create the back end code for a music application on my website. I have created the correct view in my views.py file (in the correct directory) as shown below: def detail(request, album_id): return HttpResponse("<h1>Details for Album ID:" + str(album_id) + "</h1>") however, when creating the url or path for this (shown below) #/music/71/ (pk) path(r'^(?P = <album_id>[0-9])/$', views.detail, name='detail'), I am experiencing a warning on my terminal stating: ?: (2_0.W001) Your URL pattern '^(?P = [0-9])/$' [name='detail'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). and whenever the /music/ (for which the path works) is followed by a number, such as /music/1 (which is what I want to be able to do) the page cannot be found and the terminal gives the above warning. It may be a simple error and just me being stupid but I'm new to Django and python regex statements, so any helps is appreciated, thanks. -
Django OneToOneField Unique fails when extending User model
I'm trying to extends Django User model by means of an Actor model but I'm getting some problems. There is my code: class Actor(models.Model): usuario = models.OneToOneField('auth.User', unique = True, null = True) def __str__(self): return self.usuario.get_full_name() + ' (' + self.usuario.get_username() + ')' The problem is that one-to-one relationship is not unique so I can create two differents actors and relate them with the same user. Use case idea: I create a User (User model by Django) then I create an actor and relate him with the user I created before. If I create a second actor, there would not must be posible related him with the same user. -
Connecting to RDS Postgres from Heroku
I'm in the process of migrating my Heroku app database from Heroku to AWS RDS Postgres. On my computer, I can connect to my RDS DB using: psql -d "postgres://user:password@XXX.rds.amazonaws.com/mydb?sslrootcert=config/amazon-rds-ca-cert.pem&sslmode=require" However, the same psql command run from within my heroku server just hangs forever. Also, config/amazon-rds-ca-cert.pem is the RDS certificate that I added to my package as mentioned in the documentation https://devcenter.heroku.com/articles/amazon-rds#authorizing-access-to-rds-instance and here https://stackoverflow.com/a/29467638/943524 (I did combine certificates as I am using a eu-central-1 instance). Would someone have an idea what is blocking the connection here ? -
How to get current url in views.py django?
First I read many answers here and mostly are about getting url in template. I need to get url in views.py then I need to assign it as veriable. I have 6 views like that and I have 6 querysets as well. SweatbandsView, HeadbandsView, BandanasView, BalloonsView ,TableCoversView, CoastersView I created new view which is called Preview: class Preview(SweatbandsView, HeadbandsView, BandanasView, BalloonsView ,TableCoversView, CoastersView): template_name = "preview.html" As you see there, this view includes all of those. Now I need to get my current url and assign it like the_url. Then Preview.py should be like this: class Preview(SweatbandsView, HeadbandsView, BandanasView, BalloonsView ,TableCoversView, CoastersView): template_name = "preview.html" the_url = whatever_func_is_it() if (the_url == '/someting/something'): queryset = Product.objects.all().filter(category_id='6') else: . . . . With this way I want to use needed queryset in if condition! By the way I have 2 models in database which are Product and Category and they have OneToMany relation. Thanks! -
django REST framework nested serializer and POST nested JSON with files
How do I send a POST request with nested data including files (images) to django REST nested serializers? Given this JS object: bookData: { title: 'Anne of Green Gables', coverImage: File(123456), pages: 123, author: { name: 'Lucy Maud Montgomery', born: 1874, profilepicture_set: [ {file: File(234567), description: 'Young L. M. Montgomery'}, {file: File(234568), description: 'Old L. M. Montgomery} ], quote_set: [ {text: "I'm so glad I live in a world where there are Octobers."}, {text: "True friends are always together in spirit."}, ] }, } I want to send a POST request to my django REST API (I use VueJS on frontend, but this does not really matter). # views.py class CreateBookView(generics.CreateAPIView): serializer_class = CreateBookSerializer queryset = Book.objects.all() # serializers.py class CreateBookSerializer(serializers.ModelSerializer): author = CreateAuthorSerializer() class Meta: model = Book fields = ('title', 'pages', 'author') @transaction.atomic def create(self, validated_data): author_data = validated_data.pop('author') uploader = self.context['request'].user book = Book.objects.create(uploader=uploader, **validated_data) Author.objects.create(book=book, **author_data) return book # models.py class AuthorManager(models.Manager): def create(self, **author_data): quotes_data = author_data.pop('quote_set') photos_data = author_data.pop('profilepicture_set') author = Author(**author_data) author.save() for quote_data in quotes_data: Quote.objects.create(author=author, **quote_data) for photo_data in photos_data : ProfilePicture.objects.create(author=author, **photo_data) return author ## Skipping the CreateAuthorSerializer, Quote and ProfilePicture Managers as they are analogous. ## Assume one Author … -
How to name sorl-thumbnail files based on a field of the source picture model ? (Django)
Our site is based on Python 2.7 / Django 1.9 and sorl-thumbnail 12.4.1 Basic picture model: class Picture(models.Model): file = ImageField(max_length=500, upload_to='pics') placename = models.CharField(max_length=200) We override the _get_thumbnail_filename function of sorl-thumbnail to have more SEO friendly thumbnail names (so that the thumbnail file takes the name of the initial picture): class SEOThumbnailBackend(ThumbnailBackend): def _get_thumbnail_filename(self, source, geometry_string, options): key = tokey(source.key, geometry_string, serialize(options)) filename, _ext = os.path.splitext(os.path.basename(source.name)) path = '%s/%s' % (key, filename) return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']]) We would like to add the "placename" at the end of this thumbnail file name. We can't get how to retrieve the Picture model from the function. Any clue ? That would be much helpful. Thanks a lot