Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I schedule a task in my djnago amazon product tracking project?
I am working on a web-app project with Django. It is an Amazon product price tracker. I want the app to automatically scrape products in the product table to check if the price of the product has reduced or not. I want to deploy the application once it is finished so it should work there too. I looked for answered online but it seems that cronjobs and celery do not work for windows so is there any other ways I can achieve my goals. I have created a function that needs to be executed once every day. This is the function I want to execute every 24 hours. def track(): products = Product.objects.all() for product in products: new_data = getproduct(product.link) update_data(product, new_data) I have tried the schedule library: import schedule import time from .models import Product from .utils import getproduct schedule.every().day.at("12:00").do(track) here getproduct is the method which scrapes the product data and product is the model -
Django Rest Framework deployed under subdirectory proxy
I'm trying to deploy a small API using a subdirectory on the server. Usually if I do the following config it works fine: location /iframe/api/ { proxy_pass http://127.0.0.1:8001; 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 https; client_max_body_size 0; } The funny thing is that for static files it seems to work, because I get back proper styling for the rest framework, but for every single urlpattern it also transfers the iframe/api which isn't ideal and basically not a single API route is matched. I tried to add proxy_redirect off but still no avail. Any idea why isn't this working as expected? How should I deploy a rest framework API under a sub-directory? -
Cannot resolve keyword 'use_as_keyword' into field
Django==3.2 class SemanticsLevelThreeGeneral(general.ArchivedMixin, semantics.model_mixins.UniquePhraseMixin, semantics.model_mixins.PhraseStrMixin, semantics.model_mixins.SemanticsLevelTwoMixin, general.FlagMixin, general.CommentMixin, models.Model): """ Just general semantics. 1. For reports. 2. Used in <meta name="keywords">. """ use_as_keyword = models.BooleanField(null=False, default=False, validators=[semantics.validators.validate_use_as_keyword,]) class Meta: verbose_name = gettext("Level 3 general") verbose_name_plural = verbose_name Absolutely new database. I deleted all the migrations and made them anew. Everything opens fine in the admin site. Migration went fine. The database: ads6=# select * from semantics_semanticslevelthreegeneral; id | comment | archived | flag | phrase | use_as_keyword | semantics_level_two_id ----+---------+----------+------+--------+----------------+------------------------ (0 rows) Problem When I try to save an instance of this model in the admin site, it blows up. Environment: Request Method: POST Request URL: http://localhost:8000/admin/semantics/semanticslevelthreegeneral/2/change/ Django Version: 3.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'omnibus', 'images.apps.ImagesConfig', 'clients', 'toponyms', 'generals', 'home', 'scaffolds', 'staticassets.apps.StaticassetsConfig', 'semantics', 'commerce', 'tmplts.apps.TmpltsConfig', 'dashboard', 'files', 'marketing'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … -
In Django Generate only s3 client generate_presigned_post with content type for mp4 file upload
After uploading the video(.mp4) file S3 metadata sets its Content-Type : binary/octet-stream when makes my browser force to download the file instead of playing In order to make it play in browser i need to change that content-type programmatically to "video/mp4" in django -
Django admin suddenly starts throwing crbug/1173575
I am building a backend that I administrate using the django-admin view. I have a prod version that runs on a server using nginx, which works as expected (using Gunicorn). Starting yesterday, developping locally has become impossible because when I try to access Django's dev server (started using python manage.py runserver) I get the error "The site can't be reached" (crbug/1173575, non-JS module files deprecated.) as in this post. This never happened before, and because I am not directly using Angular, I can't use the solution described in the post. I did a pip freeze both locally and on the prod server, and the output is the same, which means I did not install a parasite package. It seems to me that the django-admin website is using some deprecated js modules that is now no longer accepted by browsers. It is worth mentionning that I tried to access the dev server using both Mozilla Firefox 78.10.0 and Google Chrome 90.0.4430.93. -
how to past list to template
I am trying to pass this eligable list to my template so that I can display it in my website but when I run the website it says that local variable 'eligable' referenced before assignment. I dont understand because this is the only time I used the word eligable in my code. code: def specificDate(response): empName = employeeName.objects.all if 'checkEmployee' in response.POST: n = response.POST.get("nameEmployee") specDate = response.POST.get("date") if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists(): emp = employeeName.objects.get(employee=n) t = Name.objects.get(name=emp, date=specDate) overT = Name.objects.filter(name=emp, overtime=True) eligable = [] for item in overT: eligable.append(item.date) print('Hello') checkIn = t.timeIn.strftime("%H:%M:%S") checkOut = t.timeOut.strftime("%H:%M:%S") datee = datetime.strptime(specDate,'%Y-%m-%d') print("Here:: ",t.date) print("Month:: ",datee.month) messages.info(response, checkIn + ' - ' + checkOut) return redirect('/specificDate') else: messages.info(response, 'Name does not exist') else: pass return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable}) -
trying to refresh page in django from view not working
I have developed a funcktion that deletes several entries in my django project. They are bases on marked checkbox values. When all done, I want to refresh my template page so that all premarked checkboxes diseapear. But when trying redirect and render, nothing really happens. I want to refresh the page as if I clicked refresh on the page. How do I do that? views.py def deleteMulti(request): g=request.GET checked=g.getlist('marked[]') dbase=g.get('dbase') print('delete: ',checked) print('dbase: ',dbase) #res=[Concert.objects.get(pk=l) for l in checked] if dbase=='concert': deleted=[Concert.objects.filter(id=l).delete() for l in checked] res=Concert.objects.all() print('delete') response=redirect('events') return response urls.py: path('events',Events.as_view(),name='events'), -
DRF: serializer validation without a model
Is the validate_fieldname method not called when not using a ModelSerializer? I am trying to validate my input: class SomeSerializer(serializers.Serializer): serial = serializers.CharField() class Meta: fields = ["serial",] def validate_serial(self, value): if value ... return value I want to use a validator method on the input of serial, but I do not have a related model I could use. -
Not able to send email to sendgrid python
my send_mail code from rest_framework.views import APIView from middleware.response import success, bad_request from user.serializer.dao import SendEmailDao from core.models import EmailLeadLogs from util.email import send_mail class SendEmailView(APIView): def post(self, request): attributes = SendEmailDao(data=request.data) if not attributes.is_valid(): return bad_request(attributes.errors) email_lead_logs = EmailLeadLogs(**attributes.data["meta"]) email_lead_logs.subject = attributes.data["subject"] email_lead_logs.save() send_mail(attributes.data["email"].split(","), attributes.data["subject"], attributes.data["message"]) return success({}, "email send successfully", True) This is the error i am getting, I am trying to use it from drf error -
How should I resolve this error - cannot able call function in a view in django
Please see image I am not able add userid in a queue -
Admin page not loading in Django
I have a new app, which works fine, i can load all my new pages and navigate without any problem. But when i try to access the admin dashboard, i have an error 500. I am new to Django (from Railsd) and would appreciate some help, as i do not see any error log. My setup is as follow: Settings.Py INSTALLED_APPS = [ 'djangoformsetjs', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_hosts', 'rest_framework', 'djoser', 'app' # Enable the inner app ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) core/url.py urlpatterns = [ path('api/app', include('app.urls')), path('admin/', admin.site.urls), path("", include("authentication.urls")), # add this path("", include("app.urls")) # add this ] I was told to check the setup of the admin using : django-admin check, But i get the following error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is a bit overwhelming given that i was super comfortable in my previous language. Can you guys help me understand please ? -
How would you design a API Gateway, service registry and Service Discover with Django or Python?
can anyone recommend to me some tools/libraries that I can use to design/implement API Gateway, Service Registery and Service Discovery with Django and Python. Till now I have found Consul, Eureka and a package called Sharkraidar(https://pypi.org/project/sharkradar/), I just need some help to decide the correct tools and the correct approach to implement them. -
ISR not working in django server but in next dev server
hello i recently ran into an error, when i try to do ISR in django python server it fails but when i do in next dev server it works.. on dev server when i update content in django admin panel it changes in dev server , but when in production mode we use django server and it would not work there , whats the solution.. index.js import Head from 'next/head' import Image from 'next/image' import Posts from '../comps/Posts' import styles from '../styles/Home.module.css' export default function Home({data}) { console.log(data) return ( <div> {data.map(e=>{ return( <div> <h1 id='data_h1'>{e.username}</h1> </div> ) })} </div> ) } export async function getStaticProps() { const res = await fetch('http://127.0.0.1:8000/userprofile_data/'); const data = await res.json(); return {props: {data}, revalidate: 1 }; } -
Why does my django url pattern not accept paths starting with "api/payments/"?
I have an app with a payment module, when I use the path "api/payments/" for this module, requests from the front-end do not hit the api, however, when i change the module url path to something else e.g. 'api/collections/' all methods in the module work fine. What could the issue be with that specific url path? -
How to send different message on same group for different users in django channels
I am trying to build a real-time ticket reservation app so I want to display the real time seat booking status to users. For example; I have user1 and user2 connected to a group reservation-1 Now when the user1 selects the ticket in group reservation-1 the seat status will be converted to selected and the message should be broadcasted to all the users connected to the same group with the status of unavailable for that particular seat. But for user1 it should be the status of selected. My code implementation for JavaScript: const socket = new WebSocket('ws://${window.location.host}/ws/reservation-1'); // This is an event when user select the seat socket.send(JSON.stringify({ "event": "SELECT", "seat": "seat_id" })); // This is an event when user deselect the seat socket.send(JSON.stringify({ "event": "DESELECT", "seat": "seat_id" })); socket.onmessage = function(e) { const data = JSON.parse(e.data); // code logic to update the seat based on return values of seat status. } My Django server-side consumer code using django-channels: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ReservationConsumer(WebsocketConsumer): def connect(self): self.chat_group_name = 'reservation-1' async_to_sync(self.channel_layer.group_add)( self.reservation_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.reservation_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) user = self.scope['user'] event = data['event'] … -
Sjango - Saving updated information to existing user
I'm creating a multi-step user form for registration. The idea behind it, is when the user registers, it gets their registration information. Then, it saves the users information. In the registration form, if the user selected a certain option (rank = 'Anak'), they are redirected to a base form that obtains the tribe name. What I want it to do, is save the tribe name into that users account that was just created, but I am having trouble doing this since there is no save() function for base forms in Django. forms.py class RegisterForm(UserCreationForm): email = forms.EmailField( initial='', required=True, help_text='Please enter a valid email address' ) rank = forms.ChoiceField( label='Are you a PSMC member?', choices=SavBlock.models.User.rank, initial=False, required=True, help_text='Member accounts will be validated with your HC.', ) class Meta: model = User # username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fields = ['username', 'first_name', 'last_name', 'email', 'rank', 'password1', 'password2'] def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.ranking = self.cleaned_data['rank'] if commit: user.save() return user class AnakRegisterForm(Form): tribe = forms.ChoiceField( label='What tribe are you from, Uce?', choices=SavBlock.models.Anak.tribe, initial=False, required=True, help_text='Member accounts will be validated with your HC.' ) class Meta: model = Anak fields = ['tribe'] def save(self, commit=True): user = super(RegisterForm, … -
How should I do django admin becomes like this?
enter image description here What should I do django admin becomes like this? -
I get the error "SyntaxError: can't use starred expression here"
I get the error SyntaxError: can't use starred expression here in Python. At the same time, I also got the error SyntaxError: non-default argument follows default argument. Why is this? I would appreciate it if you could tell me more about this. -
Get all details from serializers.PrimaryKeyRelatedField in django
So I have my family serializer like below class FamilySerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField( many=True, queryset=Parishioner.objects.all(), allow_null=True ) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'enabled') read_only_fields = ('id',) depth = 1 Family can have multiple Parishioners so it's One to Many relationship. When I send a GET request to /api/family/1/ I get below response { "id": 1, "name": "Mendis Family test", "address": "No 48, Katukurunda, Moratuwa", "monthly_contribution": 50.0, "members": [ "1", "2" ], "enabled": true } as you can see in members array I can see only id of the members. How can I get all data of member within that array (NOT just the id. name, address, etc..) ? I tried changing depth = 1 to many numbers but it did NOT do the trick. -
Hi guys,Trying to get past the user registration as I assign groups to different users through giving different permisions. Kindly assist
Traceback (most recent call last): File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alvin/.local/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) TypeError: 'NoneType' object is not callable [28/Apr/2021 10:17:24] "GET / HTTP/1.1" 500 70741 from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.users.groups.exists(): group = request.users.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse("You are not allowed to view this page!") return wrapper_func return decorator**strong text** -
django rest-auth login token use approach
I am using django rest-auth for handling user registration and login. whenever I try to login, it gives me token. so my question is now how to make use of that token to log in user to the home page. enter image description here what I want is to make use of that token to login the user in to home page. thank you -
Use dictionary value from if in statement
I have a need for an If/Else statement in my Django (3.1.5) template check if a value exists in a dictionary (very popular concept). My challenge here is now trying to use the value from the dictionary it matched on. I know i can use a for loop and then use another if to match again when that value exists but i am wondering if there is a shorter way to do what i am looking for. For example, in my template i have 2 query sets, config and user_settings that i pass to the template. What i do is check if the name from the config exists in the user_setting dictionary, then I use the config details in a form. What I want to do is take the "total" field from user_settings dictionary that matched on the if in statement. In the below code the, the piece i am talking about is on line 6 value='{{user_setting.total}}'. This clearly doesn't work but can i do something like that to reduce the amount of code? {% for c in config %} {% if c.location == 'Dashboard' %} {% if c.name in user_settings.all %} <div class="form-group col-md-6"> <label for="{{c.web_friendly_name}}">{{c.name}}</label> <input class="form-control" data-type="dashboard" … -
I cloned it from the collar, and the django admin goes like this. Why is that?
enter image description here I cloned it from the collar, and the django admin goes like this. Why is that? -
page will keep getting 404 error with {%endfor%} but if removed will render but now posts will show
Hi i'm hoping i make sense here i was hoping someone can point out for me why {% endfor % causes a 404 error for me but when i remove it the page renders but no posts show thank you in advance i've also attached screenshots code for Views from django.shortcuts import render from django.http import HttpResponse posts = [ { 'author': 'Joshua Harvey', 'title': 'blog post', 'content': 'first post test', 'date': 'may 1st 2021', }, { 'author': ' Deidre gibson', 'title': 'blog post 2', 'content': 'second post test', 'date': 'may 2st 2021', } ] def myView(request): context = { 'posts': posts } return render(request, 'hello/home.html', context) def about(request): return render(request, 'hello/about.html', {'title':about}) code for home.html {% extends "hello/base.html" %} {% block content %} <article class="media content-section"> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted }}</small> </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endblock content %} when i enter {%endfor} above {% endblock content%} i get 404 error for webpage but i need {%endfor%} to end the block but if i remove it i dont see any post's whatsoever -
Django Paginator - If there are more than ten posts, a “Next” button should appear
How can I detect in my JavaScript how many posts are there if my views method only sends 10 every time? basically, my all posts length is in the views.py method..But I need to know how many So I can add a next button if there are more than 10 posts. views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() paginator = Paginator(all_posts, 10) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj], safe=False) index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts.length) all_posts.forEach(function(post) { // loop to loop over each object build_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } urls.py # API Routes path("posts/all_posts", views.show_posts, name="show_posts"),