Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to authenticate for login
How I can authenticate my user for login ,here authenticate does not work properly I have used authenticate for login views.py from django.shortcuts import render from basic_app.models import Signup from django.contrib.auth import authenticate,login,logout from django.http import HttpResponse,HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required def signup(request): if request.method=="POST": obj=Signup() obj.username=request.POST.get('username') obj.password=request.POST.get('password') obj.save() context={'username':'username'} return render(request,'basic_app/singup.html',context) else: return render(request,'basic_app/singup.html') def login(request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(username=username,password=password) if user: return HttpResponse("you have login") else: return HttpResponse("wrong password or username") else: return render(request,'basic_app/login.html') -
how to add ajax to django webpage
I am working on a django application. This application hold two forms. In the first form (image_form) the user can upload an image. In the second form (image_description) the user can fill some description about the image. when the image is uploaded in the first form, an image classifier runs on the image tries to fill parts of the image_description form. Once the second form is submitted the item is displayed in a new page (item_list). This is the urlpatterns for the application. urls.py urlpatterns = [ path('', views.index, name='home'), path('accounts/', include('django.contrib.auth.urls')), path('signup/', views.signup, name='signup'), path('items/', views.item_list, name='item_list'), path('items/upload/description/', views.upload_item, name='upload_item'), path('items/<int:pk>/', views.delete_item, name='delete_item'), path('items/upload/image_classification/', views.image_classification, name='image_classification'), ] here item_list is the page where all items are displayed. This page is displayed once the image_description form is submitted. upload_item page contains both the forms. image_classification runs when upload image button in the first form is clicked. This happens in the upload_item page. views.py def item_list(request): items = Item.objects.all() return render(request, 'item_list.html', {'items':items}) def upload_item(request): if request.method == 'POST': form_des = ItemForm(request.POST, request.FILES) if form_des.is_valid(): form_des.save() return redirect('item_list') else: form_des = ItemForm() return render(request, 'upload_item.html', {'form_des': form_des}) def image_classification(request): form_des = ItemForm() if request.method == 'POST': if 'file' in request.FILES: handle_uploaded_file(request.FILES['file'], … -
Django rest-framework with react - blank page on frontend
I have this code on my react App.js: import React, { Component } from 'react'; import axios from "axios"; import './App.css'; class App extends Component { state = { inventory: [] }; async componentDidMount() { try { const res = await fetch('http://localhost:8000/items/'); const inventory = await res.json(); this.setState({ inventory }); } catch (e) { console.log(e); } } render() { return ( <div> {this.state.inventory.map(item => ( //<div key={item.url}> <div className="App"> <h1>{item.name}</h1> <span>{item.url}</span> <span>{item.price}</span> <span>{item.scalable}</span> <span>{item.taxable}</span> </div> ))} </div> ); } } export default App; I'm using django react-framework, I want to communicate from react frontend into my django backend through the framework. So, inventory is the name of the django app. Which is registered on my settings.py file as inventory. It has a model of course, and one of the classes of this model, is item, which, on my django backend api, the url is defined as items. Like this router.register(r'items', ItemViewSet). it's like a list of all the products on the database. The typical rest-framework viewset. Also, this is all serialized, and it's working well on the backend, if I access http://localhost:8000/items/ it works, but the problem is the frontend, it just shows a blank page. My index.js hasnt been … -
Django REST API without using Database
I have an existing Django application. I need to include a functionality in it which doesn't involve DB. I have written the operation to be performed in views.py class VamComponent(View): def getSectionADetails(self,request): ....... return HttpResponse() In urls.py I have included this line in urlpatterens url(r'^vamcomponent$', VamComponent.as_view()) I am able to access the details from this url http://localhost:8000/vamcomponent/ . I need to have my endpoints with some value for section in the url like http://localhost:8000/vamcomponent/SectionA and http://localhost:8000/vamcomponent/SectionB. In views.py if I modify the class to have 2 functions it,based on the value of section in the request it should call the respective method class VamComponent(View): def getSectionADetails(self,request): ....... return HttpResponse() def getSectionBDetails(self,request): ....... return HttpResponse() How to make this change in urls.py file so that getSectionADetails() is called when the request has SectionA in it else getSectionBDetails()? -
Stripping/adding offset-aware info from datetime
I've got the following function to round a date time up to the nearest X minutes def round_time_up(dt, delta): return dt + (datetime2.min - dt) % delta Within another function, I call round_time_up: rounded = round_time_up(end_time, timedelta(minutes=15)) This code works within one of my .py files, but when I use this same code in another py file, I get the following error: can't subtract offset-naive and offset-aware datetimes My end_time has nothing to do with timezones. It's a time entered by the user and then stored as a datetime object. 1) In order to get this to work, how do I check if end_time is currently offset-naive or offset-aware? 2) How to I add offset-awareness or remove it from a datetime object? Thanks! -
How i can Schedule tasks (with starting date and ending date) in django to perform some calculation and save them into database?
Three models : User Membership PurchasedMembership How application works Each membership having starting date and ending date. User can purchase the membership and their information stored into PurchasedMemebership model. When membership date expire (ending date greater then current date) then count the each membership and store the counted value into total_membership (PurchasedMemebership model field). I have 3 solutions with issues Do manually like when membership ending date met call the perform_Calculations(request) function.(Doing manually) Increment the total_membership filed when user purchased the membership. Race condition will be occur. When user purchased the membership or view the membership then check ending date and perform the calculation but the issue is that every time user view the membership after ending date it will be performing extra check (if-else). What i want No performance issues. Best way to solve this problem. How to handle race condition ? How to schedule tasks ? Any django package with no stability issues ? Which of my solution is good and how it can be ? Django Models User model store the user information. class User(models.Model): #Django User Model This model store the membership details. class Membership(models.Model): title = models.CharField(max_length=100) start_date = models.DateTimeField(auto_now_add=True) end_date= models.BooleanField(default=None) total_membership = models.IntegerField(default=0) … -
Python & Heroku: How to send tasks to background workers in Heroku?
I'm currently building a Django app on Heroku. I currently have background tasks setup, but I am only able to run tasks on the web dyno instead of the worker dyno. How can I send tasks to the worker dyno instead? If I run heroku run python manage.py worker 'queue name', it creates a worker within the web dyno. I have the procfile set to spin up a rqworker, so the worker runs great. I've followed the tutorials on the heroku site to no avail. -
How to get response from django rest api in jsend format?
I am a complete beginner in django and django rest framework. I want to get the response in the jsend format where success ,fail, error message and status code is displayed. Any video tutorial or blog tutorial will help a lot. The main problem is I couldn't find how to get back success ,fail, error message and status code. -
I want to integrate MQTT with django for a smart lock how to use in production
I want to use mqtt in django of IOT and i want to subscribe a topic in django and i want to do operation on that JSON data which is provided by the publiser. -
Image is not being resized
I have form where the user chooses their profile picture and writes their bio. The form should take the uploaded image and resize it to 200x200. It uploads the picture, but the resizing does not take place. I tried following this tutorial: However, for some reason my image is still not able to resize when I upload it. Here's my code: class ProfileForm(ModelForm): avatar = forms.ImageField(required=False, widget=forms.FileInput) bio = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, "placeholder": "Bio"}), max_length=200, required=False) class Meta: model = Profile fields = ['avatar', 'bio', 'gender''] def save(self, *args, **kwargs): profile = super(ProfileForm, self).save() image = Image.open(profile.avatar) resized_image = image.resize((200, 200), Image.ANTIALIAS) resized_image.save(profile.avatar.path) return profile class Profile(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.CharField(max_length=200, null=True) avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) The image is being uploaded and everything is working fine, however, the image is not being resized. -
Converting HTML form to Django form
im creating a website with django and i made the site in html before moving to django and i know need to know how to create this in a djang form and store is in a model, any help much appreciated <form> <div class="newEvent"> <fieldset id="ResultSheet"> <legend>Result Sheet</legend> Event: <br> <select name="Events" id="Events"> <option disabled selected value> --SELECT AN OPTION BELOW-- </option> <option value="100 Metres">100 Metres</option> <option value="200 Metres">200 Metres</option> <option value="300 Metres">300 Metres</option> <option value="400 Metres">400 Metres</option> <option value="800 Metres">800 Metres</option> <option value="1500 Metres">1500 Metres</option> <option value="400 Metres">400 Metres</option> <option value="Hurdels">Hurdels</option> <option value="Shot Put">Shot Put</option> <option value="Discus">Discus</option> <option value="Javelin">Javelin</option> <option value="Long Jump">Long Jump</option> <option value="High Jump">High Jump</option> <option value="Triple Jump">Triple Jump</option> <option value="4x100 Metres Relay">4x100 Metres relay</option> </select> <div class="newParticipant"> <br> Placing: <input type="number" name="placing" min="1"> First name: <input type="text" name="fisrtName"> Last Name: <input type="text" name="lastName"> Result: <input type="number" name="result"> </div> <input type="button" class="newPupil button" name="newPupil" value="New participant"> <input type="submit" value="Submit" class="button"> </fieldset> </div> </form> <input type="button" id="addEvent" name="addEvent" value="Add Event" class="button" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <button value="Refresh Page" onClick="refreshPage()" class="button">REFRESH</button> -
How to get the number of m2m attribute with a conditional in Django models
For example, there have two class in Django model: class Generus(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) LIST_KLP = ( ('Marbar', 'Marbar'), ('Marsel', 'Marsel'), ) klp = models.CharField(max_length=6, choices=LIST_KLP, default='Marbar') def __str__(self): return self.user.first_name class Event(models.Model): LIST_EVENT = ( ('Mince', 'Mince'), ('Persami', 'Persami'), ) name_event = models.CharField(max_length=20, choices=LIST_EVENT, default='Persami') attendance = models.ManyToManyField(Generus, related_name='foo', blank=True) def __str__(self): return '%s %s' % (self.jenis_kegiatan, self.tanggal) From those class, I want to get the number of the attendance which has the klp = Marsel. Is there any possible solution? -
How I can create a signup and login page in django ,I dont want to use inbuilt form or User
How I can create a simple login and signup page in I dont want to use inbuilt form or authentication ,I am new in django so I want to understand the basic concepts ,Thanks in advance -
How to override some methods inside of the installed plugin
I am using django import-export and I am trying to override the forms.py to include additional options. I know in order to override django admin templates I need to create an admin folder inside of the templates/admin/base.html. The question is how would I do that inside for the plugin Forms.py -
add channel in group in django channels
I am trying to use django channels library for my project. Basically, i am trying to implement the next algorithm: User "X" presses the button to make a new chat with "Y" user. The very record to database regarding this event I have made, but how can I include both of this users to the group, so they can communicate with each other in real time? Cannot resolve this issue for a long time ((( Thank you! -
Forgotten psql Password: sql: FATAL: password authentication failed for user "username"
I have created a database with a database user and password using the psql shell. Now, I want to create another additional database using the shell. However, when I enter psql in Windows Command Prompt, I am prompted to enter my password, which I have forgotten. It says sql: FATAL: password authentication failed for user "username" I want to keep my other databases I created 100% in tact and functioning but would like to create another database in addition. What should I do to accomplish this without messing up the other database? -
How to count on distinct fields with subquery in the FROM clause, using Django ORM?
I have a GameInstance model that tracks player/score history which looks like this: class GameInstance(Model): id = AutoField() username = CharField() console = CharField() score = IntegerField() I want to get a count of how many of each console is being used. Obviously a player can have multiple records of gameplay, so the console for a player with multiple records should only be counted once (if player plays on 2 different consoles with same username, 1 count for each console). The way I'm trying to achieve this is by first getting all distinct username/console combinations and then counting for each console in the resulting set. The SQL query would look like this: SELECT console, COUNT(console) AS console_count FROM ( SELECT DISTINCT console, username FROM GameInstance) AS x GROUP BY console Output: console | console_count ----------------------- Xbox | 100 PC | 200 PS4 | 150 Using Django ORM I can get the inner FROM clause queryset easily: subqueryset = GameInstance.objects.values('console', 'username').distinct() And I know I have to annotate for count, something along the lines of: queryset = subqueryset.values('console')annotate(console_count=Count('console')) # Does not work But I'm having trouble combining these two aspects (since you can't call values() on the same queryset multiple times). … -
How can I use Create View and is it possible to avoid dependent- drop-down list?
I have been working on this project for quite some time and learned everything except HTML and CSS from scratch. However, I have been stuck on different occasions and gotten a lot of help here. This time, I would like to know what kind of queries do I need to use to get the results I need. The goal is to have my result viewed using CreateView on a different template using the forms that I have. I have two ModelForm and both of them are ModelChoiceField except that the first one is ModelMultipleChoiceField I have my forms.py down here and am not sure if I have defined my save function correctly. from django import forms from betterforms.multiform import MultiModelForm from .models import Topic, Image, Question, Answer class TopicForm(forms.ModelForm): topic_name = forms.ModelMultipleChoiceField( queryset = Topic.objects.all(), widget = forms.SelectMultiple( attrs = {'class': ''} )) class Meta: model = Topic fields = ['topic_name',] class QuestionForm(forms.ModelForm): topic_name = forms.ModelChoiceField( queryset = Topic.objects.all(), widget = forms.Select( attrs = {'class': ''} )) class Meta: model = Question fields = ['questions_type',] class QuizMultiForm(MultiModelForm): form_classes = { 'topics' : TopicForm, 'questions' : QuestionForm } def save(self, commit=True): objects = super(QuizMultiForm, self).save(commit=False) if commit: topics = objects['topics'] topics.save() … -
Using filtered table values as choices in django
I am using django 2.1.5v and am creating models which will be used in the admin section and am trying to avoid creating a separate view for the same. Here are my models: class Schedule(models.Model): instructor = models.ForeignKey(Instructors, on_delete=None, to_field='username') start_time = models.DateTimeField('Start Time', default=None) course_name = models.ForeignKey(Course, unique=False, on_delete=None, to_field='course_name') def __str__(self): return 'Course {}, Start {}, End {} Room {}'.format(self.course_name, self.start_time, self.room_number) The model for attendance is as below: class InstructorAttendance(models.Model): instructor = models.CharField(max_length=200, editable=False) # course_name = LIST PICKED FROM SCHEDULE BASED ON INSTRUCTOR NAME lecture_date = models.DateField('Lecture Date', default=None, auto_created=False, blank=False, null=False) def __str__(self): return '{} Conducted'.format(self.lecture_date) I want a attribute course_name in the InstructorAttendance model which will be list of course_name's picked up from the list of schedules created/available. If it is not there then no option should be there in the dropdown. This will be in the admin section and I have registered the model like admin.site.register(InstructorAttendance). I am trying to use choices, but seems it is not possible. Anyone can help me with this? -
Session- webapp with django
I created a webapp with django by usibg posthresql. How can i use session to logout user when there's no activities in all pages of the webapp open in tabs ? How to start in order to better understand what is sessiin.? -
Django 'User' object has no attribute 'Goals'
I have created a function that can save multiple goals per one user and display them in an html file. The issue is once I logout, I cannot log back in with the same user as I get the error 'User' object has no attribute 'Goals', even though it is saved in the database. My question is what is causing this error, the references to goals in my view maybe, and what is a potential solution? Thank you! models.py class Goals(models.Model): user = models.ForeignKey(User, null=True, default=None, on_delete=models.CASCADE) goal = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) goal_date = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.Goals @receiver(post_save, sender=User) def create_user_goals(sender, instance, created, **kwargs): if created: Goals.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_goals(sender, instance, **kwargs): instance.Goals.save() class GoalsForm(ModelForm): class Meta: model = Goals exclude = ('user',) views.py def goal_creation(request): form = GoalsForm() cur_goals = Goals.objects.filter(user=request.user) if request.method == 'POST': form = GoalsForm(request.POST) if form.is_valid(): goals = form.save(commit=False) goals.user = request.user goals.save() cur_goals = Goals.objects.filter(user=request.user) return redirect('/student/goal-progress') else: form = GoalsForm() context = {'form' : form, 'goals': cur_goals} return render(request, 'student/goal_creation.html', context) -
How to Filter the authenticated user by the Staff Status in Django? I'm in Trouble
Here all My codes and I haven't set it yet, just a regular auth class login(View): template_name = "admin/page.html" context = {} def get(self, *args, **kwargs): next = self.request.GET.get('next') forms = adminForm() if next : self.context['next'] = next self.context['forms'] = forms return render(self.request, self.template_name, self.context) def post(self, *args, **kwargs): forms = adminForm(self.request.POST or None) next = self.request.POST.get('next') if forms.is_valid() : user = authenticate(username=forms.cleaned_data.get('username'), password=forms.cleaned_data.get('password')) login(self.request, user)# authenticate(username=forms.cleaned_data.get('username'), password=forms.cleaned_data.get('password'))) if next : return redirect(next) return redirect('/admin/users') if not forms.is_valid() : self.context['errors'] = 'Invalid Username or Password' self.context['forms'] = forms return render(request, self.template_name, self.context) -
itertools.groupby can not group django queryset by a foreignkey correctly
Supposed I have the following models: class Category(models.Model): name = models.CharField(max_length=10) class Post(models.Model): title = models.CharField(max_length=10) category = models.ForeignKey(Category, on_delete=models.CASCADE) Then, I want to select all posts and group them by category: from itertools import groupby from operator import attrgetter qs = Post.objects.all().select_related('category').order_by('category') posts_group = groupby(qs, key=attrgetter('category')) However, posts_group doesn't contain the expected data. For example, I hava two posts in database, the belong to different category. The query does select all category but only one post display in last category group. -
How does Django model save data that is cleaned?
I've seen bits and pieces of this, but am having trouble putting it all together. Let's say I have a model with a field: class MyModel(models.Model): my_field = models.CharField(...) And I want to remove all of the "x's" from my_field and save it: def clean(self): x_less = self.my_field.replace('x', '') How do I get x_less to the save method? or how does the cleaned data get saved? def save(self, *args, **kwargs): self.my_field = x_less #?????? super().save(*args, **kwargs) If there is a good tutorial that I missed somewhere, please let me know. Thanks. -
Temporarily disable Django cache during Unit Test
Is it possible to run some unit tests with real cache and some with dummy cache ? I'm trying to change cache settings in unit test, but it's not working. class SomeUnitTests(unittest.RollbackTestCase): def setUp(self): settings.CACHES['default'] = {'BACKEND': 'xxx.xxx.DummyCache'}