Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Triggering creation of new object on CreateView form submission
First of all, my apologies if my questions are too obvious or if this has been discussed in another topic. I've been working on this issue for almost a week and searching for similar topics without success. I'm not a professional programmer but I love creating some useful pieces of software. So I'm programming a webapp to have control on substances in my laboratory. I've set one model for a substance (which takes the name from another model called SubstanceDict), another for quality control, and another one for substance status, lets say: class Substance(models.Model): reg_num = models.CharField(max_length=11, default=adding_reg_num, editable=False) name = models.ForeignKey(SubstanceDict, on_delete=models.CASCADE) provider = models.CharField(max_length=20) '''some other fields and functions in here...''' @receiver(post_save, sender=Substance) def set_to_quaratine(sender, **kwargs): if kwargs.get('created', False): SubstanceStatus.objects.get_or_create(origen=kwargs.get('instance'), status=0, comments="Set to quarantine whilst reception.") class QualityControl(models.Model): qc_reg_num = models.CharField(max_length=12, default=adding_qc_reg_num, editable=False) source = models.ForeignKey(Substance, on_delete=models.CASCADE, related_name='quality_control') '''whatever else''' class SubstanceStatus(models.Model): source = models.ForeignKey(SustanciaDetalle, on_delete=models.CASCADE, related_name='status') status = models.IntegerField(choices=( (0, 'Quarantine'), (1, 'Approved'), (2, 'Rejected'),), null = False) quality_control = models.ForeignKey(QualityControl, on_delete=models.CASCADE, blank=True, null=True) date = models.DateTimeField(auto_now_add=True) comments = models.TextField() So basically, using CreateView for Substance Model, whenever I create a new instance of Substance, the @receiver triggers the creation of an instance of SubstanceStatus with status … -
Django unit testing for custom admin site
I am new to Django unit testing. Can Someone tell me how to unit test Django custom Admin? I am just copy pasting the code from the Django docs class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('email', 'date_of_birth') def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin') def clean_password(self): return self.initial["password"] class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'date_of_birth', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('date_of_birth',)}), ('Permissions', {'fields': ('is_admin',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'date_of_birth', 'password1', 'password2')} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () I read that we can create superuser in testing. Is it necessary to create superuser while testing the above classes? I have changed my User little bit, I tried to test the UserCreationForm class but I am not sure of that class … -
How to provide a counter feild for every user in django model?
I want to provide a counter field in my Group1 model i.e. whenever a user create a new group1 object it will save the counter as it is... For example: If a user create a new group1 object it will save the counter field value as 1, then 2 for another new group1 object and so on. And I want to do this for every user i.e. for every user the counter field value should start from 1. This is my Group1 model: class Group1(models.Model): counter = models.IntegerField() user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) group_Name = models.CharField(max_length=32) Do anyone have any idea about how to perform this? Thank you -
How "python manage.py runserver" works?
I have been looking for how Django works internally but; I didn't even find it in their official documents. When we run the command "python manage.py runserver" what exactly happens in back-end? How this command works? What steps it takes? How it triggers file and initiate server? How django serve each and every file in our application? I want to know everything. Can somebody help? -
How to save the distance between two Postal Codes in a Postgres database (Django)?
I have a database of Indian PIN (Postcodes around 19000+) and their centroid Latitude and Longitude. Now for my application, I need a ready reckoner which can tell me the driving distance between two pin codes (I can find this value one time using the Google Maps Distance API). My question is as follows: Once I calculate the distance between 110012 and 400094 how do I store this value in a postgres Database so I know this for all future uses (querying the API repeatedly for the same information would be very expensive financially) My approach till now: I thought about storing it as a many to many model, but I calculate it will be about 180 million records. Is there a more efficient pattern to store this data? Also am I going about this wrong and is there a more pythonic way to do it. I can't use the Haversine Formula or pgeocode because they return the geographic distance not driving distance. -
Django auto logout not updating in Database
I'm working on a project using Python(2.7) and Django(1.11) in which I was needed to implement auto-logout on inactivity for a few minutes or hours. Note: I have searched a lot and take a look on a various related question but couldn't find any solution for my specific problem, so don't mark it as duplicate, please! I have achieved this thing by adding some settings in settings.py as: SESSION_COOKIE_AGE = 120 SESSION_SAVE_EVERY_REQUEST = True LOGOUT_REDIRECT_URL = 'mainlogin' Only for testing purpose, I have set it up for 1 minute. After 2 minutes then when I refresh the page user get logged out and redirected to the login page but in the backend/database the status of the user is still active. I need to use the active users for further processing/execution, so if a user logged out automatically it shouldn't be available is an active user, but it is. If I manually logged out the user, it's not displaying in the active user anymore, this means the manual logout is working well but the auto log out still shows the user as an active user. Here's how I'm getting the active users: all_active_users = user_table.objects.filter(user_type='a', status=1, approval_status=1, is_active=True) # further execution … -
Djnago2.1 making social group like in the Facebook
I am learning django these days . I wish to make a social group where user can post articles ..do likes or comment in the articles like as in the Facebook -
Django {% extends 'home.html' %} does not transfering dynamic content from extended page to new page
Is that possible to see extended dynamic content((link.nameOne,link.nameTwo)) from home.html page on next.html page on By using following code: home.html <!doctype html> <html lang="en"> <head> </head> <body> <header> <ul> {% for link in links.all %} <li> <a href="{{ link.nameOne }}">{{ link.nameTwo }}</a> </li> {% endfor %} </ul> </header> {% block content %} {% endblock %} <footer> </footer> </html> nextPage.html {% extends 'home.html' %} {% block content %} Hello world! {% endblock %} -
How to Show Foreign Key data in Django rest framework?
Model: class Demo(models.Model): name = models.CharField(max_length=255) desc = models.TextField() user = models.ForeignKey('auth.User', on_delete=models.CASCADE) Serializer: class DemoSerializer(serializers.ModelSerializer): class Meta: model = Demo fields = '__all__' I have form in frontend side where I'm adding name, desc and assigning to User so here I'm getting on an issue. I'm passing data to API {name: "demo", desc: "lorem ipsum", user: 1 } It's working on save but after saving it's return same response but I want user first_name, last_name, and email in return response. Because I have a table showing a list of demo table content. but always getting only User ID not a detail of user. If I'm increasing depth of Serializer It's creating an issue in save time but on get records time I'm getting all details of User model. Like Password also in response so that is a security issue for me show all thing. -
Django 2.1.7 - Retrieve all Model fields from user(x)
Hello this is my first post on here. I am new to python and django and i am trying to learn more about both so i am working with them to gain more experience. I am trying to get all the metros for user(x) lets say 1. I want to be able to have user 1 as the id and get all the metros associated with that user. Models from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Metro(models.Model): class Meta(): verbose_name_plural = "MetroCards" owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Creator") metro_name = models.CharField( max_length=30) created = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.metro_name} by: {self.owner}" Views from django.shortcuts import render, redirect, Http404 from .models import User, Metro from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm def user(request, user_id): try: user = User.objects.get(pk=user_id) metro = Metro.owner.get(pk=user_id) except User.DoesNotExist: raise Http404("User Does Not Exist") context = { "user": user, "metro": metro } return render(request, "metrocard/user.html", context) Urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path("user/<str:user_id>", views.user, name="userid"), path('map/', views.map, name='map'), ] Html <h1>User Id: {{ user.id}} </h1> <ul> <li>Username: {{ user.username }} </li> <li>Email: {{ … -
patch doesn't work with pytest when not specifying a directory
I have a weird problem with pytest and mock patching. My django app calls currency exchanges' APIs when receiving a request. I want to patch them while testing, but it doesn't work. The command below succeeds. It doesn't send any request to real exchange servers. pipenv run pytest --reuse-db myapp But, the command below fails because it sends requests to real exchange API servers. Seems patching is not working. pipenv run pytest --reuse-db The project structure looks like this. django_proj/ django_proj/ myapp/ views.py urls.py backends/ backend1.py backend2.py tests/ test_views.py test_views.py class MockBackend1: # Some mock methods # They returns mock values instead of sending requests to real servers. class MockBackend2: # Some mock methods # They returns mock values instead of sending requests to real servers. @patch('myapp.backends.backend1.Backend1', MockBackend1) @patch('myapp.backends.backend2.Backend2', MockBackend2) class TestListAPIView: @pytest.fixture ... def test_list(self, client, params): """Test list.""" response = client.get( reverse("myapp:list"), data=params ) content = response.json() # sample assertion asset content == mocked_content What causes the difference above? And how can you make patching work properly in both cases? Thanks in advance. -
Sum TimeField hours/minutes with Pandas
I am trying to use Pandas to sum the time (hours, minutes) of a series. The data comes from a TimeField class PhoneRecord ( models.Model ): et = models.TimeField ( null=True, blank=True ) In python I get the record and convert to a dataframe. phone = PhoneRecord.objects.all() df = read_frame ( phone ) df.et = df.et.fillna ( '00:00:00' ) # some records are blank df [ "time" ] = pd.to_datetime(df.et, format = '%H:%M:%S', errors = 'coerce') this gives me the following output. 0 00:00:35 1 00:00:29 2 00:00:00 3 00:00:00 4 00:00:37 ...... When I try to sum df.time.sum () I get errors like: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time' What do I need to do to be able to sum and average the data. Thank you. -
Configuring django-celery-email with django-anymail
I am using django-anymail(sendgrid) to send emails in my web app. I would like to let the emails send in asynchronous manner without letting the users wait for some time.So, how can I configure django-celery-email with django-anymail. Now, my email config. is: ANYMAIL = { "SENDGRID_API_KEY": os.environ.get('SENDGRID_API_KEY') } EMAIL_BACKEND = "anymail.backends.sendgrid.EmailBackend" -
Getting Session Variable In Views -- Django
I am trying to assign the GET request value to symbol if the user has just filled out the form on the previous page. I can navigate to other pages and request the session variable, but when I go back to the index, it is no longer there. def index(request): if 'symbol' in request.GET: symbol = request.GET.get('symbol', '') request.session['symbol'] = symbol elif not request.session.get('symbol', 'none'): symbol = request.session['symbol'] return render(request, 'backtests/earnings.html', {'symbol' : symbol}) I know there are a few things wrong with this code, but I really do not know where to take this. As of now, I am getting the error local variable 'symbol' referenced before assignment -
passing variable from js to django view
I'm Trying to pass data from javascript on a page to another view in my django project.But it seems the view isn't getting called. What I want to do is that Using JS I want to just get data from page containing the JS and print it from django view to console. js on html page: <script> var URL="{% url 'projects:Unread' %}" function Unread(){ var data = {'count': '5', 'X-csrfmiddlewaretoken': csrfmiddlewaretoken}; $.post(URL, data); } </script> somewhere from page I'm calling this function,I have used an alert to make sure it is called. my urls.py : path('notification/',Unread,name='Unread') my view: def Unread(request): count=request.body['count'] print("hello") print("count status ",count) I have also tried request.POST to get value but now working.What I exactly want is to get 'count' from JS to my view.But its not happening, Even the 'hello' is not getting printed it's not even related to JS.I'm fairly new to both django and JS so I'm not sure what I'm doing wrong. Thanks in advance :) -
Wagtail- 'Save Draft' Page appears on user side
I along with my project team build a website for our client using Python and Django framework. I have a functionality question regarding Wagtail as we have integrated Wagtail in our Django Project and are facing a minor issue. Q. When I create a page and choose "Save Draft" as an Admin, the Page still appears on the user side even though I haven't published it, is there a way to avoid it? -
how to pass variable from DOM script to href link
I want to pass a variable from java script to html link. <li hidden><a id="url_call" href='/paytm/response/?response={{response}}' value="{{response}}">{{response}}</a></li> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "rzp_test_rpDFJlAD0LDl8Y", "subscription_id": "{{ sub_id }}", "name": "My Billing Label", "description": "Auth txn for sub_8seKGNhVEOwnjj", "handler": function (response){ // alert(response.razorpay_payment_id); document.getElementById("url_call").click(response); } }; var rzp1 = new Razorpay(options); document.getElementById('rzp-button').onclick = function(e){ rzp1.open(); } </script> In the above code I want to variable response from "handler": function (response){ // alert(response.razorpay_payment_id); document.getElementById("url_call").click(response); } to <li hidden><a id="url_call" href='/paytm/response/?response={{response}}' value="{{response}}">{{response}}</a></li> I think the way im doing is wrong. Could soemone help me with this? Thanks. -
Cannot connect to the EC2 instance through port 8000
I am running the Django on my EC2 instance, I use the Route 53 to map the instance to the mengshushi.com. Right now I am trying to access the instance through the port 8000, mengshushi.com:8000. But it returns timeout. Here are the informations. 1, Instance ID: i-0ea258cf3216757a7 2, Instance IP: 3.17.158.238 3, The security group inbound is Ports Protocol Source launch-wizard-4 80 tcp 0.0.0.0/0, ::/0 ✔ All All 0.0.0.0/0, ::/0 ✔ 8000 tcp 0.0.0.0/0, ::/0 ✔ 22 tcp 0.0.0.0/0 ✔ 443 tcp 0.0.0.0/0, ::/0 ✔ 4, There is a app listening port 8000 on the instance. $ sudo netstat -plnt Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 2660/rpcbind tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 3322/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 3145/master tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 13995/python tcp6 0 0 :::111 :::* LISTEN 2660/rpcbind tcp6 0 0 :::22 :::* LISTEN 3322/sshd 5, The connection on the instance itself is success. Use the telnet on the instance: $ telnet mengshushi.com 8000 Trying 3.17.158.238... Connected to mengshushi.com. Escape character is '^]'. 6, The connection outside the instance will timeout. nc -v mengshushi.com 8000 nc: connect to … -
Getting wrong values in Jinja2
I am passing a dictionary from python to my HTML in Django, and then I want to get the value of a particular key. I pass the dictionary in a for loop, and then search for the key using an if statement. If that key is found, print the value. Below is the dictionary passed: {'id': 1, 'book': {'isbn': '0439554934', 'isbn13': '9780439554930', 'title': "Harry Potter and the Sorcerer's Stone (Harry Potter, #1)", 'publisher': 'Scholastic Inc', 'publishYear': 1997, 'publishMonth': 6, 'edition': None, 'rating': '4.46', 'popularity': 25779963, 'authors': ['J.K. Rowling'], 'genres': ['fiction', 'fantasy', 'young-adult']}, 'userID': 1, 'price': '10.00', 'condition': 'New', 'image1': '', 'image2': '', 'image3': '', 'image4': '', 'image5': '', 'comment': ''} I then want to get the title of the book so below is my code: {% for key, value in book.items %} {% if value.title %} <h3> {{value.title}}</h3> {% endif %} {% endfor %} However, not only do I get the title, I also get the price and condition printed. Can someone please let me know what I am doing wrong? -
aggregation of a dictionary list
I'm trying to sort and aggregate this data that I have located in a django app that I am working on. Problem is that I am lost on the best way to iterate through the lists and store the data. Here is an example of what I have: from score.models import LocData q = [ {'ref': '002', 'loc': 'seattle', 'total': '200'}, {'ref': '002', 'loc': 'seattle', 'total': '100'}, {'ref': '123', 'loc': 'dallas', 'total': '100'}, {'ref': '452', 'loc': 'cleveland', 'total': '600'}, {'ref': '123', 'loc': 'dallas', 'total': '200'}, {'ref': '002', 'loc': 'seattle', 'total': '300'} ] What I would like to end up with is the list below, it's aggregated by the ref field and maintains this field with the loc, but adds the total field. Here is the desired output. q = [ {'ref': '002', 'loc': 'seattle', 'total': '600'}, {'ref': '123', 'loc': 'dallas', 'total': '300'}, {'ref': '452', 'loc': 'cleveland', 'total': '600'}, ] Can someone clue me into what tools I have available to do this? Thanks in advance! -
How to stop a form zooming out of a fixed div?
I have a div here with a form in it and despite setting the div to fixed, the form inside it will not fix at all and zooms out of the bottom of it when the page is zoomed in and out (browser). I have tried all sorts, such as setting style="position:fixed;" in the form's inline css and copying the style of the parent div and putting it in the form's inline css but it doesn't work. <main role="main" class="mx-auto"> {% load staticfiles %} <div style="position: fixed; width: 50%; height: 100%"> <img src="{% static "img/shard.jpg" %}" style="object-fit: cover; object-position: 100% 0; width: 100%; height: 100%;"></img> <div style="background-color: white; padding: 0% 3% {% if messages %}1%{% else %}1.5%{% endif %}3%; width: 58%; position: fixed; right: 10%; top:30%; bottom:20%; box-shadow: 0 4px 16px -7px gray;"> <form method="POST" class="" action="{% url 'users:login' %}"> {% csrf_token %} <h1 class="h3 mb-3 font-weight-normal text-center" style="padding-top:3%">Login</h1> <input id="username" name="username" type="text" class="form-control" required placeholder=Username> <input id="password" name="password" type="password" class="form-control" required placeholder=Password> <button class="btn btn-sm btn-primary btn-block center-align" type="submit">Login</button> </form> <div class="center-align" style="padding-top:5px"> <button class="btn btn-sm btn-primary btn-block" style="background-color: #151515;">Register</button> </div> <div style="padding-top:10px"> {% if messages %} {% for message in messages %} <div class="alert alert-danger" role="alert"> {{ message … -
How can I access instance of a model to get the fileds data
I created an Address model: class Address(models.Model): name = models.CharField(max_length=100, blank=False) address1 = models.CharField("Address lines 1", max_length=128) ... in my views.py when I try to access the data, it doesn give me anything, this is what I've tried: user_AddressForm = AddressForm(instance=request.user.profile) and user_AddressForm = AddressForm(address_listNames) where address_listNames is are the objects: <QuerySet [<Address: Elizabeth's house>, <Address: Work>, <Address: Home>]> When I display the form in the html: {% for address in user_AddressForm %} {{ address }} {% endfor %} it's empty, I'm only getting 2 zipcodes, how can I get the data? Thank you -
Cannot assign "'2'": "TakenQuiz.question" must be a "Question" instance
I am trying to insert those value I got from radio buttons after the user as taken options. Then, I want to insert it into another table which I will use to prepare the final result for the student. After taken all my values and created insert query, I am getting this error. Kindly, see all the code below. enter image description here models.py class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='questions') text = models.CharField('Question', max_length=500) def __str__(self): return self.text class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') text = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) def __str__(self): return self.text class TakenQuiz(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='taken_quizzes') course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='taken_course') question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='taken_question') selected_choice = models.ForeignKey(Answer, on_delete=models.CASCADE, null=True) marks_obtained = models.DecimalField('Marks Obtained', default=0, decimal_places=2, max_digits=6) is_correct = models.BooleanField('Was this attempt correct?', default=False, null=False) date = models.DateTimeField(auto_now_add=True) views.py @login_required @student_required def take_exam(request, pk): course = get_object_or_404(Course, pk=pk) student = request.user.student question = course.questions.filter() #correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count() total_questions = course.questions.count() choice = Answer.objects.filter() marks_obtainable = Details.objects.get(course_id=course) if request.method == 'POST': question_pk = request.POST.getlist('question_pk') choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk] zipped = zip(question_pk, choice_pk) for x, y in zipped: correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values('id').first()['id'] #print(type(correct_answers)) #print(choice_pk) print(x, y, correct_answers) … -
How to order by a specific ForeignKey in django?
This is a kinda follow-up of this question: How to store a variable history in django? To simplify my problem, let's say I have a simple Gamer that track users settings and data, and a specific UserScore model to track a tuple of (time, score). class GamerExperience(BasicModelProperties): gamer = models.ForeignKey('Gamer', on_delete=models.CASCADE, related_name='experience_history') time = models.DateTimeField() experience = models.BigIntegerField() I would like to order every Gamer in the database by the highest (latest-score). Note that my Gamer model has a property that returns the latest score using self.experience_history.order_by("-time").first()["experience"] However, using sorted is really slow, and I'm sure there is another way to achieve that :) -
Auth.User.None when rendering a ManyToManyField
I am trying to render a ManyToManyField from a model that render a list of hotels with staff that belong to each hotel. I am trying to display in the template the users that are inside the current hotel being shown but I get an error auth.User.None my template {% for Hotel in object_list %} {{ Hotel.collaborateurs }} {% endfor %} My models.py class Hotel(models.Model): collaborateurs = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés") (....) Thanks