Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data too long for column when creating user
By going to url(r'api/users/', views.MyUserCreate.as_view(), name='user-create'), one can see DRF Browsable API which uses MyUserCreate (in views.py) class MyUserCreate(APIView): """ Creates the user. """ def post(self, request, format='json'): serializer = MyUserSerializer(data=request.data) if serializer.is_valid(): MyUser.objects.create_user( serializer.username, serializer.password ) if user: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Note that it references MyUserSerializer (in serializers.py) class MyUserSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=MyUser.objects.all())], min_length=5, max_length=20 ), password = make_password(serializers.CharField( write_only=True, required=True, max_length=256 )) class Meta: model = MyUser fields = ('username', 'password') def create_user(self, validated_data): password = make_password(validated_data['password']) user = MyUser.objects.create_user(validated_data['username'], password) return user and MyUser (in models.py) class MyUserManager(BaseUserManager): def create_user(self, username, password): user = self.model( username=username ) user.set_password(password) user.save(using=self._db) return user class MyUser(AbstractBaseUser): objects = MyUserManager() class Meta: # managed = False db_table = 'user_entity' user_id = models.AutoField(primary_key=True, db_column='userId') username = models.CharField(db_column='username', unique=True, max_length=20) password = models.CharField(db_column='userPassword', max_length=256) USERNAME_FIELD = 'username' def __str__(self): return str(self.user_id) + " (%s)" % str(self.username) When I post to create a user { "username": "tiagoperes", "password": "test" } I get django.db.utils.DataError: (1406, "Data too long for column 'username' at row 1") Following information from other users, checked if the column is UTF8 and doesn't make sense to use TextField instead of CharField here. -
Vertically Assignment of Block in Page
I am learning DJANGO and while proceeding wanted to give nice look to some pages. I am currently new in programming (only 4 months coding) and mostly spent time with Python, could find time to properly learn front-end. So my problem is I can`t center LOGIN block in the page. I am using Bootstrap4.5 and gave some Shadow to make object like floating. I now there were similar questions here with answers and tons of tutorial of centering elements either with custom CSS or Bootstrap Flex or Justify and I really tried almost everything I found with no result. Every time time position of Block is getting somewhere else but not center. My Base HTML: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384- 9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <title>Newspaper Project</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" … -
django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile
My models.py file looks like: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' When I'm trying to look it into the shell: >> from django.contrib.auth.models import User >>> user = User.objects.filter(username='TestUser').first() >>> user <User: TestUser> >>> user.profile Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\Visual Studio Code Projects\cs50\Learning Django(other source)\Corey\djangoenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 423, in __get__ self.related.get_accessor_name() django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile. I looked various different tutorials and solutions it works fine for everyone. Please help me with this regards, really stuck at this point. -
Setting up one custom logger for the entire django project
This is how i'm configuring logger in my Django project currently In settings.py file import os import logging.config from django.utils.log import DEFAULT_LOGGING logger = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'dark': { 'format': '{asctime} {name} {levelname} {message}', 'datefmt': '%d-%b-%y %H:%M:%S', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs.log', 'formatter': 'dark' }, }, 'loggers': { 'darkbot': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': False, }, }, } logging.config.dictConfig(logger) The logs are getting written in the file as expected but the problem which i'm encountering is the name of the module in logs remain constant doesn't matter by which module that log is get written For instance if i use this logger = logging.getLogger("darkbot") logger.info("started reading new file") Then my log looks some thing like this 30-May-20 12:22:56 darkbot INFO started reading new file As you can see i'm getting darkbot as the name of the module which is constant. By which i can't trace the module it originally originated from. but if i replace my name of the logger with name of django app as one of my django app name is fileparser import os import logging.config from django.utils.log import DEFAULT_LOGGING logger = { 'version': … -
Add user signup feature to existing django project
I am new to django and I'm still learning it. I followed a tutorial https://tutorial-extensions.djangogirls.org/en/authentication_authorization/ I have followed it properly and my site is working cool. But i want to add User Signup feature to this site . I have created a module using this tutorial https://learndjango.com/tutorials/django-signup-tutorial but I am getting the error whenever I'm clicking on Submit form button of signup page. My data is not saving in database and user are not getting created. Kindly help me I'm stuck at this point. My folder structure you can see on github ---> https://github.com/aman2457/my-first-blog there i have created a new app called accounts using the above mentioned tutorial. code snippet of my "mysite\urls.py" from django.contrib import admin from django.urls import path, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), # new path('', include('blog.urls')), path('', include("django.contrib.auth.urls")) ] Code Snippet for accounts\urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), ] code snippet for accounts\views.py from django.shortcuts import render # Create your views here. from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' I can provide more details … -
TypeError at /users/login/ __init__() takes 1 positional argument but 2 were given
I am currently working on a tutorial in the "Python Crash course" Book. The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics I am currently stuck at the login page and receive an Error, when I run http://localhost:8000/users/login/ urls.py from django.conf.urls import url # Importing the default login view provided by Django from django.contrib.auth.views import LoginView from .import views app_name = 'users' urlpatterns =[ # Login page url(r'^login/$', LoginView , {'template_name':'users/login.html'},name = 'login'), ] login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p> Your username and password didn't match.Please try again. </p> {% endif %} <form method="post" action="{%url 'users:login' %}"> {%csrf_token %} {{form.as_p}} <button name="submit">log in</button> <input type="hidden" name="next" value="{%url 'learning_logs:index' %}"/> </form> {% endblock content %} base.html <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics'%}">Topics</a> - {% if user.is_authenticated %} Hello,{{user.username}}. {% else %} <a href="{% url 'users:login' %}">log in</a> {% endif %} </p> {% block content %}{% endblock content %} -
Error handling with POST signals from axios to Django Rest Server
I use React + Django, when user signup from frontend the axios in React send POST signal to Django, if form is invalid it shows below response xhr.js:178 POST http://localhost:8000/account/users/ signup.js:120 Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) If I do same POST with invalid fields in Django browsable API or Postman I get below error and it is useful to display error to users { "email": [ "This field may not be blank." ], "username": [ "This field may not be blank." ] } If user type invalid details in form and after form submission, How can I get same error message from axios ? Please note that if user type correct information in form, axios responds with sufficient details. Axios function axios.post('/account/users/',{data}).then(res=>console.log(res)).catch(err=>console.log(err) -
ImportError: Cannot import 'views' from '__main__'
This is the url.py file in the polls app on my website(project) file from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] File "<string>", line 2, in <module> ImportError: cannot import name 'views' from '__main__' (/storage/emulated/0/website/polls/urls.py) Now the main urls.py file in the website file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] Traceback code: Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/i ie c_run.py", line 31, in <module> start(fakepyfile,mainpyfile) File % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [Program finished] I have tried the polls urls.py like this from polls import views but it gets a Module Error so what's the issue with the code? Can someone help me out? thanks in advanced! -
Optimize DB requests in Django
I have a page view in Django set up as follows: blog = get_object_or_404(Blog, subdomain=extracted.subdomain) all_posts = Post.objects.filter( blog=blog, publish=True).order_by('-published_date') nav = all_posts.filter(is_page=True) posts = all_posts.filter(is_page=False) This causes the DB to be accessed 3 times. I'm trying to optimize this to only access the DB once. The following snippet reduces the number of calls to 2, but I'm sure there is a better way than this that I don't know about. blog = get_object_or_404(Blog, subdomain=extracted.subdomain) all_posts = Post.objects.filter( blog=blog, publish=True).order_by('-published_date') nav = [] posts = [] for post in all_posts: if post.is_page: nav.append(post) else: posts.append(post) As far as I understand, prefetch_related and select_related work inversely and I'm unsure how to implement them in this context. My models are set up as follows: class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) title = models.CharField(max_length=200) ... class Post(models.Model): blog = models.ForeignKey( Blog, on_delete=models.CASCADE, related_name='post') title = models.CharField(max_length=200) ... Thanks in advance! -
Static Media Failure with NGINX and Gunicorn
Hello and thanks for taking time to read this request for help. I am installing a web application called Netbox, which is built on Django. A basic Gunicorn is front-ended with NGINX in a rather simplie configuration. The problem I'm running into is that the web application reports that it is unable to load any of the static files, and I can validate that I'm getting a 404 for these requests. I have validated that I can view the correct files in the /static/ path referenced in the NGINX path /opt/netbox/netbox/static, and the permissions are correctly set as well. Since this is a Django web app, I have performed a simple test with the built-in test web server and all the static files are correctly rendered; this is almost certainly an issue between Gunicorn and my NGINX configuration. nginx.conf server { listen 443 ssl; # CHANGE THIS TO YOUR SERVER'S NAME server_name netbox.example.com; ssl_certificate /etc/ssl/certs/netbox.crt; ssl_certificate_key /etc/ssl/private/netbox.key; client_max_body_size 25m; location /static/ { alias /opt/netbox/netbox/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; } } server { # Redirect HTTP traffic to HTTPS listen 80; server_name _; return 301 https://$host$request_uri; } gunicorn.py bind = … -
Why can not access the uwsgi server with ERR_EMPTY_RESPONSE response?
I use manage.py runserver 127.0.0.1:8000, my project run perfectly, I can access success: (venv) dele-MacBook-Pro:majsbh_django ldl$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 30, 2020 - 20:28:19 Django version 2.2.12, using settings 'mabh_django.settings_dev' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. but when I run my django rest framework project use uwsgi in my Mac: $ uwsgi ./mabh_django/wsgi_dev.ini I can not access the 127.0.0.1:8000, with this response: ERR_EMPTY_RESPONSE in browser. My wsgi_dev.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'majsbh_django.settings_dev') application = get_wsgi_application() My pid of the uwsgi, this means the uwsgi run success: (venv) dele-MacBook-Pro:mabh_django ldl$ ps -ef | grep uwsgi 501 24625 1 0 8:24PM ?? 0:00.44 uwsgi ./mabh_django/wsgi_dev.ini 501 24627 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24628 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24629 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24630 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24631 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24632 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24633 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 24634 24625 0 8:24PM ?? 0:00.00 uwsgi ./mabh_django/wsgi_dev.ini 501 … -
Apache HUE, can login using REST API, but the rest doesn't work
I'm struggling with Apache HUE Rest API and django csrf. The problem is that I can kind-a login, but the rest doesn't work. I always get redirected to login page. Seems like server doesn't like my csrftoken or sessionid cookie. I have absolutely no idea why. Here is my login code: val accessToken = getAccessToken(Http(s"$baseUrl/accounts/login/?next=/").asString) val response = Http(s"$baseUrl/accounts/login/") .postForm(Seq( "username" -> username, "password" -> password, "csrfmiddlewaretoken" -> accessToken.csrftoken.getValue, "next" -> "/" )) .cookie(accessToken.csrftoken) .asString getAccessToken(response) // wrapper for cookies and headers from response Now I try just to get page from HUE protected with csrf def getDir(hdfsPathDirParent: String): Unit = { val accessToken = login() val response = Http(s"$baseUrl/filebrowser/view=$hdfsPathDirParent") .cookie(accessToken.csrftoken) // retrieved after login .cookie(accessToken.sessionid) // retrieved after login .header("X-CSRFToken", accessToken.csrftoken.getValue) .header("Host", "localhost:8888") .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9") .header("Connection", "keep-alive") .header("Sec-Fetch-Dest", "empty") .header("Sec-Fetch-Mode", "cors") .header("Sec-Fetch-Site", "same-origin") //.header("Sec-Fetch-User", "?1") .header("Upgrade-Insecure-Requests", "1") .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36") .header("Accept-Encoding", "gzip, deflate, br") .header("Accept-Language", "en,en-US;q=0.9,ru;q=0.8") .header("Cache-Control", "max-age=0") .header("X-Requested-With", "XMLHttpRequest") .asString I literally copy-pasted all tokens from Google Chrome debug panel. It doesn't work [30/May/2020 05:19:29 -0700] access WARNING 172.17.0.1 test_user - "POST /accounts/login/ HTTP/1.1" -- Successful login for user: test_user [30/May/2020 05:19:29 -0700] middleware INFO Redirecting to … -
Scraping gets blocked, gets response of a buffer reader
So i have been building a Django App using Beautiful soup to scrape a website and it was working perfectly in development. However, then deployed the web app to a linux server and ran it and that is when the the request was blocked and I got this error You don't have permission to access "http://www.xxxxxx.com/en-ca?" on this server.<p> Reference #xxxxxxxxxxxxxx I tried using Mozilla and Chrome headers but that still did not work. hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Saf$ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Referer': 'https://cssspritegenerator.com', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} req = get(url, headers=hdr) soup = BeautifulSoup(req.content,'html.parser') print(soup) I also tried another solution I saw online that uses a particular request like this class AppURLopener(urllib.request.FancyURLopener): version = "Mozilla/5.0" def scrape(): opener = AppURLopener() response = opener.open(url) print('response: ', response) which gives me the response response: <addinfourl at 139782695145200 whose fp = <_io.BufferedReader name=-1>> which is something I do not understand So I just needed some help as to what this response is and how can i use it? Furthermore, should I look into using something like Selenium instead of beautifulSoup as it could be a better option to access the site … -
Django and FCM to send push notifications
What's the correct way to use fcm-django using a custom Device-info model or a possibility to extend FCMDevice with more attributes. For example, I need to store into the device info some additional fields like language, position (lat/lng), app version, vendor etc. I'm new for FCM but for me, at the moment, It's not very clear the device registration flow. My current project is a backend service for mobile apps. So, I have some REST service using djnago-rest-framework. I already have an API to register/update a mobile device. Can I reuse it adding the FCM registration-id? -
AttributeError: Cannot use remove() on a ManyToManyField which specifies an intermediary model. Use songs.Playlist_Activity's Manager instead
I followed the documentation on figuring out how to remove an item in the manytomanyfield below but it doesn't seem to work and I am getting an attribute error. The remove method works totally fine without the intermediary model. models.py class Song (models.Model): author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) timestamp= models.DateTimeField(auto_now_add=True, editable=False) songname = models.CharField(max_length=500, null=False, blank=False) tags = TaggableManager() def __str__(self): return self.songname class Playlist (models.Model): name = models.CharField(max_length=150, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) song = models.ManyToManyField(Song, through='Playlist_Activity') class Playlist_Activity(models.Model): song= models.ForeignKey(Song, on_delete=models.CASCADE) playlist= models.ForeignKey(Playlist, on_delete=models.CASCADE) timestamp= models.DateTimeField(auto_now_add=True, editable=False) class Meta: ordering = ('timestamp',) Views.py @login_required def Playlist_Remove(request, id, P_id): Playlist_Activity p = Playlist.objects.get(id=P_id) s = p.song.get(id=id) p.song.remove(s) return redirect('account') -
How to change from request.site to Site._find_for_request(request) in wagtail 2.9
I've recently upgraded my wagtail app to the latest version, version 2.9, now since the wagtail site middleware has been deprecated I'm having trouble getting my site to work. I was using a request.site now wagtail 2.9 uses Site._find_for_request(request) How do I change my current code to work with the latest wagtail version? Thanks in advance @register.simple_tag(takes_context=True) def og_image(context, page): protocol = re.compile(r'^(\w[\w\.\-\+]*:)*//') if protocol.match(settings.MEDIA_URL): base_url = '' else: base_url = context['request'].site.root_url if page: if page.og_image: return base_url + page.og_image.get_rendition('original').url elif page.cover_image: return base_url + page.cover_image.get_rendition('original').url if LayoutSettings.for_site(context['request'].site).logo: layout_settings = LayoutSettings.for_site(context['request'].site) return base_url + layout_settings.logo.get_rendition('original').url return None -
(Django) Trying to figure out how I can get the right product using query parameters on Postman (url.py and views.py)
I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so: http://10.58.1.157:8000/product/sandwich?product_id=1 Below are my codes for urls.py and views.py urls.py from django.urls import path from .views import ProductView urlpatterns = [ path('sandwich/int:<product_id>/', ProductView.as_view()), ] views.py import json import bcrypt import jwt from django.views import View from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.db.models import Q from .models import Product, Category, SubCategory class ProductView(View): def get(self, request): product_id = request.GET.get('product_id', None) return JsonResponse({'product_name':Product.objects.get(id=product_id).values()}) To clarify the GET request, I will add the screenshot of Postman below: -
Django crispy form layout helper does not work
I'm trying to set the html layout of my forms using the helper and layout of crispy form. In other words I have set my form in the following manner. class MaterialeForm(forms.ModelForm): data_contabile=forms.DateTimeField(widget=DatePicker(attrs={ class Meta: model = Materiale fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.layout = Layout( Field('conta', id="form-conto", css_class="form-control", name="Conto")) And after that I have set in my template the html code: <div class="modal-body"> <label for="conto"></label> {{form.conto|as_crispy_field}} but in the layout the id and name does not work properly. In fact if I ispect the page I try the following code: <select name="conto" class="select form-control form-control" required="" id="id_conto"> <option value="">---------</option> <option value="1" selected="">Materia Prima</option> </select> where is the error? -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed, how to fix this error
the problem appeared when I added the field id_parent How to solve this problem? models.py class ArticleComment(TimeStampMixin, models.Model): comment = models.TextField() id_user = models.ForeignKey(User, on_delete = models.CASCADE) id_article = models.ForeignKey(ParseMovieInfo, on_delete = models.CASCADE) id_parent = models.ForeignKey( 'self', verbose_name="Родитель", on_delete = models.SET_NULL, blank=True, null=True ) liked = models.ManyToManyField(User, default = None, blank = True, related_name = 'liked_review') dislike = models.ManyToManyField(User, default = None, blank = True, related_name = 'dislike_review') def __str__(self): return self.id_article.title @property def num_likes_review(self): return self.liked.all().count() @property def num_dislikes_review(self): return self.dislike.all().count() in views.py message = request.POST.get('comment') # if request.POST.get('parent'): ArticleComment(comment = message, id_user_id = pk_user, id_article_id = pk_article, id_parent_id = request.POST.get('parent')).save() enter image description here -
How do I work with multiple databases with django 'sites' framework
I have a django application that is to be used by various concurrent groups. Each group will have their own 'site', users and database. However, they will be using the same views and models. The official django documentation is of no help. What is the complete procedure? -
Django Angular images not loading from AWS S3
My Django-Angular app works fine, but without static images. I run "ng build --prod" to the Django static folder and uploaded these files to AWS S3 Bucket. My Index.html file in Django Template is loaded and the page displayed. My Settings.py: AWS_ACCESS_KEY_ID = '*******' AWS_SECRET_ACCESS_KEY = '******' AWS_STORAGE_BUCKET_NAME = 'mys3bucket' AWS_S3_REGION_NAME = 'eu-central-1' AWS_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_DEFAULT_ACL = None STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' STATICFILES_DIRS = ('static'), In my angular App I have a src/assets dir. When building the app I used paths for images like: <img src="static/assets/png/Logo1.png"> this worked fine. Now they are in S3 and I thought that the path will be automatically set to "Static_Url" from Django settings.py. But somehow angular looks from the rooT and this error is shown: GET http://localhost:8000/static/assets/png/Logo1.png 404 (Not Found) How kann I set a relative path to Angular looking at the defined Static_Url ? -
Django static files are not loaded when deploying on Heroku using Whitenoise
I'm trying to deploy a django app on Heroku (using Whitenoise), and all works fine except for the static files. The sample project just shows a header "Home" on the front page. If the css file is loaded correctly then the header will have the red colour, otherwise it will be black. I got the above project to work in a virtualenv, a Docker container, with DEBUG=False, but I could not make it work on Heroku for some reason. I tried to use the django-heroku as suggested by the Heroku docs but it starts throwing 500 server error, and when checking the heroku logs it says manifest not found for the css file, which seems to be because it sets STATICFILES_STORAGE to a different value. Is there something setup incorrectly in the settings or the yml files? -
DRF: Do DRF serializers, SerializerMethodField have execution order
class ProfileAPI(serializers.Serializer): name = serializers.SerializerMethodField() age = serializers.SerializerMethodField() def get_name(self, obj): return "name" def age(self,obj): return 78 is their ordering while execution of SerilaizerMethodField or it is random, means will "get_name" is executed before "get_age". -
Search form Django e-commerce. Unsupported lookup 'search' for CharField or join on the field not permitted
enter image description here views.py from django.shortcuts import render from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.views import View from shop.models import Product class Search(View): template_name = 'search.html' def get(self, request, *args, **kwargs): context = {} question = request.GET.get('q') if question is not None: search_product = Product.objects.filter(name__search=question) context['last_question'] = '?q=%s' % question current_page = Paginator(search_product, 10) page = request.GET.get('page') try: context['product_lists'] = current_page.page(page) except PageNotAnInteger: context['product_lists'] = current_page.page(1) except EmptyPage: context['product_lists'] = current_page.page(current_page.num_pages) return render(request,template_name=self.template_name, context=context) urls.py from django.urls import path from . import views app_name = 'search' urlpatterns = [ path('search/',views.Search.as_view(), name='search'), ] Product Model The model is taken from the usual e-commerce web-site class Product(models.Model): name = models.CharField(max_length=200, db_index=True) I’ve been trying to fix this for 2 days, I can’t find a solution. -
waypoints infinite scroll doesn't append newly loaded items to the infinite-container in django
The code works just fine while performing a standart pagination, but when I update it to infinitite pagination using waypoint-jquery it triggers the waypoint function which also is able to trigger views.py function and data is sent to the html side. But the newly loaded items are not appended to the infinite-container. {% extends "layout.html" %} {% load static %} {% block body %} <h1 class=yazar>{{yazar}}</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus auctor pharetra purus in viverra. Suspendisse nec sem eget urna blandit malesuada. Duis pellentesque nibh vel rutrum placerat ligula.</p> <div class=yazar-top> <a class=t-holder href=""> <p class=p1>takipçiler</p> <b class=b1>{{follow}}</b> </a> <a class=t-holder href=""> <p class=p1>takip ettikleri</p> <b class=b1>{{followed}}</b> </a> <a class=t-holder href=""> <p class=p1>başlıkları</p> <b class=b1>{{titles}}</b> </a> <a class=t-holder2 href=""> <p class=p1>yazıları</p> <b class=b1>{{entry_count}}</b> </a> </div> <div class=yazar-bot> <button id=bt-holder1>takip et</button> <button id=bt-holder2>mesaj</button> <button id=bt-holder3><span class=spandot>...</span></button> </div> <div class="infinite-container"> {% for entry in entries_list %} <div class=entry-yazar> <span class=title-span>{{entry.title}}</span> <p class=content-holder id={{entry.id}}> {% if entry.safe %}{{entry.content|safe|linebreaksbr}}{% else %}{{entry.content|linebreaksbr}}{% endif %} </p> <button id="{{entry.id}}b" onclick="larger('{{entry.id}}','{{entry.id}}b')" class=uzat>doyamadım...</button> <form method="GET"> {% csrf_token %} {% if entry.already_liked %} <div class=kokomo> <button type="button" onclick="like('{{entry.id}}')" class=active-button id=like-button{{entry.id}}><img class=icon5 src="{% static 'icons\virus.png' %}" alt="like"></button> <button style="display:none" onclick="like('{{entry.id}}')" class=active-button type="button" id=dislike-button{{entry.id}}><img class=icon5 src="{% static …