Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect two django model query sets
When a list of strings(representing tags) are sent to a function, it retrieves tags that are in DB and also crates tags that are not found in db. I need to then combine those two into one queryset and return but when I tried to connect the two querysets by using +, it raises error. How can I connect two querysets? # Separate one in DB and not in DB tags_found_in_db = Tag.objects.filter(name__in = tag_strings) name_of_tags_found_in_db = [tag.name for tag in tags_found_in_db] tags_not_in_db = list(set(tag_strings) - set(name_of_tags_found_in_db)) # Bulk Create tags_to_be_created = [] for new_tag_name in tags_not_in_db: tags_to_be_created.append( Tag(name = new_tag_name) ) new_tags = Tag.objects.bulk_create( tags_to_be_created ) # > TypeError: can only concatenate list (not "QuerySet") to list return new_tags + tags_found_in_db -
PostgresSQL full text search query from long text
I am using PostgreSQL full text search in my django+postgresql app. I have a crawler which crawls a bunch of websites and stores the body text of the crawled webpages in a column in the database. User input is a long piece of text and I want to figure out if it is about the same topic/subject as any of the webpages. Can you suggest an optimal way to build the search query from a long piece of text for postgres full text search? -
How to link django custom user model and django allauth package
I have a custom user model in django made using AbstractUser. I am using the django allauth package for my authentication. I have made custom fields in both but am unable to link both of them. models.py from django.db import models from django.conf import settings from django.shortcuts import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser class User(AbstractUser): age = models.CharField(max_length=30, blank=True) phone = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=30,blank=True) gender = models.CharField(max_length=30,blank=True) forms.py from allauth.account.forms import SignupForm from django.contrib.auth import get_user_model from .models import User class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') age = forms.CharField(max_length=30, label='Age') phone = forms.CharField(max_length=30, label='Phone Number') address = forms.CharField(max_length=30, label='Address') gender = forms.CharField(max_length=30,label = 'Gender') print('FN',first_name) print('Age',age) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.age = self.cleaned_data['age'] user.phone = self.cleaned_data['phone'] user.address = self.cleaned_data['address'] user.gender = self.cleaned_data['gender'] user.save() return user I have defined a customUserAdmin admin.py from django.contrib import admin from .models import Medicine,Order,OrderItem,Pharmacy,Address from django.contrib.auth.admin import UserAdmin from .models import User from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model class CustomUserAdmin(UserAdmin): """Define admin model for custom User model with no username field.""" fieldsets = ( (None, … -
Django ORM Model saving
when I'm trying to interact with SQlite model I created I cant save the models using .save it is prompting that <fuction Model.save at (some hex address)> where in tutorial there is no such prompt command can any one help me rectify it -
Getting django.db.utils.IntegrityError: duplicate key value violates unique constraint But value does not exists
I was trying to get some object from DB using Django ORM. Medicine.objects.get(unique_item_id=26775) But while fetching I was caught up with Error -> item_medicine.models.DoesNotExist: Medicine matching query does not exist. Then I tried Inserting the same using Django ORM. Medicine.objects.create(unique_item_id=26775) But again I am getting error psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "item_medicine_medicine_unique_item_id_key" DETAIL: Key (unique_item_id)=(26775) already exists. In my models I have added unique=True for unique_item_id field. I don't know why is this happening. I tried answers given on similar posts But nothing worked. Traceback: Traceback (most recent call last): File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "item_medicine_medicine_unique_item_id_key" DETAIL: Key (unique_item_id)=(26775) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-46fdec6a582b>", line 1, in <module> Medicine.objects.create(unique_item_id=26775) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/home/rohit/Projects/medicine/item_medicine/models.py", line 58, in save super(Medicine, self).save(*args, **kwargs) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/models/base.py", line 924, in … -
ProgrammingError at /catalog/
So I'm trying to open my Heroku app website. After pushing the files from a git repository to my git heroku repository, I open the website and get this error message. Environment: Request Method: GET Request URL: http://chimpbooks.herokuapp.com/catalog/ Django Version: 3.1.2 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog.apps.CatalogConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "catalog_book" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "catalog_book" ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/catalog/views.py", line 11, in index num_books = Book.objects.all().count() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 411, in count return self.query.get_count(using=self.db) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/query.py", line 515, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/query.py", line 500, in get_aggregation result = compiler.execute_sql(SINGLE) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", … -
Reverse for ' ' with arguments '('',)' not found. 1 pattern(s) tried
I'm getting this error anytime I click on this submit button on my listing page. I've looked through the typical places that this kind of error is triggered by but I can't see what I'm doing wrong here. Error: Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<id>[0-9]+)$'] and further down on the page, on the traceback this line is highlighted as below. For clarity, it is highlighting the 2nd return render in that view. auctions\views.py, line 229, in closeListing return render(request, "auctions/closeListing.html", { I know that in my views and urls I pass the argument of id but then on the template I pass the argument of listing.id but this has been working throughout my project for some reason but just not working here. I actually just tried to change all the arguments in views and urls to listing_id to match the listing.id in the template and this produced the exact same error so I'm really lost. views.py def closeListing(request, id): bids = Bid.objects.filter(bid_item_id=id).order_by('-bid_input') winner = Bid.objects.filter(bid_item_id=id).latest('bid_input').bidder.id winner_name = Bid.objects.filter(bid_item_id=id).latest('bid_input').bidder.username currentHighest = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] if request.method == "POST": if bids == 0: return render(request, "auctions/closeListing.html", { "bids": bids, "error": "No bids have been placed on your listing", … -
What is the best Way to run a CronJob in containerized django application with 2 or more Replicas
I am working on a project which is deployed on docker swarm as a service with 3 replicas. I want to run a simple management command to delete some rows from a table if the date has passed. I have written a django command for it, but want to make the run automated using cron job. I do want to make sure the Job is run only once a day from any of the container which is part of my service. On the internet I found some packages built for running cron jobs for Django application, but none of them considers more than one containers. Some packages have lock based approach but it were file based locks and not a shared lock. I did not want to celery for this simple task. Following is glimpse of my command: class Command(BaseCommand): """Command to clear user subscription if end_date has passed""" def handle(self, *args, **options): try: deleted_count, relative_deleted = MyModel.delete_inactive_instances() except Exception: raise CommandError('Could Not Remove Inactive Subscriptions From DB') else: self.stdout.write(self.style.SUCCESS('Successfully Removed Inactive Subscriptions %s ' % deleted_count)) I am currently running a command each day by docker exec: python manage.py delete_inactive_instances Following is my docker-stack file: services: production_app: image: {id}.dkr.ecr.{region}.amazonaws.com/xxxxxx:latest … -
How to sort table columns using button in Django
I'm building a website in django and I want to add button and drop down menu above the table. In drop down menu, there will be name of the columns and if i select one column and then click the button sort then table will be sort on basis of that columns. def index(request): slist = Stock.objects.all() paginator = Paginator(slist, 20) page = request.GET.get('page') slist = paginator.get_page(page) template = loader.get_template('stocks/screener.html') context = { 'slist': slist, } return HttpResponse(template.render(context, request)) What should i do?? -
Creating project manager system using django
I am creating a project manager system with using Django backend. But I am not sure what is the best approach to build a model for this. For example planning to establish a system structure like: class Organization(models.Model): user = models.ManyToManyField(User) organization_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organization_name = models.CharField(max_length=255) def __str__(self): return self.organization_name Organization Model creates a record when a new user created in Database and bind the user id to itself. class Role(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.name This model take the [read, edit] roles. class Project(models.Model): user = models.ForeignKey(User,on_delete=models.DO_NOTHING) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) project_name = models.CharField(max_length=255) def __str__(self): return self.project_name When a project created. It takes the users' organization. So the project can only seen by the users which participated with same organization. class ProjectParticipant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.user ProjectParticipant controls the which user read or edit the project. I am not sure this is the good approach to build a project manager system. If there are flaws, how can I fix those... -
SVG not rendering
My django project is storing images on AWS. https://race-hub.herokuapp.com/ All png and jpg files are rendering as expected but svg files are not. I've checked various threads on this including content-type to be used for uploading svg images to AWS S3 I've checked the file type is set to "image/svg+xml" on AWS and that the files exist and render fine in AWS. -
Generate PDF file in Django using xhtml2pdf
I tried to generate a PDF file based on the information that comes from client side. I fetched the data using request.POST. @csrf_exempt def create_pdf(request): if request.POST: context = {} data = json.loads(request.POST.get("users")) // I didn't use it. context["title"] = "AMIR" render_to_pdf( template_path="useres/users_template.html", context=context) return HttpResponse(response) and to render pdf file I've wrote the code down below: def render_to_pdf(template_path, context={}): # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response when I call render_to_pdf in create_pdf view It doesn't return pdf file! How do I should return it? -
django_filters, how do I query based on associated model?
My problem is like so, I am using django-tables2 and I want to list some people on my page but these people should go through some queries. These queries will change according to information from other models.if the query is ok, this person will be in my table. # My models class AgeGroup(models.Model): age_group = models.CharField(choices=age_choices, max_length=5) class SolvedExam(models.Model): age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='solved_exam_age_group') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='solved_exam') class Person(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person') age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='person_age_group') * * * class Exam(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person') age = models.ForeignKey(AgeGroup, on_delete=models.CASCADE, related_name='exam_age_group') * * * # my view class PersonList(SingleTableMixin, FilterView): table_class = PersonTable model = Person queryset = Person.objects.all() paginate_by = 10 template_name = 'person/person-list.html' filterset_class = PersonFilter def get_queryset(self): super(Ogrenciler, self).get_queryset() return Person.objects.filter( **some query** ) raise Http404 I want to list the students if there are exams which is not finished in the person's age group. Thank you very much! -
Pycharm Django Macos Catalina Zsh abort and file tracking disabled
I been moving some PyCharm projects to my new iMac, but with 1 of my project im having issues when I try to run my custom Django commands, witch do work properly in other projects. To give you an overview, this is happening: When I try to run the project in PyCharm (run server): Process finished with exit code 134 (interrupted by signal 6: SIGABRT) When I manual try to run a Django command, it does seem to see the command file but it returns: Process finished with exit code 134 (interrupted by signal 6: SIGABRT) When I copy the command and try to execute it myself: /Users/gerd2020/Documents/Projecten/werkblad/venv/bin/python /Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py testdit /Users/gerd2020/Documents/Projecten/werkblad File tracking disabled zsh: abort /Users/gerd2020/Documents/Projecten/werkblad/venv/bin/python testdit im confused , when I do a collect static that does seem to work. Any ideas where I got to look? -
Django: Why am I getting ValueError when referring to a ForeignKey using a varchar?
My application (called users) includes these two models: class RankingType(models.Model): type_code = models.CharField(max_length=16, unique=True) description = models.CharField(max_length=64) def __str__(self): return f'{self.description}' class RankingProfile(models.Model): user = models.ForeignKey( User, to_field='username', on_delete=models.PROTECT, related_name='ranking_profile_as_user', blank=False ) type_code = models.ForeignKey( RankingType, to_field='type_code', on_delete=models.PROTECT, related_name='ranking_profile_as_type', blank=False, default='btb_buyer' ) profile_name = models.CharField(max_length=64) price_weight = models.IntegerField(default=100) transhipment_weight = models.IntegerField(default=0) earliest_etd_weight = models.IntegerField(default=0) latest_eta_weight = models.IntegerField(default=0) def __str__(self): return f'{self.profile_name}' makemigrations and migrate work fine. I then run some code that loads the users_rankingtype table from a CSV and then users_rankingprofile from another CSV. The users_rankingtype table loads without problem, but when I try to run the code that loads the users_rankingprofile it fails on the first insertion with a ValueError: Cannot assign "'btb_buyer'": "RankingProfile.type_code" must be a "RankingType" instance. Here's the code that loads the table: file_in = path + 'users_rankingprofile.csv' count_rankingprofile = 0 with open(file_in) as csvfile: reader = csv.DictReader(csvfile) for row in reader: r = RankingProfile( profile_name=row['profile_name'], price_weight=row['price_weight'], transhipment_weight=row['transhipment_weight'], earliest_etd_weight=row['earliest_etd_weight'], type_code=row['type_code'], username=row['username'], latest_eta_weight=row['latest_eta_weight'], ) r.save() count_rankingprofile = count_rankingprofile + 1 I use PyCharm, and so I can inspect the RankingType table. The first row of the users_rankingtype table has btb_buyer in the type_code column is in the table. What am I doing wrong? Thanks and regards...Paul -
What is the best way to deploy a django app in 2020?
I have been looking for the best way to deploy my Django app I have been found some solutions and suggestions, but I'm still not sure which one is the best way. Many youtube videos suggest that the serverless solution such as 'Amazon Elastic or Google App Engine' is the best way. I would be very grateful if an experienced Django developer would share with me what is the best way to Deploy a Django application today. -
How to send value to filter in if condition django?
In my html, I want to send this values to my filter but I got this error : ValueError at / invalid literal for int() with base 10: '{{request.user.id}}' My HTML: <span><i{% if post|liked:"{{request.user.id}},{{post.id}}" %} class="fa fa-heart pointer" {% else %} class="fa fa-heart-o pointer" {% endif %} aria-hidden="true"></i> <span class="text-dark">{{ post.likes.count }}</span> My Filter: @register.filter() @stringfilter def liked(value, args): values = args.split(',') user_id, post_id = values user = User.objects.get(id=user_id) post = Post.objects.get(id=post_id) is_liked = post.likes.get(id=user_id) if is_liked != None: return True else: return False Thanks for any answer. -
ai want to separate products based on id stored in postgresql database in django tell me template syntax
i tried this {% for i in object %} {% if i.get(id=1) %} Rs {{i.price}} {% endif %} {% endfor %} but shows error like TemplateSyntaxError Could not parse the remainder: '(id=1)' from 'i.get(id=1)' -
How to test custom authentication backend in django
I wrote a custom authentication backend, I used it in my views to prove that it is working, however I would like to test it so in case it breaks in future for whatever reason, I would know. I think the problem may be because I have no request in the test, so no request is passed into the authenticate method. If this is the problem, then how can I pass a valid request into the authenticate method and test it so the test passes. In other words, can someone please show me a test that passes for the authentication backend below backends.py class EmailBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = User.objects.filter(email=email).first() if user.check_password(password): return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None test_backends.py class TestUserBackend(TestCase): def test_authenticate(self): user = UserFactory() authenticated_user = authenticate(email=user.email, password=user.password) self.assertEqual(authenticated_user, user) UserFactory() is from factory boy. I have also checked that user.password is hashed and the same as user.password which is also hashed. But I keep getting None != the user.email that was generated . Thanks for your help. -
Trying to inject one html page into another after an AJAX call but returning blank
I'm trying to inject an html template with a django function on it, into another html template. The function rests on an AJAX call for its variables. My AJAX call seems to be firing correctly (after checking in the Chrome dev tools) but the result is not showing on the html page as it should be. Here is the AJAX call //dashboard $(document).ready(function(){ console.log('Document Ready') $.ajax({ type: "GET", url : '/electra/playlist', dataType: "json", data: { 'venue': 'venue', 'list': 'list', }, success: function(data){ $("#playlist").html(data); console.log(data) }, failure: function(errMsg) { alert(errMsg); } }); }); Here is the html file where the Django function occurs playlist.html <!--what is the purpose of this fragmented code?--> <div class="user_playlists"> <ul> {% for item in playlist %} <li> <div> <h6 class="playlist-name">{{ item.list }}</h6> <h6 class="venue-name">{{ item.venue }}</h6> </div> </li> {% endfor %} </ul> </div> And here is the portion of the dashboard.html template where the playlist.html function should be injected: <body> {% block content %} <div class="container-fluid" style="padding:15px"> <!--location --> <div class="row"> <div class="col-sm-3"> <h3 class="list-heading"> Your Playlists </h3> <div id="playlist"> </div> </div> </div> </div> {% endblock %} Please note I have tried with {% include "playlist.html" %} and would like to avoid this if I can, … -
Why am I getting an smtp authentication with Django on PythonAnywhere
If you go on my webapp. You'll see a reset password option at the bottom of the login form but you need to register an account first and then try resetting your password. If you then type in your email and send, you will get a 500 Error page which I added custom styling to. So there was an error in my app in production, which does not show up in development. Everything worked perfect when I ran the localhost and tried it. I hosted my Django app on pythonanywhere so I went on my profile on PythonAnywhere and went to my log files and found this: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials m67sm7365001qkf.98 - gsmtp') 2020-10-10 08:08:56,103: OK: /password-reset/ Traceback (most recent call last): File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/contrib/auth/views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "/home/beefykenny/.virtualenvs/myenv/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) … -
Changing ordering of model in the admin views
I have a User model in Django, in which I defined class Meta with ordering. It's defined like this: class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('-speedy_net_site_profile__last_visit',) swappable = 'AUTH_USER_MODEL' But, I have two apps - Speedy Net and Speedy Match, and in Speedy Match I want a different order ( ordering = ('-speedy_match_site_profile__last_visit',) ). How can I do this? -
What is the appropriate way to use a ModelForm field as an argument to upload_to?
I have a ModelForm, where two of the fields are lastname and firstname. As several files are being uploaded by many different people, I would like to group the files into a directory based on their names. I've been trying to use a custom formatted string to do this, but so far I'm getting an error that there are not enough arguments for format string, and I am wondering if it as something to do with the form not being saved yet. My attempt to generate a filename based on form fields is: def filename_path(instance, filename): return os.path.join('applicant_documents/%s_%s/%s' % instance.last_name, instance.first_name, filename) and the field from my model is defined as: documents = models.FileField(upload_to=filename_path) Am I doing something wrong, or is this not possible? -
For what is better Django and for what Wordpress?
I asked this question because I would like to have an answer from a person with experience in that field. If something in my question is "wrong-formulated" tell me. (I know that Django and Wordpress are different thing, for this reason I'd want to know more) -
How to let PIL's Image.open find files from static?
I want to access a file in static from a module called "generate.py" inside my app. However I don't really have any idea how to do it. I believe I've properly "installed" the app because i can access the .html file in the App Things I've tried in generate.py 1 - from django.conf.urls.static import static Image.Open(static('resources/App/template/photothatiwanttoopen.jpg')) Error I get from code above: 'list' object has no attribute 'read' 2 - from django.conf import settings Image.Open(settings.STATIC_URL+'resources/App/template/photothatiwanttoopen.jpg') Error I get from code above: [Errno 2] No such file or directory: '/static/resources/App/template/photothatiwanttoopen.jpg' Here's my folder structure view - Project - App - templates - App - app.html - apps.py - generate.py <<< Script - models.py - urls.py - views.py - Project - settings.py and stuffs - static - resources - App - template - photothatiwanttoopen.jpg - manage.py and stuffs Here's last few lines of my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Let me know if you need any more information.