Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to correctly import urls.py from app?
This is probably pretty simple but I can't get my head around it. I'm learning Django, have v3.0.4 installed and can't get the URLs from an app to work correctly. On the project urls.py I have the following: Project\urls.py: from django.contrib import admin from django.urls import path from django.urls import include from AppTwo import views urlpatterns = [ path('', views.index, name='index'), path('', include('AppTwo.urls')), path('admin/', admin.site.urls), ] I've created an app named "AppTwo" and have the following urls.py and views.py in the app: AppTwo\urls.py: from django.urls import path from . import views urlpatterns = [ path('/help', views.help, name='help'), ] AppTwo\views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("<em>My Second App</em>") def help(request): return HttpResponse("<em>Help Page!!!</em>") If I browse to http://127.0.0.1:8000/ the index page loads and I see the text "My Second App" as expected. However if I browse to http://127.0.0.1:8000/help I get page not found 404 error. I can also browse to the admin page just fine. So far this is a stock project, the only other change I made after creating it was to the settings.py file to install the "AppTwo" application. Based on the documentation, this looks like it should … -
django cannot get static css to work in template base.html
I am trying to setup a site wide css file. My css will render if I place it directly in my block content cat register/templates/register/register.html {% extends "base.html" %} {% block title %}Create an Account{% endblock %} {% load crispy_forms_tags %} {% block content %} <style> .registration_base { padding-top: 50px; margin: auto; width: 30%; } </style> <div class="registration_base"> <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} </div> and it will function fine but I would like the code called from a style.css file site wide, in my base.html file. I cannot get the css file to actually render. In my templates/base.html I have <head> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}style.css"> </head> in my register/static/style.css I have the same css code: .registration_base { padding-top: 50px; margin: auto; width: 30%; } I can run #python3 manage.py findstatic style.css Found 'style.css' here: /home/user/www/src/register/static/style.css and it finds it, but my css formatting never changes. I have the app installed in site/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', 'register.apps.RegisterConfig', 'crispy_forms', ] How do I get a site wide css file properly included? -
how to detect url IP change in django
I am trying to detect the change in IP address for my website. If website IP address is changed, then redirect the page to login screen with new ip address. Detailed problem statement explanation given below Lets say website URL assigned to IP address 192.168.0.15 Login to the website and navigate to any page or just remain on the home page Change the website IP address to 192.168.0.12 (or something different from step 1) Select a link to a different page in already opened screen (in step 2) Confirm the Login screen is displayed. Could you please help me how this can be achieved in Django. -
django rest api not creating user
halo i'm working on a django rest_framework api code for user signup, but when i test the code with postman, they user doesn't get registered and it doesn't return any particular error, hoping anyone can help out, below is my models, serializers and views codes..... models class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=100) created = models.DateField(auto_now=True) timestamp = models.DateTimeField(auto_now=True) role = models.CharField(max_length=5) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: ordering = ('email',) objects = CustomManager() views @api_view(['POST', ]) def registration(request): if request.method =='POST': serializer = RegisterUserSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() data['response'] = 'registration successful' data['email'] = user.email else: data = serializer.errors return Response(data) Serializers class RegisterUserSerializer(serializers.HyperlinkedModelSerializer): confirm_password = serializers.CharField(style= {'input_type': 'password'}, write_only=True) class Meta: model = CustomUser fields = ['id', 'email', 'password', 'confirm_password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def save(self): user = CustomUser( email = self.validated_data['email'], ) password = self.validated_data['password'] confirm_password = self.validated_data['confirm_password'] if password != confirm_password: raise serializers.ValidationError({'password: Password didn\' match'}) user.set_password(password) user.save() return user -
ProgrammingError at /admin/auth/user/1/change/
Cant add user to group Cant add permission to a group or user I already used pgAdmin and django shell but same throwing this error ProgrammingError at /admin/auth/user/1/change/ The whole traceback: Traceback Switch to copy-and-paste view C:\Users\User\Envs\work\lib\site-packages\django\db\backends\utils.py in _execute return self.cursor.execute(sql, params) … ▶ Local vars The above exception (syntax error at or near "ON" LINE 1: ...ser_groups" ("user_id", "group_id") VALUES (1, 1) ON CONFLIC... ^ ) was the direct cause of the following exception: C:\Users\User\Envs\work\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\utils\decorators.py in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\views\decorators\cache.py in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\sites.py in inner return view(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py in change_view return self.changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\utils\decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\utils\decorators.py in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars C:\Users\User\Envs\work\lib\site-packages\django\contrib\admin\options.py … -
linkedin-oauth2 fails with "redirect_uri does not match the registered value" on Safari but works on Firefox and Chrome
I manage Presbot.com Linkedin works fine on Chrome, Firefox but fails with "The redirect_uri does not match the registered value" only on Safari. I am unable to track this issue down and need some guidance on debugging this. The linkedin App is configured with a redirect_url that starts with http. I suspect the issue is related to redirects but not sure how to debug. Any help would be appreciated. Server Os: Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-1021-aws x86_64) Web Server: nginx version: nginx/1.14.0 (Ubuntu) SSL: NGINX is configured with HTTPS certificates via Let’s Encrypt App server: Gunicorn (gunicorn==20.0.0) Web Framework: Django==2.2.4 social-auth-app-django==3.1.0 -
Django 3 and jQuery - sort <li> items on all paginated pages
Currently I can sort li items on one page but not all paginated pages. I select an item from a dropdown list to sort by various attributes based on a model. Here is the jquery for one of the items. ''' var sortIconsetsTitle = function () { $("ul.iconsets-list li[data-sort-title]").detach().sort(function(a,b){ return String($(b).attr('data-sort-title')) < String($(a).attr('data-sort-title')) }).appendTo($("ul.iconsets-list")) $('div.iconsets-sort span').text("Title"); // show the order by name }; $('li a.sort-title').on('click', function () { sortIconsetsTitle(); }); //make it so ''' The code works beautifully - but only on one page. How can I use this code to return results from all the paginated pages? -
Foreign Key between Django application
In Django, I would like to link foreign key from another app. Bellow is the method for same application, but in my case, they are two different applications on same project. App Client Model : name = models.CharField(max_length=64) App Invoice Model : client = models.ForeignKey('Client', on_delete=models.CASCADE) thanks -
Count the number times a choice is selected by users, and plot a chart based on the data
I have a model models.py ILLNESS_CHOICES = ( (1, "Anxiety"), (2, "Arthritis "), (3, "Asthma"), (4, "Anemia"), (5, "Cancer"), (6, "Covid-19"), (7, "Diabetes"), (8, "Ebola"), (9, "HIV"), ) class MedicalHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) illness = MultiSelectField(choices=ILLNESS_CHOICES) symptoms = models.CharField(max_length=100) additional_info = models.CharField(max_length=100) disability = models.BooleanField(default=False) medications = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Medical History' I am trying to plot a chart by counting the number of times an Illness is selected by users. I have seen similar questions from Count the number of occurrences of certain choices in models, Django Monthly/quartarly grouping of DateField() data and some other tutorials, but I am still not clear on how to approach. I am making use of Chart.js to display the data. views.py def pie_chart(request): labels = [] # illnesses as labels data = [] queryset = # get the count of each of the choices selected by users for entry in queryset: labels.append(#append the labels) data.append(#append the count of the choices) return JsonResponse(data={ 'labels': labels, 'data': data, }) Any help with this would be appreciated. -
Django how to annotate count nested forloop queryset dictionary
Good Day, My Problem is: my project depending on giving points to users who make any actions like (post, comment, favorite, likes ......). So, in users list page i want to list all users and other data for each user (name, points, badges, ....) to give the users points i have to count his posts, comments, likes, and so on..... i tried several methods and ways but all is failed to get annotate or prefetch_related or select_related Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') Views.py def user_list(request): users = User.objects.all() template = 'user/users_list.html' nested_posts = {} for user in users: posts = user.posts.all() nested_posts[user, posts] = posts.count() print("nested : ", nested_posts) context = { 'users': users, 'user':user, 'posts': posts, 'nested_posts': nested_posts,} return render(request, template, context) when i print nested .. i found the count of every user' posts .. but how can i make it as variable to re-use in calculated field QuerySet nested : {(<User: Fareed>, <QuerySet [<Post: Senior Purchasing Specialist>]>): 1, (<User: Hussein>, <QuerySet [<Post: Senior Software Development Engineer in Test>]>): 1, (<User: Karima>, <QuerySet []>): 0, (<User: Yahia>, <QuerySet []>): 0} and i also tried : GetUserID = User.objects.get(id=2) var01 … -
Append information to queryset to sort
I have Book and and Reader models, and each of them have m2m relationship with Author and Genre. For any given book, I have a function that iterates over all readers and calculates a likely_to_read score (from 0 to 100, details of how it's calculated aren't particularly relevant). I'd like to now have this function return a list of readers sorted by likely_to_read from highest to lowest, that also includes the calculated score, but I'm not sure what the best way of achieving this is. I know I can create a local dictionary that stores just the reader_id and likely_to_read score, and then reverse it by score and have another queryset where id__in=<ids>, but I'm wondering if there's some way to 'extend' the queryset with this score? -
What's the purpose of setting "X-Forwarded-For" header in nginx
I have the following Nginx configuration for my Django application: upstream api { server localhost:8000; } server { listen 80; location / { proxy_pass http://api; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /staticfiles { alias /app/static/; } } I based this config on a tutorial here. After some research, looks like setting the Host header allows the Django API to determine original client's IP address (instead of the IP address of the proxy). What's the point of the X-Forwarded-For header? I see a field called $http_x_forwarded_for in the nginx logs but I'm not sure it's related. -
Django swagger ui not accessible on nginx
I have setup Django using nginx, gunicorn and postgres as per below url. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 Now I am trying to access swagger ui. Nginx is up and running however showing default page. When I run the same project using, python manage.py runserver myip:8000 and then access the same url I can see actual swagger ui with rest end points. I am not sure what I am doing wrong here. Here is what I have added to nginx file. server { listen 80; server_name <myipaddress>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/threat-dashboard/backend; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/tmp/backend.sock; } } -
Clear entire cart with one button click - Django/Python
So I have a working shopping cart. You can add and delete items, one at a time. However, once payment is submitted, I want to be able to just click a button and delete all of the items in the cart at once. Here is what I have: Cart Views.py: def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse("cart")) try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = Cart.objects.all() cartitem.delete.all() return HttpResponseRedirect(reverse("cart")) The top section is what allows users to delete one item at a time. The second half is me attempting to use the same view on the same page to delete every cart item. Models.py: class CartItem(models.Model): cart = models.ForeignKey('Cart', null= True, blank = True, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete = models.CASCADE) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default = 10.99, max_digits = 1000, decimal_places=2) def __unicode__(self): try: return str(self.cart.id) except: return self.product.title class Cart(models.Model): total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) active = models.BooleanField(default=True) def __unicode__(self): return "Cart id: %s" %(self.id) Urls.py: url(r'^add-to-cart/(?P<item_id>[-\w]+)/$', add_to_cart, name="add_to_cart"), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='remove_from_cart'), url(r'^cart/(?P<slug>[\w-]+)/(?P<qty>\d+)/$', carts_views.update_cart, name='update_cart'), url(r'^cart/$', carts_views.view, name='cart'), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='clear_cart'), HTML: {% for item in cart.cartitem_set.all %} <a … -
e.preventDefault() not letting me submit my form
I wrote some javascript to validate a form. However, if the form fields pass all validations, the form never submits! Is my code somehow incorrectly preventing the form from being able to submit? If I delete all of the javascript and use browser's built-in validation then form executes fine and user is added to the database. const form = document.getElementById('form'); const first_name = document.getElementById('first_name'); const last_name = document.getElementById('last_name'); const username = document.getElementById('username'); const email = document.getElementById('email'); const password = document.getElementById('password'); const password2 = document.getElementById('password2'); // Show input error message function showError(input, message) { input.className = 'form-control is-invalid'; const small = input.parentElement.querySelector('small'); small.className = 'invalid-feedback'; small.innerText = message; } // Show success outline function showSuccess(input, message) { input.className = 'form-control is-valid'; const small = input.parentElement.querySelector('small'); small.className = 'valid-feedback'; small.innerText = message; } function checkRequired(inputArray) { inputArray.forEach(function(input) { if (input.value.trim() === '') { showError(input, `${getFieldName(input)} is required`); return false; } else { showSuccess(input, "Looks Good!"); return true; } }); } // Check email is valid function checkEmail(input) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (re.test(input.value.trim())) { showSuccess(input, 'Looks Good!'); return true; } else { showError(input, 'Email is not valid'); return false; } } // Check input length function checkLength(input, min, max) { if … -
Book value calculation in Django
quick question. I have the following model: class Shares(models.Model): name = models.CharField(max_length=128) ticker = models.CharField(max_length=128) date = models.DateField() quantity = models.FloatField(default=0) price = models.FloatField(default=0) currency = models.CharField(max_length=128) and I'm trying to calculate the book value of each position with the following view: class SharesListView(ListView): model = Shares context_object_name = 'shares_details' def get_context_data(self, **kwargs): context = super(SharesListView, self).get_context_data(**kwargs) latest_fx = fx_table.objects.last() queryset = context['shares_details'].annotate(book_value=Case( When(quantity > 0, then=F('price')*('quantity')), default= Value (0), output_field=FloatField() ) ) context['shares_details'] = queryset context['total'] = queryset.aggregate(sum=Sum('book_value'))['sum'] return context However I can't make it work. Would you please be able to help? Thanks in advance -
In wagtail how do I setup the v2 api to attach the full base url ( e.g. http://localhost:8000" ) to steamfield images and richtext embeds?
I am currently using nuxt.js as a frontend for my wagtail headless cms. When I load a richtext field or an image block within a streamfield I am unable, or don't know how to, attach the full base url of the wagtail server so when it gets rendered on the nuxtjs site it resolves to src="/media/images/image.png which in the end tries to find the image on the nuxtjs site http://localhost:3000 and it needs to find it on the wagtail server side http://localhost:8000. For standard images I can intercept and prepend the server base url, but not when it comes to anything inside a streamfield. -
Postgresql trigger fire for arrayfield on tsvector
We have the following model which creates a Trigger event for simple TextField on INSERT or UPDATE. from django.db import models from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() # New modifications. A field and an index content_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search"])] Custom migration file to create trigger event for postgres database. from django.db import migrations class Migration(migrations.Migration): dependencies = [ # NOTE: The previous migration probably looks different for you, so # modify this. ('web', '0002_auto_20190524_0957'), ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ] How to create a trigger event in the migration file for Arrayfield as tsvector_update_trigger expects text or varchar field.?? class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() tags = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) ### ['wordpress','drupal'] content_search = SearchVectorField(null=True) tags_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search","tags_search"]),] -
I would like to be able to redirect connected users to the main page and also use user_passes_test and login_required thank you
I created a user_passes_test (groups) to limit users according to user groups but when I redirect all the users already connected to the main page it creates a redirection loop and firefox displays 'The page is not redirected correctly' is the link to my home page is the link that is accessible to all connected users [is the page link which authorize when i want to leave d home page to this page with a user who is not authorized firefox referral The page is not redirected correctly Firefox has detected that the server is redirecting the request for this address in a way that will not be successful. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="{% static 'accounts/img/favicon.ico' %}"> <title>Authentification</title> <link href="{% static 'accounts/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'accounts/css/loguer.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static 'accounts/js/jquery-3.3.1.min.js' %}"></script> <script type="text/javascript" src="{% static 'accounts/js/bootstrap.min.js' %}"></script> </head> <body> <div class="container-fluid"> <div class="row"> <main role="main" class="col-sm-6 ml-sm-auto col-md-12 pt-6"> <div class="container"> <div class="card card-container"> <!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> --> <img class="profile-img-card" src="{% static 'accounts/img/academy.png' %}" /> {% if form.errors or error %} <p … -
Django rest frame work nested serializer doesn't update object
I have a model with a Foreign Key field and upon serialization of the object, I'm performing a create method on it which updates the field if it None. In the second serializer, I overwrote the update method to make sure that the data was inserted. I don't get any errors when running the update, yet, the field is not updated. models: class Mission(models.Model): # Some other irrelevant fields. area = models.CharField( name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(verbose_name="Date Added", default=now()) gdt = models.ForeignKey(KnownLocation, on_delete=models.PROTECT) class KnownLocation(models.Model): """ Add known location to map, But also use this as Base Object to describe locations as GDTs. :rtype Django base model for GeoLocation. """ name = models.CharField(name="Name", unique=False, primary_key=True, max_length=150, blank=False, help_text="Enter the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) elevation = models.FloatField(name="elevation", help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill. ", blank=True, null=True, verbose_name="Elevation" ) serializers: class KnownLocationSerializer(HyperlinkedModelSerializer): def create(self, validated_data): """ Checks if user inputted the elevation or left … -
Postgresql fire TRIGGER on BEFORE INSERT OR UPDATE on multiple columns in single query
from django.db import models from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() # New modifications. A field and an index content_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search"])] Custom migration file to create trigger event for postgres database. from django.db import migrations class Migration(migrations.Migration): dependencies = [ # NOTE: The previous migration probably looks different for you, so # modify this. ('web', '0002_auto_20190524_0957'), ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ] Trigger which works for only one column field content_search whenever Page table get's updated. How do I create a trigger event for both following multiple columns in single fire class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() content_search = SearchVectorField(null=True) title_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search","title_search"]),] -
Getting the correct data for the form in Django
Currently, I am getting the data from the whole database so I am attempting to filter it and then pass the filtered model to the form so only the data relevant to the user is shown. I did it according to what I found on google but I am getting this error: too many values to unpack (expected 2) It makes no sense to me as I am filtering the data as expected. Here is my code: models: from django.db import models from django.contrib.auth.models import User from posts.models import PDF from children.models import Children HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) child = models.ForeignKey(Children, on_delete=models.CASCADE) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) children model: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.urls import reverse from django.dispatch import receiver from django.db.models import signals DIAGNOSIS_CHOICES = [ (1, ("Yes")), (2, ("No")) ] class Children(models.Model): first_name = … -
Server-side implementation of image downloading in Django web app (images served from a remote location)
I'm trying to do a server side implementation of a download button for static assets (served via AWS S3) in a Django web app. What I've tried: I first tried the download attribute with a tags. But it doesn't cover Firefox in my experience (i.e. instead of the asset being downloaded, a new browser tab opens and the asset renders in that window). I tried a server-side solution once the aforementioned failed. Specifically, in an html template, I've got: <form method="GET" action="{% url 'download_image' %}" target="_blank"> <input type="hidden" name="img_url" value="{{ img_url }}"> <button>Download</button> </form> And in a view, I'm trying: def download_image(request): """ Download the image """ image_url = request.GET.get("img_url",None) # image_url value is //s3.eu-central-1.amazonaws.com/my-app/ebc4596f-d7db-340f-b7d6-4952c949f011.jpg if image_url: with open('https:'+image_url, 'rb') as fh: response = HttpResponse(fh.read(), content_type="image/jpg") response["Content-Disposition"] = 'attachment; filename="content.jpg"' return response This results in an IOError: No such file or directory: u'https://s3.eu-central-1.amazonaws.com/my-app/ebc4596f-d7db-340f-b7d6-4952c949f011.jpg' I feel I'm doing something fundamentally wrong. Can an expert guide me via an illustrative example? Thanks in advance. -
Django file upload using Dropzone.js
I am trying to add images to a blog post using Dropzone and Ajax and I cannot manage to upload the files successfully and my post object gets created without the images. I am not seeing any errors in the console but by images are not being added. my image form: class ImageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.fields['file'].required = False file = forms.FileField( widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class':'image_upload_form' })) class Meta: model = Images fields = ('file',) my post_create.html: {% load crispy_forms_tags %} {% load static %} <body> <form id="postCreate" method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form dropzone" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="overflow-y: auto; margin:0;"> <div id="loadingDiv"> <div class="d-flex justify-content-center mb-1"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> {{ form|crispy }} <div class="d-flex justify-content-left"> <div> <button type="button" id="upload-image" class="btn btn-sm mr-auto btn-primary pb-1 fileinput-button"> <span><i class="fas fa-image"></i></span> </button> </div> <div> <p class="pt-1 mx-2 text-muted small">Add up to four images to your post</p> </div> </div> <div id="previews" class="dropzone-previews"></div> <div class="fallback"> {{ image_form }} </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" id="submit-all" class="btn btn-primary">Post</button> </div> </form> <script … -
Transfer data from node application to django application both using postgres
How to efficiently insert data from one postgres database to another? I have a legacy node app which I am converting to Django. Both projects are using Postgres. The data schema in node app is vastly different from the new Django app. Therefore, I have written a script that maps old data into new data schema. The problem is that the script is painfully slow. 5 records a second. I have over 1 million records. What is the most efficient way to achieve this? My current script looks like: @transaction.atomic def migrate_users(cursor): select_query = "select * from users order by id" # old database cursor.execute(select_query) records = cursor.fetchall() for row in records: record_dict = {} record_dict['id'] = row[0] record_dict['name'] = row[1] record_dict['email'] = row[2] defaults = { 'name' : record_dict['name'], 'extra' : { 'old_node_db_values' : { 'id': record_dict['id'] } } } u, created = User.objects.get_or_create( email=record_dict['email'], defaults = defaults ) if created: u.set_password(DEFAULT_USER_PASSWORD) u.save() This is a simplified script. Actual data requires a lot of massaging.