Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not refreshing content without server start
I am working on DjangoRest Framework, if I update values from the API, and see the content on the frontend, the changes are not getting reflected without server startup. For debugging, I also directly changed the value in the database, but the changes are not getting reflected either in this case too. What could be the reason behind this? Can someone point me out in the right direction? I read about it and someone told this is happening because of .pyc files I even deleted them. But nothing solved my issue yet. How can i resolve it ? -
Django model choices from database, another model
I'm trying to figure out how to allow for a model to take only certain values. But I can't use IntegerField with choices option because it's product database with couple thousand products. To be more precise- I'm trying to create app which manages product orders. For now my models are: class Order(models.Model): timestamp = models.DateField(auto_now_add=True) komentarz = models.CharField(max_length=150, unique=False) class Product(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) r = models.CharField(max_length=50, unique=False) s = models.CharField(max_length=50, unique=False) p = models.CharField(max_length=50, unique=False) I created another app with product database, it contains around 3000 records. class ProductBase(models.Model): r = models.CharField(max_length=50, unique=False) s = models.CharField(max_length=50, unique=False) p = models.CharField(max_length=50, unique=False) Basically I want to allow Product model to take values inside database made thanks to ProductBase model. Any idea what should I use? -
how to use popup in django admin to select from another class
i want to use popup to fill input in django admin i saw it in class Email addresses as the follwing pic -
IntegrityError at /order/orderfood/ FOREIGN KEY constraint failed
views.py this is views.py @login_required(login_url='/login') def orderfood(request): category = Category.objects.all() current_user = request.user schopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in schopcart: total += rs.Food.price * rs.quantity #toplamı hesapla if request.method == 'POST': #form post edildiyse food_detail dan form = OrderForm(request.POST) if form.is_valid(): #geçerli mi csrf kontrolü #kredi kartı bilgilerini bankaya gönder onay gelirse devam et #....if kontrolü.... data = Order() #order tablosu ile ilişki kur data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() # random kod üretir data.code = ordercode data.save() #sepetteki ürünleri order'a kaydetmek için aşağıdaki kodlar schopcart = ShopCart.objects.filter(user_id=current_user.id) for rs in schopcart: detail = OrderFood() detail.order_id = data.user_id detail.Food_id = rs.Food_id detail.user_id = current_user.id detail.quantity = rs.quantity Food = food.objects.get(id=rs.Food_id) Food.amount -= rs.quantity #ürün stoktan düşme Food.save() detail.price = rs.Food.price detail.amount = rs.amount detail.save() ShopCart.objects.filter(user_id=current_user.id).delete() #sepet temizlendi request.session['cart_items']=0 messages.success(request, "Your order has been completed. Thank you") return render(request,'Order_Completed.html',{'ordercode':ordercode,'category':category}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderfood") #if there is no POST form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) context = {'schopcart': schopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, } return render(request,'Order_Form.html',context) When I add the products to the … -
Access other models from template in Class Based View Django
I have a profile page for users to see their orders but would like it so the superuser(me) can see customers address and the Orderitems in the Order model. in the template, can i grab the shipping model or orderitem model from the Order model? So far have this: # ? Profile View # Will show completed orders and link to edit account details class ProfileListView(UserPassesTestMixin ,ListView): model = Order template_name = "store/customer_view.html" context_object_name='orders' def get_queryset(self): if not self.request.user.is_superuser: qs = self.model.objects.filter(customer=self.request.user.customer,confirmed=True).order_by('-date_ordered') elif self.request.user.is_superuser: qs = self.model.objects.filter(confirmed=True).order_by('-date_ordered') return qs def test_func(self): if self.request.user.is_authenticated: return True else: return False Models: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True,null=True) date_ordered = models.DateTimeField(auto_now_add=True) confirmed = models.BooleanField(default=False,null=True,blank=True) transaction_id = models.CharField(max_length=200, null=True, blank=True) receipt = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL,blank=True,null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL,blank=True,null=True) quantity = models.IntegerField(default=0,null=True,blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product.name @property def get_total(self): total = self.product.price*self.quantity return total class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True,null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True,null=True) first_name=models.CharField(max_length=200, null=True) last_name=models.CharField(max_length=200, null=True) … -
Which template tag to include an image stored using django-storage[dropbox]
I try to build my first application with Django, and use django-storage to store my media on dropbox: DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = ---- mytoken ---- DROPBOX_ROOT_PATH = 'media' It works well to upload and display the images using the models directly (e.g. {{ object.photo.url }} in the html template works) However, how can I create a link to the image in the template if I have no object. Something like <img src="{{media_url}}/myimage.jpg"> does not work as media_url points to localhost (on my local server). Is it needed to redefine media_url or is there another tag to use? -
How to configure NGINX for Vue and Django?
I was following this tutorial to create backend and it worked. I made simple a Django REST admin panel to upload images, it worked. Then i created Vue frontend app, run 'npm run serve' while in 'VScode remote' and it worked (images are fetched from django and styled by Vue in my localhost). The PROBLEM is it's not obvious how to make all this work in production vps server (i mean from Vue 'dist' folder after 'vue run build'). Everything i tried just gives me 404 error or ruins Django admin panel. Here are my NGINX settings : server { server_name kruglovks.xyz www.kruglovks.xyz; client_max_body_size 100m; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/kirill/myprojectdir/myproject; } location /media { root /home/kirill/myprojectdir/myproject; } location /dist { try_files $uri $uri/ /index.html; alias /home/kirill/myprojectdir/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } Vue router is set to history mode. Please, i need some info how to make Vue work in this configuration. P.S. Maybe there is alternative way of using Vue alongside Django? Thank you so much and have a nice day! -
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?