Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access .env variables with django-environ in travis ci?
I'm trying to integrate travis ci with my django project using django-environ but i keep getting the same error in the travis ci build: UserWarning: Error reading /home/travis/.../.env - if you're not configuring your environment separately, check this. django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable Looks like django-environ can't find the environment variable. I already tried exporting the SECRET_KEY variable through the .travis.yml file like this: .travis.yml config. But still does'nt seem to work. Here's my .env file: .env And part of my settings.py: settings.py I also tried setting the variable in the travis ci project configuration page. -
How to return an array of images through HttpResponse in Django?
Suppose I had a Dog Object and it had fields like name, weight, and breed. Serializing these and returning them was easy as they were strings. I then added a field called image_url, which was the s3 path (I am storing their images in my s3 bucket). In my DogView (which returns all the dogs a user owns), I would have something like this: class DogsView(ListAPIView): def get(self, request): user = request.user dogs = Dog.objects.filter(user=user) dog_serializer = DogSerializer(dogs, many=True) s3 = boto3.resource("s3") for dog in dog_serializer.data: if len(dog["image_url"]) > 0: s3_object = s3.Object('my-dog-photos', dog["image_url"]) file_stream = io.StringIO() s3_object.download_fileobj(file_stream) img = img.imread(file_stream) dog["image"] = img return Response(product_serializer.data) However, when I do this, I get TypeError: string argument expected, got 'bytes' How would I be able to append my bytes/file to my serializer.data (or just return an array of images via HttpResponse) ? -
Annotate SQL Function to Django ORM Queryset `FUNC` / `AGGREGATE`
I am trying to do something very similar to: Annotate Custom SQL Function (similar to date_trunc) to Django ORM Queryset but have found the solution to be inadequate. Using the same example as found in the prior link, suppose we have a Django model as such. class Measurement(models.Model): device_id = models.IntegerField(primary_key=True) time = models.DateTimeField() s0 = models.FloatField(blank=True, null=True) s1 = models.FloatField(blank=True, null=True) We are trying to leverage the following in the ORM. SELECT time_bucket('1 minute', time) AS tb, AVG(s0) FROM measurements WHERE time >= to_timestamp(1) AND time <= to_timestamp(2) GROUP BY tb ORDER BY tb ASC; We have a successful custom function as such: class TimeBucket(Func): function = 'time_bucket' template = '%(function)s(\'{bucket_width}\', %(expressions)s)'.format(bucket_width='1 minute') But we see that running a query like the following: qs = ( Measurement.objects .filter(...) .annotate(tb=TimeBucket('time')) .values('tb') .annotate(s_desc=Avg('s0')) .order_by('tb') ) and checking its corresponding `qs.query` will always include `time` in the GROUP BY query. I **only** want to group by `tb`, the derived value, as shown in the original SQL. From what I'm reading, you need only use `values('tb')` as we are doing above to group by `tb`, but Django seems to append on `time` for some reason. Why is this the case? -
How to avoid a footer from behave like a div?
The footer from my homepage is behaving like a div - just after the content and not at the bottom of the page - only in my home page, i.e., at the store.html file. In all the other pages it behaves as expected. I've lost more time trying to solve this than I'd like to say... What am I missing? footer.html <footer> <div class="container">Helga's</div> </footer> main.html <head> ... </head> <body> {% include 'store/navbar.html' %} <div class="container"> <br> {% block content %} {% endblock content %} </div> {% include 'store/footer.html' %} <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <script type="text/javascript" src="{% static 'js/cart.js' %}"></script> </body> store.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row h-50"> {% for product in products %} <div class="col-lg-3"> <a href="#"> <img class="thumbnail" src="{{product.image_url}}"> </a> <div class="box-element product"> <h6 style="text-align: center;"><strong>{{product.name}}</strong></h6> <hr> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn btn-sm update-cart">Buy</button> <h4 style="float: right; font-size: 22;">R${{product.price|floatformat:2}}</h4> </div> </div> {% endfor %} </div> {% endblock content %} -
Multiple filters via Django template
I could do something like this via views.py: context['filtered'] = model_name.objects.filter(field1__title='value1', field2__title='value2') and call the context from within a template to get the returned value. My question is, is it possible to instead run multiple filters such as the above via a django template using a context of model.objects.all()? may need to make use of a custom filter? -
How does deploying Flask application to a Bluehost (or any) web-server work?
More specifically, I have some Flask code that reads from an Excel file in my directory, then it web-scrapes another website every minute for new data, and appends it back into that same Excel file. That database is then available for download on my localhost. Everything works fine on my computer and on localhost, but I am just confused how exactly this would work when it is running on a web-server and not on my computer. I have been digging around Stackoverflow for answers/explanations, but I still have not stumbled upon an answer that could explain how this works or if it is even possible. Thank you in advance for your time! -
Adding custom date to DateTimeField in Django?
Say I have a model with a field as such: begin_date = models.DateTimeField(blank=True) Whenever I want to add a date using a string, for example, '2020-06-15T11:00' it gives me the RuntimeWarning: received a naive datetime while time zone support is active. So what's the proper way of adding date to a model in Django? -
Associating almost every table, of a preexisting Django project, with the credentials of the logged in user
Let's say that, in a preexisting Django Project, I have to record -- in almost every of the project's tables -- the information about the logged in user responsible for the change in said tables. The first thing that occurred me was the obvious: a ForeignKey to every table and the respective code in view.py to fill in those fields... But it has to be a better way. Doesn't? I could also just store the username in plain text, but common, that is plain wrong. Just to clarify, the object is two fold. First, to create a accountability log. Second, to allow that the information could be filtered and displayed differently based on the logged in user. And just to improve on the question, let's say that I had to do this from the beginning of the project. How would you guys do it? Many thanks. -
How to get attribute from get_field
I would like to get a max_length from content TextField of my model. Actually I have something like this: max_length = Comment._meta.get_field('content') -
'QueryDict' object has no attribute 'is_authenticated'
this my login views function def login(request): context = {} user = request.POST if user.is_authenticated: return render(request, "login.html") form = LoginForm(request.POST or None) if request.POST: form = LoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.POST['email'] password = form.cleaned_data.POST['password'] user = authenticate(request, email=email, password=password) if user: login(request, user) if user.user_type == '1': return render(request, "administrateur.html") elif user.user_type == '2': return render(request, "entrepreneur.html") else: print("errors") form = AuthenticationForm() context['login_form'] = form return render(request, "entrepreneur", context) when i refresh my webpage i receive this error: 'QueryDict' object has no attribute 'is_authenticated' when i print(user) it show me this : what is my errors??? -
apache server running but django site not loading (used wsgi)
I'm using AWS EC2 ubuntu 18.04 instance running apache2 server to load my django site using wsgi. I've managed to get apache server running but when I try to open the page using my ip on browser, is says the site couldn't be loaded. The server is listening on port 80. I'm using a virtualenv to run django project. DaemonProcess is used to run venv as python home. The /etc/apache2/sites-available/django.conf file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html LogLevel error ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /project/src/static <Directory /project/src/static> Require all granted </Directory> Alias /media /project/src/media <Directory /project/src/media> Require all granted </Directory> <Directory /project/src/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /project/src/project/wsgi.py WSGIDaemonProcess shout_app python-path=/project/src python-home=/project/venv WSGIProcessGroup shout_app </VirtualHost> The /var/apache2/error.log file after restarting apache and loading ip: [Sun Jun 14 21:07:30.830952 2020] [suexec:notice] [pid 16647:tid 139870270000064] AH01232: suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec) [Sun Jun 14 21:07:30.840208 2020] [:notice] [pid 16663:tid 139870270000064] mod_ruid2/0.9.8 enabled [Sun Jun 14 21:07:30.843684 2020] [mpm_event:notice] [pid 16663:tid 139870270000064] AH00489: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.1 configured -- resuming normal operat$ [Sun Jun 14 21:07:30.843701 2020] [core:notice] [pid 16663:tid 139870270000064] AH00094: Command line: '/usr/sbin/apache2' The wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = … -
Streaming webcam video from a mini-PC to a Django-based webserver in the cloud
I'm currently working on a project which requires using a mini computer running Windows to capture frames from a USB Camera and stream it to a Django-based server in cloud. The architecture of the problem can be described as follows I managed to implement a Python script using OpenCV that extracts the frames. However, I am still unsure about how would be the appropriate solution for streaming those frames to a Django-based webserver in the cloud. I am considering using Socket (UDP or TCP) Websockets Is it the correct way of streaming frames from a python script to a webserver? I appreciate any advice. Thank you very much! -
Success/Error Messages Not Showing in Django?
I'm not quite sure why, but the success/error messages are not displaying when I complete the checkout process on my website. For example, if you successfully make a payment you should receive a popup with the message You have successfully paid, but it doesn't pop up. I'm not sure if anyone can see any issues with how the checkout view has been set up? I've added it below. def checkout(request): """ Returns the checkout page and allows the user to enter the personal and payment details in order to complete their order """ if request.method == 'POST': order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() customer = Customer.objects.get(user=request.user) order.customer = customer order.save() cart = request.session.get('cart', {}) total = 0 for (id, quantity) in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price order_line_item = OrderLineItem(order=order, product=product, quantity=quantity) order_line_item.save() try: customer = stripe.Charge.create(amount=int(total * 100), currency='GBP', description=request.user.email, card=payment_form.cleaned_data['stripe_id']) except stripe.error.CardError: messages.error(request, 'Your card was declined!') if customer.paid: messages.success(request, 'You have successfully paid') request.session['cart'] = {} return redirect(reverse('products')) else: messages.error(request, 'Unable to take payment') else: print(payment_form.errors) messages.error(request, 'We were unable to take a payment with that card!' ) else: payment_form = MakePaymentForm() order_form … -
I want to print both, keys and values of dictionary which I pass in render to a HTML page in Django
This loop format in html is only printing the key but not value,I want to print both key and value in html page. views.py def predict(request): if request.method == "POST": dict = {'Name': John, 'Age': 40} return render(request,'standalone.html',{'content':dict}) else: return render(request,'test_homepage.html') satandalone.html {% for c in content %} {{c}} {% endfor %} -
Collaborative text editing with Django Channels
I have a relatively full-featured Django application which already works with Django Channels for live page updates and on-page live chat (Redis channel layer backend). If it is relevant I also have Celery working in the background to synchronise data with external APIs. I am trying to allow site visitors to collaboratively edit text on various pages (with some formatting preferred). I'd like to store the data using the Django ORM (I am using a Postgres DB) and don't need offline editing capability. Is anyone familiar with a possible solution here? I have been searching for a long time and most solutions require alternative full 'stacks'. Ideally I can use something that already leverages the existing Django Channels Websocket connection. I have found these options so far: Firepad - Requires a connection to a Firebase server (and therefore another account) Codox.io - Initial set-up didn't work and would prefer not to pay an additional subscription fee ShareDB - Looks great, especially with the in-memory implementation. I just don't know how to integrate with Django Channels! Any pointers would be greatly appreciated. -
Django application shows default page of nginx on ip after succesfully deployed on nginx and gunicorn
I am trying to run application on given ip but it is showing default page Also there is no problem with nginx and gunicorn they are running fine I also removed default file as I read in other answers. but no solution is working for me Any help will be highly appreciated server { listen 80; server_name 142.93.206.139; listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; include snippets/self-signed.conf; include snippets/ssl-params.conf; location = /favicon.ico {access_log off;log_not_found off;} location /static/ { root home/akshit/django/django-dashboard-material/core; } location / { include proxy_params; proxy_pass http://unix:/home/akshit/django/django-dashboard-material/core.sock; } } -
Django Key error while parsing json dict from a web request
I have searched stackoverflow for a solution to my problem however none of them solved the issue hence I am creating a new question. I created a web request using requests package in django app view and able to get the response back as json dict. Next step - I am parsing the json object to map the keys to model elements to save the data however I am getting a key error. I have eve tried to create a function to check if the key exists but that does not solve the issue and returns only a key error issue. Code I have tried so far.. First Approach data = response.json() for key in data: my_placeholder = my_model_name( field_name = item.get(data['name'],None) ) my_placeholder.save Second Approach using a function: def valuechecker(valinput): if len(valinput) >0: return valinput else: return None -- as part of my main def: data = response.json() for key in data: my_placeholder = my_model_name( field_name = valuechecker(data['name']) ) Appreciate if anyone can help solve this. Also, is there a way I can check if my_placeholder is valid? I tried my_placeholder.is_valid and I am getting an error as does not have attribute is_valid. Please advise Thank you! -
Choose from Sub-Sub-Category of a Sub-Category of a category in Django Admin & Forms.py
I want something like this in Admin & Template where user can add & select from Sub-Sub Category within a Sub-Category of a category. Explaining the Scenario: We have a Category named Skills Which further can have Sub-Categories like > Technical Skills/Vocational Skills etc Further, these sub-categories can have Sub-Sub-Categories e.g Technical Skills can Have > C/CPP/Java, etc. This Pic Describes what I Need in Admin Panel -
NoReverseMatch at /movies/category/action
I can't find the problem, please help me out. I use namespace='movies' in urls.py file Reverse for 'movie_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['movies/(?P<slug>[-a-zA-Z0-9_]+)$'] url.py app_name = 'movie' path('category/<str:category>', MovieCategory.as_view(),name='movie_category'), view.py class MovieCategory(ListView): model = Movie paginate_by = 2 def get_queryset(self): self.category = self.kwargs['category'] return Movie.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super(MovieCategory, self).get_context_data(**kwargs) context['movie_category'] = self.category return context html <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'movies:movie_category' 'action' %}">Action</a> <a class="dropdown-item" href="{% url 'movies:movie_category' 'comedy' %}">Comedy</a> <a class="dropdown-item" href="{% url 'movies:movie_category' 'drama' %}">Drama</a> <a class="dropdown-item" href="{% url 'movies:movie_category' 'romance' %}">Romance</a> </div> -
Getting Python Django 'SERVER_PROTOCOL' TypeError: 'NoneType' object is not subscriptable
I wrote the PUT request API to set the user password. I wrote so many views but I am not experiencing any issue like in below view function. views.py @api_view(['PUT']) @permission_classes([]) def setForgotPasswordWithNewPassword(request): data = request.data print(data) user = User.objects.get(username=data['username']) secret_key = request.data['secretkey'] backend_secretkey = cache.get('reset_pwd_%s' % (data['username'])) if backend_secretkey: if backend_secretkey == secret_key: if user: user.set_password(data['password']) # print(user.password) user.save() return Response({"msg":"Your password has been successfully changed"},status=200) else: return Response({"error":"Username does not exist on our system"},status=403) else: return Response({"error": "Your not authorized to use this link"}, status=403) else: return Response({"error": "Your password link has been expired, please try again"}, status=403) Using Postman I am not getting any Exception on command line. but when I am hitting this API using my Angular project getting the below exception and due this exception wsgi server loaded again so angular loaded to again front page. But changing password working. so I am curious to know about this error which I am experiencing. error: [15/Jun/2020 00:34:01] "PUT /api/setForgotPasswordWithNewPwd/ HTTP/1.1" 200 53 Traceback (most recent call last): File "C:\Users\vipin\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\vipin\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\vipin\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\vipin\AppData\Local\Programs\Python\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File … -
How to solve HTTP 403 error on input of data in Django Ajax?
I am trying to implement a search function to search for users of my blog. In my base.html I have my navbar and within the navbar I have the following search form: <form class="form-inline" method="POST"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">@</span> </div> {% csrf_token %} <input id="user_search" type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1"> <ul class="list-group" id="results"></ul> </div> </form> My ajax code looks as follows: $('#user_search').keyup(function(){ $.ajax({ type: 'POST', url: "{% url 'user-search' %}", data: $(this).serialize(), dataType: 'json', success: function(response){ $('#results').html(response['form']); console.log($('.profile-section').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); and my views.py search view looks as follows: def user_search(request): if request.method == 'POST': search_text = request.POST['search_text'] else: search_text = '' users = User.objects.filter(username__icontains=search_text) context = { 'users': users, } if request.is_ajax(): html = render_to_string('feed/user_search.html', context, request=request) return JsonResponse({'form': html}) and the relevant part of my urls.py looks like this: path('search/', login_required(views.user_search), name="user-search"), When entering data in the input field I am getting a 403 HTTP error that says I am not using the csrf_token correctly, however I have included it as I did it before and it worked the other times before... Any idea how I can solve the 403 error? -
Django CMS Modify Uploaded File
I'm new to Django and Django CMS, but I'm developing a plugin for displaying uploaded images with some text. The plugin works well, but I would like for the user to upload an image and then have actions performed on it before it is stored (specifically, to modify the image size and resolution to create uniform file sizes on the server without relying on frontend css). How could I accomplish this or something similar? -
About django/restframework request
This is my APIview: class Comments(ListCreateAPIView): queryset = models.NewsComment.objects filter_backends = [CommentsFilterBackend] http_method_names = ["get", "post"] def get_serializer(self, *args, **kwargs): if self.request.method = "get": return Myserializer I want to know why self.request can call the "method". Isn't it the encapsulated Request new object? The native request object is encapsulated in Request obj. Why can self.request call the request.method attrs? -
Django form not saving even after everything seems all right
My view: ''' from django.shortcuts import render from django.http import HttpResponse from .models import Post from .forms import createPostForm def showPosts(request): if request.method == "POST": crf = createPostForm(request.POST) crf.author = request.user crf.save() else: crf = createPostForm() context = { 'post' : Post.objects.all(), 'crf' : crf } return render(request, 'Content/FeedsPage.html', context) ''' My Model: ''' from django.db import models from django.contrib.auth.models import User class Post(models.Model): # image = models.ImageField(blank=True, null=True, upload_to='post_images/') # video = models.FileField(blank=True, null=True, upload_to='post_videos/') title = models.CharField(max_length=100) description = models.CharField(blank=True, max_length=1000) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title ''' My Template: ''' <form enctype="multipart/form-data" novalidate method="post"> {%csrf_token%} <div class="fieldWrapper"> {{crf.title.errors}} {{crf.title}} </div> <div class="fieldWrapper"> {{crf.description.errors}} {{crf.description}} </div> <button class="primaryButton" type="submit">submit</button> </form> ''' My Form: ''' from django import forms from .models import Post class createPostForm(forms.ModelForm): title = forms.CharField( widget = forms.TextInput(attrs={ 'placeholder': 'Give a sweet title', 'autocomplete' :'off' }) ) description = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Please elaborate a little', 'autocomplete' :'off' })) class Meta: model = Post fields = '__all__' ''' I removed the is_valid() function to see whats happening and apperently its showing 'The Post could not be created because the data didn't validate' Please somebody help -
How to mock a function that returns a user object
I am trying to mock a method that returns a user object like so @mock.patch('impersonate.helpers.which_user', return_value=self.user2) def test_user_can_retrieve_favs_using_impersonation(self): It's failing with the error: NameError: name 'self' is not defined . I defined self.user2 in the setup method of the test class.