Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass html file input, run python script on file, return file and string on webpage with django or flask
I have been doing some research and I can't seem to find what I am looking for. I wrote a python script using pandas to reformat an excel report. I would like to use the django or flask framework to build a simple site that allows the user to upload the file and then get the new one back all on the webpage. What is the best way to do this? -
Multiplying 2 Variables Together in Django
Hey so I'm looking to multiple (or add, any aggregation function really) the values of 2 django querysets together. I have tried this multiple ways and I am still running into a number of errors such as Request Method: GET Request URL: http://127.0.0.1:8000/paymentamount/ Django Version: 2.1.2 Exception Type: TypeError Exception Value: unsupported operand type(s) for *: 'QuerySet' and 'QuerySet' MODELS: class List(models.Model): vin = models.CharField(max_length=100, null=True, default=None) unit = models.CharField(max_length=10, null=True, default=None) year = models.CharField(max_length=4, null=True, default=None) make = models.CharField(max_length=100, null=True, default=None) model = models.CharField(max_length=100, null=True, default=None) trim = models.CharField(max_length=50, null=True, default=None) transmission = models.CharField(max_length=10, null=True, default=None) drivetrain = models.CharField(max_length=10, null=True, default=None) seats = models.IntegerField(default=0, null=False) kilometers = models.IntegerField(default=0, null=False) .... tier1book = models.FloatField(null=True, default=0) tierid = models.ManyToManyField('TDTier') class TDTier(models.Model): listid = models.ManyToManyField('List') bank = models.CharField(max_length=100, null=True, default=None) year = models.CharField(max_length=5, null=True, default=None) tier = models.CharField(max_length=100, null=True, default=None) frontendltv = models.FloatField(null=True, default=0) backendltv = models.FloatField(null=True, default=0) interest = models.FloatField(null=True, default=0) VIEWS: def payment(request): item = List.objects.all() item3 = List.objects.values_list('tier1book', flat=True) item6 = TD.objects.filter(list__year=F('year'), kmbottom__lte=F('list__kilometers'), kmtop__gte=F('list__kilometers')) item7 = TDTier.objects.filter(list__year=F('year'), tier=('5 Key')).values_list('frontendltv', flat=True) item8 = item3 * item7 return render(request, 'paymentamount.html', {'item8':item8) I get that trying to add 2 lists together does not work, however, Pythonic solutions do not seem to be … -
How to json response list of queryset from different models?
I have two models like this class User(models.Model): user_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=18) last_name = models.CharField(max_length=10) age = models.CharField(max_length=10) class Friend(models.Model): friend_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=18) age = models.CharField(max_length=10) friend_id and user_id is the same id's users = User.objects.filter(user_id=1) friends = Friend.objects.filter(friend_id=1) I make the union like this merge = list(users) + list(friends) [<User: User object (1)>, <Friend: Friend object (1)>] I want to do is a json response from merge HttpResponse(json.dumps(merge), content_type='application/json') I hope you understand my question and some idea of how to implement it -
Setup celery worker and celery beat (django app) on AWS ECS
I have a Django app with celery worker and beat, and I'm having a hard time trying to set up celery on ECS (The Django app was pretty straightforward). 1) What kind of service should I use for the worker and the beat: REPLICA or DAEMON? 2) What command could I use to the Healthcheck on the task definition configuration? I tried using supervisor and also simply calling the celery command directly in the command section of the task definition. I don't know what exactly I am missing... Supervisor configuration files: supervisor.conf: [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0700 ; sockef file mode (default 0700) [supervisord] logfile=/var/log/supervisor/supervisord.log ; supervisord log file logfile_maxbytes=50MB ; maximum size of logfile before rotation logfile_backups=10 ; number of backed up logfiles loglevel=debug ; info, debug, warn, trace pidfile=/var/run/supervisord.pid ; pidfile location nodaemon=false ; run supervisord as a daemon minfds=1024 ; number of startup file descriptors minprocs=200 ; number of process descriptors user=root ; default user childlogdir=/var/log/supervisor/ ; where child log files will live [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket [include] files = /etc/supervisor/conf.d/*.conf celeryworker.conf: [program:celery] command=/start-worker.sh directory=/app user=myuser numprocs=1 stdout_logfile=/var/log/app_logs/celery-worker.log stderr_logfile=/var/log/app_logs/celery-worker.log autostart=true autorestart=true … -
How to access Meta on CustomNode using Graphene and Relay
I want to make a generic get_node_from_global_id, so I need to get the root model the query is requesting and then return a row from that table. To do this I want to use model = getattr(Query,info.field_name).field_type.Meta.model . The first part, getattr(Query,info.field_name).field_type gets me TableNameNode from Query using info.field_name. But when I try to access ...Meta.model I get an error saying that there is no attribute Meta on TableNameNode. I can see that there is a nested class Meta so how can I access it? from graphene_django import DjangoObjectType from graphene import relay class CustomNode(relay.Node): class Meta: name = 'Node' @staticmethod def to_global_id(type, id): #returns a non-encoded ID return id @staticmethod def get_node_from_global_id(info, global_id, only_type=None): user = info.context.user model = getattr(Query,info.field_name).field_type.Meta.model #return row here... pass class Query(object): tablename = CustomNode.Field(TableNameNode) class TableNameNode(DjangoObjectType): class Meta: model = TableName interfaces = (CustomNode,) -
how to get the file of an image? in python ? django rest framework
class DemoAPIView(APIView): parser_classes = (JSONParser, FormParser, MultiPartParser) def post(self, request, format=None): data = request.data attached_file = request.FILES['attached_file'] description_image = data.get('descriptionImage', None) attachment = dict(object_id=174, project=1, attached_file=attached_file, description=description_image) header = {'Authorization': 'Bearer eyJ1c2VyX2F1dGhlbnRpY2F0aW9uX2lkIjoxNn0:1gSTf6:KbOb0yhqC-qVPTEPRoiVBBZjN6M'} r = requests.post('demo/api/v1/issues/attachments', data=attachment, headers=header) print(r.json()) return Response({'error': 'ERROR XD'}, status=status.HTTP_400_BAD_REQUEST) and the error that the api booted me is the following: {'attached_file': ['No file was submitted. Check the encoding type on the form.']} which is the image that I sent from the client. print the attached file and just show me the url, apparently that's the problem. Is there any way to get the full file? -
Django manage.py runserver command freezing on OSX
I have a few different systems that I use for development of a Django project. The main being Linux, then Windows, and then Mac...all systems implement development using Pycharm Up until about a week ago I was able to develop my Django project on Mac just fine, I could run the server and check updates as usual, however, for some reason I cannot seem to figure out, the terminal just freezes for about 5 minutes when I run: python3 manage.py runserver 8000 The server still starts after that 5 minutes but the startup time is quite literally awful, and I do not know what to look at to figure out where the issue is. I have not changed my code between work and home, just pulled directly from Git and I have the same issues. On my Windows System at home the Django app also runs within a few seconds of starting the server, as does the Linux system at work, so it seems to be only happening on OSX. Again, I am using Pycharm, but even if I manually enter the project directory and run the server, the startup time is slow Has anybody run into issues like this, … -
saving blob in django creates a file with size 0
I post an audio blob to django using ajax, before posting I do console.log(blob) //prints //Blob(262188) {size: 262188, type: "audio/wav"} //size: 262188 //type: "audio/wav" //__proto__: Blob Inside the django view: from django.core.files.storage import default_storage from django.core.files.base import ContentFile audio_data = request.FILES.get("recordedBlob", None) print(type(audio_data)) #prints <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(audio_data.size) #prints 262188 path = default_storage.save('audio/' + '123' + '.wav', ContentFile(audio_data.read())) But when I open the audio file in my file system, it is size Zero Bytes. Any idea how to save the blob correctly? -
What does format=None do in Django rest full API
Recently when I read Django rest full API document I faced this code : def get(self, request, format=None): """Return a list of APIView features.""" an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete).', 'It is similar to a traditional Django view.', 'Gives you most control over you logic.', 'Its mapped manually to URLs.' ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) this code is work fine but I look for format=None and I cant find out what does it do. is any body know what is it and why its important to be? -
'NoneType' object has no attribute 'add'
I have the following User object, class User(AbstractBaseUser, PermissionsMixin, Base): username = models.CharField(db_index=True, null=False, unique=True, max_length=255) mobile = PhoneNumberField(db_index=True, null=False, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And I've the following class to manage connections, class Connections(Base): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True) friends = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friend_set', null=True, blank=True) followers = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_set', null=True, blank=True) followings = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following_set', null=True, blank=True) When I try to add a friend, sender = User.objects.get(id=kwargs.get('sender_id')) receiver = User.objects.get(id=kwargs.get('receiver_id')) sender_connections, created = Connections.objects.get_or_create(owner=sender) sender_connections.friends.add(receiver) I get the following error, 'NoneType' object has no attribute 'add' Can someone help me with this? -
Django template variable does not show up
for some reason im unable to display the comments of a category_request and i have now idea why, is smb. maybe able to have an eye on that, praticaly i should work but i dont see the mistake here. as far as i see I'm using category_request_comment from the view to get a releated comment objects from a category_request... any idea? Template Snippet: {% for category_request_comment in category_request_comments %} <div class="comment"> <p>{{ category_request_comment.content|readmore:15 }}</p> {% if category_request_comment.content.published_date %} <div class="date"> <a>Comment by: {{ category_request_comment.author }}</a><br> <a>Commented at: {{ category_request_comment.published_date }}</a> </div> {% endif %} {% if request.user == category_request_comment.author %} <a class="commentoption" href="{% url 'comment_edit' pk=category_request_comment.pk %}">Edit</a><a> | </a> <a class="commentoption" href="{% url 'comment_delete' pk=category_request_comment.pk %}">Delete</a> {% endif %} </div> {% endfor %} views.py def category_request_detail(request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) list_category_request = CategoryRequests.objects.get_queryset().filter(id=pk).order_by('-pk') paginator = Paginator(list_category_request, 20) page = request.GET.get('page') category_request_comment = paginator.get_page(page) return render(request, 'myproject/category_request_detail.html', {'category_request': category_request, 'category_request_comment': category_request_comment}) views.py (only for Reference) def category_request_comment_new(request, pk): if request.method == "POST": form = CategoryRequestsCommentForm(request.POST) if form.is_valid(): category_request = get_object_or_404(CategoryRequests, pk=pk) requests_comment = form.save(commit=False) requests_comment.author = request.user requests_comment.published_date = timezone.now() requests_comment.category_request = category_request requests_comment.save() return redirect('category_request_detail', pk=requests_comment.category_request.pk) else: form = CategoryRequestsCommentForm() return render(request, 'myproject/comment_new.html', {'form': form}) urls.py url(r'^categories/requests/$', myproject_views.category_request_list, name='category_request_list'), … -
Why doesn't Django 2.1 login_required work when parameter is present
In urls.py I have: ... path('/admin/login', login_required(admin.site.login)) This reroutes to a custom authentication view, specified in settings.LOGIN_URL. When you go to /admin it redirects to /admin/login?next=/admin, which does not redirect to LOGIN_URL. But when you go to /admin/login directly, everything works correctly. Note: This worked correctly in Django 1.11. -
Django not loading static CSS file
I have looked around on this site as well as others and still have not found a solution that works for why django is not loading my css file my settings.py file: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] in my html file: {% load static %} <link rel="stylesheet" href="{% static '/css/my_style.css' %}"> My file tree: todo_app static todo_app todo_list db.sqlite3 manage.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo_list', ] Any help would be greatly appreciated. I tried using the STATIC_ROOT as shown on a different thread but there was no change with that. -
django using ModelAdmin.list_editable in view
I have a model: class Question(models.Model): question_text = models.CharField(max_length=200, unique=True) pub_date = jmodels.jDateField(verbose_name='date published') def __str__(self): return self.question_text I want to edit one field of all objects of this model in a view via ModelAdmin.list_editable (from the documentation: Set list_editable to a list of field names on the model which will allow editing on the change list page. That is, fields listed in list_editable will be displayed as form widgets on the change list page, allowing users to edit and save multiple rows at once) (I want to edit this in a view not admin) for better understanding this can be the result: enter image description here Is it possible? -
Download a File through Django
I am making a file serving system that organizes different files based on categories. Once a user finds the file they need, they click a download button and it downloads it. These files are of all different kinds pdf, ai, video, etc. I was using the download attribute on HTML and it was working find locally but then I found that it didn't work when I pushed it to a hosting service. I have read 20 different posts about using Content-Dispostion but I am having trouble even getting to that point. I don't have much to go on at all but below is my attempt to even access the file to be able to push it back to the user. Honestly I am just not sure of where to go from here. I just want the use to be able to click a button and the django-filer file downloads Let me know if I need to inlclude anything else. def asset_detail_view(request, slug, *args, **kwargs): obj = get_object_or_404(Asset.objects.prefetch_related('file_set'), slug=slug) context = { 'object': obj, } return render(request, 'detail_view.html', context) def search(request): queryset = Asset.objects.prefetch_related('file_set').all() filter_set = AssetFilter(request.GET, queryset=queryset) return render(request, 'asset_filter_view.html', {'filter': filter_set}) def download(request, slug): download = File.objects.filter( asset__slug=slug ).first() … -
Django Using reverse() with multiple URLs that include the same app
So I have a django project with a single app, and I have two different url patterns mapped to this one app. I currently have this mostly working, however for a few cases using reverse() results in the wrong namespace. My base urls.py looks like this: from django.conf.urls import url, include from django.views.generic.base import RedirectView urlpatterns = [ url(r'^api/', include('api_project.api_app.urls', namespace='api')), url(r'^beta/api/', include('api_project.api_app.urls', namespace='beta')), url(r'^$', RedirectView.as_view(url='api', permanent=False), name='index') ] In most cases reverse works as expected, e.g. using /beta/endpoint has links on the page that look like: /beta/endpoint/example However, in a few cases using /beta/endpoint has links like: /api/endpoint/different-example My question is less about how reverse determines which namespace to use, but instead is this the appropriate way to use two namespaces for the same app? Is this something I should approach completely differently? Most of my research so far has not resulted in much success, so I'm thinking this might be fundamentally the wrong approach. If this approach is okay, then I'm curious why reverse is inconsistent in which namespace it returns. -
Error when creating admin in django tutorial
I am following the Django tutorial and am stuck on the second part, where I have to create an admin account. I followed everything described in the tutorial up to that point and get the following error: Traceback (most recent call last): File "e:\venvs\django_tutorial_venv\lib\site-packages\django\utils\module_loading.py", line 20, in import_string return getattr(module, class_name) AttributeError: module 'django.contrib.auth.password_validation' has no attribute ' UserAttributeSimilarityValidator' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 26, in get_password_validators klass = import_string(validator['NAME']) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\utils\module_loading.py", line 24, in import_string ) from err ImportError: Module "django.contrib.auth.password_validation" does not define a " UserAttributeSimilarityValidator" attribute/class During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 163, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "e:\venvs\django_tutorial_venv\lib\site-packages\django\contrib\auth\password_validation.py", line 29, in get_password_validators raise ImproperlyConfigured(msg % validator['NAME']) … -
Fill model field with default value instead of null
I have my model defined like this: class Activity(models.Model): country = models.CharField(max_length=100, default="Unknown") country field is filled from JSON response, but sometimes is not available. I am currently getting django.db.utils.IntegrityError: NOT NULL constraint failed: explorer_api_activity.country I have tried different combinations of null=True, blank=True and getting rid of the default, and also deleting migrations and the database, but to no avail. I want to fill the field with "Unknown" whenever null is encountered. How do I do this? -
Auto create related model
I am wondering if it's possible to auto create a related model upon creation of the first model. This is the models class Team(models.Model): name = models.CharField(max_length=55) class TeamMember(models.Model): team = models.ForeignKey('Team', on_delete=models.CASCADE, null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) So what I want to do is something like this on the 'Team' model class Team(models.Model): name = models.CharField(max_length=55) @on_new.do_this TeamMember.team = self TeamMember.user = request.user TeamMember.save() I have tried to find any documentation about this. But only found some example about onetoonefields. But nothing about this. Appreciate any help. Cheers! -
Why does img.thumbnail adjustment raises FileNotFoundError [Errno2] No such file directory?
I have a django blog application that is deployed on Heroku and has images being served from AWS S3 Bucket. When a user attempts to upload an image, we use PIL to thumbnail resize the dimensions based on an if condition (as shown in models.py below). When I attempt to update profile image, it throws the dreaded: FileNotFoundError at /profile/ [Errno 2] No such file or directory: 'profile_pics/0umkn7tybif11.jpg' The traceback of the error also shows what appear to be these key lines: /app/users/signals.py in save_profile instance.profile.save() ... ▶ Local vars /app/users/models.py in save img.save(self.image.name) ... ▶ Local vars /app/.heroku/python/lib/python3.6/site-packages/PIL/Image.py in save fp = builtins.open(filename, "w+b") ... ▶ Local vars My models.py file seems to contain the code being addressed in this error: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.core.files.storage import default_storage as storage class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open(storage.open(self.image.name)) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.name) Lastly, if I remove the following code from the models.py file, the app functions properly: if img.height > 300 or img.width > 300: output_size … -
Send data, query a table based on that data and render
I'm developing a spatial data infrastructure. It's based on a webapp created with Django. The webapp has a map, you can draw polygons on it. Based on the polygon you drew, specific data should be returned to the client. So the flow looks like this: you put points on the map, it becomes a polygon after the third point. You press a button which triggers a putData js function and sends data to the appropiate view with a GET request & the view puts the data in a postgres datatable. All fine until this point. In the putData function's success callback I specify another get request, without data. The view which handles this request gets the last row from the above specified postgres table, make queries to another datatable with the values from the last row and renders the result of the query with a html page. The problem is that the render never happens. The page where I pressed the button just stays like it is, and no redirect happens. TL;DR: I want to put data in a postgres table with a get request, get values from that table with, query a second table and render a second html … -
Django filter query and or and
I'd like to use AND OR AND in one filter method, is it possible to do without custom query? Something like that: .filter((Q(condtion) & Q(condition)) | (Q(condition) & Q(condition))) -
Wordpress as a blog with already existing django app
I have an existing django app, and I want to add a blog to it, and we decided to use WordPress for the blog as a subdomain "www.example.com/blog" for the sake of seo. so Django is served by Nginx and uses Postgress database, I assume that WP will use MySQL and will still be served by Nginx, So how can I tweak the Nginx config to make this happen, because I tried old solutions and none of them worked. and if you have another suggestion please advice, FYI, the server is Ubuntu 18.04 and php7.2 is installed. -
Which programming languages are the best way to develope mail marketing automation like Mailchimp, Sendgrid etc?
Do you think which programming languages combination (backend and frontend) for the best choice to develop apps like Mailchimp, Sendgrid, Campaign Monitor etc email marketing automations? Because as you know these apps needs ingenious SQL queries. Also, these apps have real time email design editor, advanced contact list management, comprehensive reports, unsubscriber handling, triggering campaigns and marketing automation campaigns, storing sample newsletter templates, API integrations. Surely I know, mail hosting, IP blocks and some reliable certificates are play key role in email marketing. What are your thoughts of this subject? I look forward to your precious and informative replies! Thanks in advance. -
Django 2.1 on Heroku "relation "auth_user" does not exist" with postgres
I'm trying to create a django app on heroku, i was trying to log in into the admin interface but every time it was giving this error : relation "auth_user" does not exist and i can't understand why, i'm using postgresql with the heroku-postgress ad-don. I've run all the migrations and tried dropping the database and recreating it. I'm using the django-heroku module to configure the database. I don't really know what information might be useful so if you need something i'll edit the question. Thanks in advance to everyone.