Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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"), -
How to export information displayed in the template table to excel Django
I tried to export the information I display in the template under the table tag to excel, and the information was pulled from the SQL server. However, the exported csv only has headers in the file, I was wondering if anyone knows what might cause this? Here's my template: <body> <a href="{% url 'export_csv' %}">Export all PPs</a> <table class="myTable" id="myTable"> <center> <thead> <tr> <th>id</th> <th>Tracking Number</th> <th>Delivery Date</th> <th>Delivered</th> </tr> </thead> <tbody> {% for display in Project %} <tr> <td>{{display.id}}</td> <td>{{display.TrackingNumber}}</td> <td>{{display.EstimatedDeliveryDate}}</td> <td>{{display.Delivered}}</td> </tr> {% endfor %} </tbody> </center> </table> </body> Here's my model.py: id = models.CharField(max_length=1000) TrackingNumber = models.CharField(max_length=1000) EstimatedDeliveryDate = models.DateField(max_length=25) Delivered = models.CharField(max_length=1000) Here's my views.py: conn_Project = pyodbc.connect('driver={sql server};' 'server=test;' 'Database=test;' 'Trusted_Connection=yes;') cursor_Project = conn_Project.cursor() selectedpp_p = request.POST.get('selectedpp_p', None) query_Project = """select id,TrackingNumber,EstimatedDeliveryDate,Delivered from Test.Project where Project = ?""" cursor_Project.execute( query_Project, selectedpp_p ) result_Project = cursor_Project.fetchall() return render(request, 'introduction/project.html', {'Project': result_Project, 'selected_project': selected_project}) def export_csv_p(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=Exported Table' + \ str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['ID', 'TrackingNumber', 'DeliveryDate', 'Delivered']) for project in Project.objects.all().values_list('ID', 'TrackingNumber', 'DeliveryDate', 'Delivered'): writer.writerow(project) return response Here's my url.py: path('admin/', admin.site.urls), path('', introduction.views.project, name='project'), url(r'^export/csv/project/$', introduction.views.export_csv_p, name='export_csv_p'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you in advance! -
Django unit test - patch multiple requests for external api
I need to write 'one' test code with external api, which requires requests 'twice'. first, I need to check if user is valid. So I handled this with decorator in ./users/utils.py import requests def login_decorator(func): def wrapper(self, request, *args, **kwargs): # this access token is issued by external api access_token = request.headers.get('Authorization', None) # first requests, which gives me an info about user. response = requests.get( 'https://kapi.kakao.com/v2/user/me', headers={'Authorization':f'Bearer {access_token}'} ) user_email = response.json()['kakao_account']['email'] request.user = User.objects.get(email=user_email) return func(self, request, *args, **kwargs) return wrapper and then, I need to send that user a message with the external api again. this code is in ./bids/views.py import requests class BiddingView(View): #it uses login_decorator above @login_decorator def post(self, request, art_id): try: user = request.user data = json.loads(request.body) with transaction.atomic(): #handle things with bidding system# #the external api requires its token to use a message api. token = request.headers.get('Authorization', None) #second requests, with post method response = requests.post( 'https://kapi.kakao.com/v2/api/talk/memo/default/send', headers = {'Authorization' : f'Bearer {token}'}, data = {"template_object" : json.dumps({'message':'contents'})} ) return JsonResponse({'MESSAGE' : 'SUCCESS'}, status=200) except KeyError: return JsonResponse({'MESSAGE' : 'KEY ERROR'}, status=400) This is my unit test code about BiddingView so far, which obviously only works for decorator @patch('users.utils.requests') def test_kakao_message_success(self, mock_requests): class … -
Django: How does django-admin-sortable2 package code work?
I am using a package called "django-admin-sortable2" but I do not understand what I am coding. May someone explain? Here's what I used: https://django-admin-sortable2.readthedocs.io/en/latest/usage.html#sortable-many-to-many-relations-with-sortable-tabular-inlines Here's the GitHub repository: https://github.com/jrief/django-admin-sortable2 Here's the code example they used: models.py from django.db.import models class Button(models.Model): """A button""" name = models.CharField(max_length=64) button_text = models.CharField(max_length=64) class Panel(models.Model): """A Panel of Buttons - this represents a control panel.""" name = models.CharField(max_length=64) buttons = models.ManyToManyField(Button, through='PanelButtons') class PanelButtons(models.Model): """This is a junction table model that also stores the button order for a panel.""" panel = models.ForeignKey(Panel) button = models.ForeignKey(Button) button_order = models.PositiveIntegerField(default=0) class Meta: ordering = ('button_order',) admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from models import Panel class ButtonTabularInline(SortableInlineAdminMixin, admin.TabularInline): # We don't use the Button model but rather the juction model specified on Panel. model = Panel.buttons.through @admin.register(Panel) class PanelAdmin(admin.ModelAdmin) inlines = (ButtonTabularInline,) -
Why data is not saved from the form?
I can't understand why the data from the form is not stored in the database. My code : .views.py def create(request): error = '' if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: error = 'Форма некоректна' form = ProductForm() data = { 'form': form, 'error': error } return render(request, 'create_product.html', data) .forms.py class ProductForm(ModelForm): class Meta: model = Product fields = ['title','start_date','end_date','quantity_lections','photo','description','small_description',"slug"] widgets = { 'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Назва курсу'}), "slug" : TextInput(attrs={'class': 'form-control'}) , 'small_description': Textarea(attrs={'class': 'form-control','placeholder': 'Наприклад,опишіть для кого цей курс'}), 'description': Textarea(attrs={'class': 'form-control', 'placeholder': 'Опис'}), 'start_date': DateTimeInput(attrs={'class': 'form-control',"type": "date"}), 'end_date': DateTimeInput(attrs={'class': 'form-control',"type": "date"}), 'quantity_lections': NumberInput(attrs={'class': 'form-control'}), 'photo' : FileInput(attrs={'class':'form-control'}) } When I press the submit button, I get in the console POST request with code 200. -
Django subclass model gives "duplicate key value violates unique constraint" on save
I have a class with many fields: class Parent(models.Model): id = models.AutoField(primary_key=True) ... many more fields and I create a subclass class Child(Parent): other_field = models.CharField(max_length=512, blank=True, null=True) date_featured = models.DateField() After I migrate and create a Child object in the admin I get duplicate key value violates unique constraint "parent_pkey" DETAIL: Key (id)=(5) already exists. I've seen some similar questions that suggest that you modify the database but I can't easily do that. Do I need to change the id of the subclass?