Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best django practice to collect and store users' interest data?
I need to implement the simpliest users interest module in Django. I have a very small web application with the ony search bar and a button. The search bar is intended for an account number input. After pressing the button users get information about the entered account number I need to collect and store data of users' interest by days. How many times data was searched everday. eg. | day |number of queries| |22 Oct | 7 | |23 Oct | 5 | ... Django 2.2.1 I created the model: models.py class LeadsNumber(models.Model): date_of_interest = models.DateField(blank=False) number_of_queries = models.IntegerField(blank=False, default=0) class Meta: ordering = ["date"] When the user input the data and press the button the function from view.py look for the existing model and then update or create a new instance of the LeadsNumber model for the day when the account number was searched. I guess there is a better way for implementing such thing. Share your thoughts please -
Dynamic Multi level approval system with django view flow
We have a request that needs to be processed by multiple users before it gets approved. The request can be approved by any user in a group or having certain permissions or the request be assigned to a certain user. What would be the best way to approach the problem using django-viewflow. Any suggestions would be appreciated. -
Have url with pk or id to redirect to update page in Django error message
I've creating a app, and on the CreateView page, the Submit button works fine to create new S Reference. I also created error message if the input value matches a existing Reference. I created button in the error message part and tried to link it to update page to update this reference fields, like primary contact. I tried many options but have not got right code for the argument with pk or id to get individual record update page. this is the url in error message. I tried quite few pk, id options, none of them works. 'pk'=self.pk; {'pk'=self.pk}; object.id some code as below models.py class LNOrder(models.Model): reference_number = models.CharField(max_length=15,blank=True, null=True, unique=True, error_messages={'unique':"This reference already exists."}) primary_contact = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) urls.py urlpatterns = [ path('lfcnotifier', LNCreateView.as_view(), name='lnorder_create'), path('lfcnotifier/<int:pk>', LNDetailView.as_view(), name='lnorder_detail'), path('lfcnotifier/<int:pk>/update/', LNUpdateView.as_view(), name='lnorder_update'), ] template <div class="input-group mb-3"> <div class="input-group-prepend w-225px"> <label class="input-group-text w-100">S Reference</label> </div> <input name="reference_number" type="text" class="form-control" placeholder="Enter your S Reference"/> <button class="btn btn-primary cardshadow " data-toggle="tooltip" title="Click to submit" style="width:200px;" type="submit">submit</button> {%for field in form %} {% for error in field.errors %} {{ error }} <a href="{% url 'lnorder_update' 'pk'=self.pk %}" class="shadow-sm col-sm-4 btn-block btn btn-primary mt-0">Update Request</a> {% endfor %} {% endfor %} … -
I want to access struct block default ID in its template
I want to save stream field ID into it's template. In short, in text_question.html I am giving id = {{ self.id }} but that return Nothing. I want this because in question.html file I want it to compare with {{ field.id }} which return stream field ID In another word, I want to store {{ field.id }}'s value in id field of text_question.html models.py class TextQuestionBlock(blocks.StructBlock): """Text Question""" question = blocks.CharBlock(required=True, help_text="Add your Question") is_save = blocks.BooleanBlock(label="Want to save this field ?", required=False) is_email = blocks.BooleanBlock(label="Want to get this field as an email ?", required=False) class Meta: # noqa template = "question/question_field/text_question.html" icon = "edit" label = "Text Question" @register_setting(icon='fa-commenting') class QuestionSettings(BaseSetting): body = StreamField([ ("text_question", TextQuestionBlock()), ], verbose_name='Question', blank=True) panels = [ StreamFieldPanel('body') ] class Meta: verbose_name_plural = 'Question' verbose_name = 'Questions' text_question.html {% load tag_library %} <input issave="{{self.is_save}}" isemail="{{ self.is_email }}" class="text_question" type="text" name="{{ self.question|to_name }}" id="{{ self.id }}" data-conv-question="{{ self.question }}" question.html <form name="question_form" action="" method="post" class="hidden"> <div id="unique_id"></div> {% for field in question.body %} {{ field.id }} {% endfor %} <input type="text" data-conv-question="test"> </form> Thank You!!! -
Trying to Write a Django Query That Counts Events Per Day For Events That Span Multiple Days
I am using Django and trying to count the number of events that are running on each day based on events running across multiple days. For example, if Event 1 starts on Monday and ends on Wednesday and Event 2 starts on Tuesday and ends on Thursday, the event count per day should be: Monday (1 event), Tuesday (2 events), Wednesday (2 events), Thursday (1 event). The event model looks like this: class Event(models.Model): name = models.CharField(max_length=300, blank=True) start_date = models.DateTimeField(blank=True) end_date = models.DateTimeField(blank=True) def __str__(self): return self.name I would like to get query results to include the date of the day we are counting for, the number of events running on that day, and the name of each event running on that day. Any help on this Django query would be helpful. Thanks in advance! -
Custom Button in django
enter code here I am trying to create custom Button in Django Admin class HeroAdmin(admin.ModelAdmin): change_list_template="hellogym/hellogymapp/templates/change_list.html" {% extends 'admin/change_list.html' %} {% block object-tools %} <div> <form action="immortal/" method="POST"> {% csrf_token %} <button type="submit">Make Immortal</button> </form> <form action="mortal/" method="POST"> {% csrf_token %} <button type="submit">Make Mortal</button> </form> </div> <br /> {{ block.super }} {% endblock %} I have created superuser Admin and I want a custom button inside it -
How to declare variable in django html file. not pass from any view. and i also update that variable
I check all blogs in stackorverflow but i doesn't find any solution. Django Template - Increment the value of a variable This link solution doesn't work. please tell me Other solution. -
ModuleNotFoundError: No module named 'project.appname' when running Django tests
When trying to run my tests using either ./manage.py test or pytest, all of the apps in my Django project fail their tests with ModuleNotFoundError: No module named 'project.appname'. However, when running with ./manage.py test app.tests (if the tests are in a dedicated tests directory), they do progress beyond a Module Not Found error. I think there is something wrong with my configuration that leads to this error but I have no idea where to poke to try fixing this: I'm not seeing anything that makes PyCharm yell at me when I look at any testing module nor when looking at Settings.py -
Stripe Payment Intent API Prevent Form From Submitting Until User Authenticates Card
Using the new Stripe Payment Intent API and Stripe.js, I want to be able to do the following: 1) If the user's card is valid but requires authentication (SCA), do not submit the form until the user clicks "complete authentication" on the 3D secure popup. 2) If the user's card is valid but does not require authentication (SCA), submit the form. Here is a video of my issue: https://streamable.com/797e5 As you can see from the video, the form submits itself with a card that requires authentication but the user does not have time to click "complete authentication" since the form refreshes the page immediately. Stripe support says JavaScript is needed to do this and provided me a PHP example. https://glitch.com/edit/#!/stripe-php-sca-example?path=public/charge.php:9:0 However, I am using Django and not PHP. I am also not sure how to code this in JavaScript. Any help would be greatly appreciated. Html: <form onsubmit="return false;" action="{{checkout}}" method="post" id="payment-form">{% csrf_token %} <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display form errors. --> <div id="card-errors" role="alert"></div> </div> <button id="card-button" data-secret="{{ client_secret }}"> Submit Payment </button> </form> <script src="https://js.stripe.com/v3/"></script> Stripe.js: var stripe … -
How to manually authenticate user in Django
hi I want to authenticate user manually how can I keep user signed in, in all applications of project? here's my login view function: def sign(request): context = {} if request.method == 'POST': form = SigninForm(data = request.POST) if form.is_valid: username = request.POST['username'] password = hashlib.sha256(request.POST['password'].encode('utf-8')).hexdigest() users = customer.objects.all() for user in users: if username == user.username: if password == user.password: context['tmp'] = "OK" -
Django use data in a class based view
I have a class-based view in Django. I have implemented a method get_context_data. A user can log in or update his/her data and is redirected to a class-based view template. I want the information of the logged-in user inside the class-based view. I'm not rendering the view, just re-directing. Is there any approach like saving the data in memory during computation or global variables so that it can be accessed anywhere in the views.py. -
How to put a randomly choice option in Django?
I am writing a web application in Python, using Django. I do have a drop down list of 12 items. With a current functionality, I can choose an item one by one, however, I would like to put an option which selects randomly the items in the interval of [1,12]. For example, by choosing the number 6 in the box, I can have 6 randomly chosen items. any help, hint will be appreciated a lot! thank you. -
save the data in the database by editing the table info - Django
I have a page "EditStudent" that display all absentee's name. This page allows the admin to change their status from absent to present or vice versa, add remarks if needed. The information displayed in the page involved two models. Namelist model.py: Contains all the students information such as studId, studName and more. MarkAtt model.py: save all the attended students that were marked during the class. So this model does not save the absentees name. So to retrieve the absentee's name, i have done a set difference from namelist to MartAtt models. Ive managed to save all the changes made in the EditStudent page except fr the name. Namelist models.py: class Namelist(models.Model): name = models.CharField(max_length=100) program = models.CharField(max_length=10) year = models.IntegerField(default=1) studType = models.CharField(max_length=15) courseType = models.CharField(max_length=15) nationality = models.CharField(max_length=20) VMSAcc = models.CharField(max_length=30) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) MarkAtt models.py: class MarkAtt(models.Model): STATUS=[ ('Present', "Present"), ('Absent', "Absent") ] studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=1) attendance = models.IntegerField(default=100) #100 is present status = models.CharField(max_length=10, blank=True, null=True, choices=STATUS, default="Present") remarks = models.CharField(max_length=100, blank=True, null = True, default = " ") My Views.py: def AbsentStudent(request, id=None): start = None end = None w =1 … -
django: Cant open two different pages when I have two views for an application
I am doing django course from udemy, i did one experiment. Below is my folder structure Project appTwo urls.py ProTwo appTwo/urls.py from django.conf.urls import url from appTwo import views urlpatterns = [ url(r'^$',views.help,name='help'), url(r'^$',views.users,name='users'), ] Now when i try to open the page users by http://127.0.0.1:8000/users it opens the page help.html. For http://127.0.0.1:8000/help it opens help page. When I comment the first entry in urlpatterns in urls.py it opens the users page even if i try to open help page. Can anyone please guide me what wrong I am doing or its working as expected. -
Trying to serialize data from multiple models
I am trying to serialize three django models in a section of my api, but it seems he doesn't like the way I do it .. Im following the documentation of https://www.django-rest-framework.org/api-guide/relations/#nested-relationships I have tried to create 3 serializers one for each model and then put everything together in the fields of the last serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['name', 'user'] class UserCompanySerializer(serializers.ModelSerializer): class Meta: model = UserCompany fields = ['name'] class UserInfoSerializer(serializers.ModelSerializer): profile = UserProfileSerializer companys = UserCompanySerializer(many=True) class Meta: model = CustomUser fields = ['email', 'profile', 'companys'] I thought it would work but it returns the error: ImproperlyConfigured at /user_info Field name profile is not valid for model CustomUser. models.py class UserCompany(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(default=False) companys = models.ForeignKey(UserCompany, on_delete=models.CASCADE, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class UserProfile(models.Model): name = models.CharField(max_length=300, unique=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name -
Saving user data and selecting one instance later on
I am working on a project that requires an image gallery for a website that I am making. I have already made the image upload models and uploaded a couple of images to the server media root. However, I am a newbie in django and can't for the life of me figure out the following problem: The admin should be able to upload images into the server. The admin interface must expose a selector that enables a user to select among the uploaded images to be shown on the website. Among the uploaded images, only one can be selected. In short, I need to store configuration settings from user side on the server but allow only one instance. How can I start? -
How to deploy a django web application on a wamp server step by step method creating a virtual ip
I am trying to deploy my simple dummy "hello world" application on django with wamp server.I have followed many solutions on the internet but not able to work through them.I need simple step by step procedure to deploy the application.I am using python3.7.4 and latest version of wamp server on a 64 bit windows 10 machine.I will paste the code if you need to make out if i have made any error. Thanks for the help ! -
Django Creating a App Inside of a App And Load It Inside of Settings
I want to create a app inside of a app and use it but I seem to can't get it to load in settings.py under INSTALLED_APPS but I can't seem to get it to work I tried account.useprofile.apps.UserprofileConfig - django.core.exceptions.ImproperlyConfigured: Cannot import 'userprofile'. Check that 'account.userprofile.apps.UserprofileConfig.name' is correct." account.userprofile.UserprofileConfig account.apps.userprofile.UserprofileConfig I am trying to get the app inside of the account app called userprofile but I can't successfully get it to load under settings.py files: mysite - * django files * account - userprofile -
Cannot query foreign key field in GraphQL
I'm using graphene-django framework for GraphQL. All fields I can retrieve except foreign key // models.py from django.db import models from django.contrib.auth.models import User from users.models import UserProfile class Video(models.Model): title = models.TextField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) // schema.py class VideoType(DjangoObjectType): class Meta: model = Video My query is like this query { home_videos { title description author } } Following is error message in GraphQLView. Cannot query field author on type VideoType -
Errors running django tests after python 2/3 upgrade, unittest.loader._FailedTest
I'm helping my group upgrade their application from python 2 to 3, and am running into errors with the unit tests. When I run the tests with python3 manage.py test groupapp --settings=settings.deploy_dev I get the errors below. But if I run with python3 manage.py test groupapp.tests --settings=settings.deploy_dev the errors do not occur. Its worth noting that these errors occur even after I deleted all our tests from the tests folder, and as far as I can tell they aren't connected to an actual test case. I don't understand the difference between these two calls in python 3. In python 2 if I run the two calls I get the same result (no test failures). groupapp_v2.groupapp.admin (unittest.loader._FailedTest) ... ERROR groupapp_v2.groupapp.models (unittest.loader._FailedTest) ... ERROR ====================================================================== ERROR: groupapp_v2.groupapp.admin (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: groupapp_v2.groupapp.admin Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/Users/matthew/bitbucket/consortium-website/groupapp_v2/groupapp/admin/__init__.py", line 73, in <module> admin.site.register(Grid, GridAdmin) File "/Users/matthew/virtualenv/groupapp-python3.6/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 110, in register raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model Grid is already registered ====================================================================== ERROR: groupapp_v2.groupapp.models (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: groupapp_v2.groupapp.models Traceback (most recent … -
How do I pull a part of an object and pass it through context to ouput to page. Django
Here is my object: [{'address_components': [{'long_name': '900', 'short_name': '900', 'types': ['street_number']}, {'long_name': 'West Wall Street', 'short_name': 'W Wall St', 'types': ['route']}, {'long_name': 'Janesville', 'short_name': 'Janesville', 'types': ['locality', 'political']}, {'long_name': 'Rock County', 'short_name': 'Rock County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Wisconsin', 'short_name': 'WI', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}, {'long_name': '53548', 'short_name': '53548', 'types': ['postal_code']}, {'long_name': '3574', 'short_name': '3574', 'types': ['postal_code_suffix']}], 'formatted_address': '900 W Wall St, Janesville, WI 53548, USA', 'geometry': {'location': {'lat': 42.6803769, 'lng': -89.03211}, 'location_type': 'RANGE_INTERPOLATED', 'viewport': {'northeast': {'lat': 42.6817258802915, 'lng': -89.0307610197085}, 'southwest': {'lat': 42.6790279197085, 'lng': -89.03345898029151}}}, 'place_id': 'Eig5MDAgVyBXYWxsIFN0LCBKYW5lc3ZpbGxlLCBXSSA1MzU0OCwgVVNBIhsSGQoUChIJFzIpc5QZBogRoK3T0RxPudkQhAc', 'types': ['street_address']}] I just need the {'lat': 42.6803769, 'lng': -89.03211} part. Here is my view: def home(request): posts = Listing.objects.all().filter(is_live=1) context = {'posts': posts} return render(request, 'home.html', context) Here is my html: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Set the size of the div element that contains the map */ #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <!--The div element for the map --> <div id="map"></div> <script> // Initialize and add the map function initMap() { var … -
How to safely delete a model field?
I have a field in a model in django. Last time I tried to remove it (and ran migrations), it ended up making everything break. How could I go about properly removing a field in a model? # here's an example model class Sheet(models.Model): model1 = models.IntegerField() model2 = models.IntegerField() model3 = models.IntegerField() # here's the same model with a deleted field (what I want to do) class Sheet(models.Model): model1 = models.IntegerField() model2 = models.IntegerField() -
How to update a value with signals in Django
Im trying to update an attribute with a signal with post_save, but im getting an ExceptionType: TypeError "int() argument must be a string, a bytes-like object or a number, not 'Pedido'", and I dont know what is this error. This is my signal: @receiver(post_save, sender=Venta) def update_thread(sender, **kwargs): instance = kwargs['instance'] obj = Pedido.objects.get(pk=instance.pedido) obj.estado = "Finalizado" ob.save() Also check this: What it can be the error? -
Lookup error on heroku app when trying to use stanford NER
Consumers.py import json import os import nltk nltk.download('popular', quiet=True) import pandas as pd from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from . import tasks from nltk.tag import StanfordNERTagger from itertools import groupby from chat.models import Event #from django.contrib.sessions.backends.db import SessionStore from django.conf import settings from importlib import import_module #from channels.sessions import channel_session os.environ['CLASSPATH'] = 'static/stanford-ner.jar' os.environ['STANFORD_MODELS'] = 'static/ner' java_path = 'static/java.exe' os.environ['JAVAHOME'] = java_path stanford_classifier = 'static/ner/english.all.3class.caseless.distsim.crf.ser.gz' st = StanfordNERTagger(stanford_classifier) The stanford-ner.jar, ner, java.exe, english.all.3class.caseless.distsim.crf.ser.gz are located as coded above in the folder structure, Despite this I am facing error as LookupError: NLTK was unable to find stanford-ner.jar! Set the CLASSPATH environment variable. Kindly help with the issue as the app is failing when trying to deploy on heroku. Thanks in advance -
Django - Suspending/deactivating an account for N amount of seconds
In my Django application, If the user enters the wrong password more than 7 times, then I want to suspend/deactivate their account for 10 seconds. I perform an If statement to see if the wrong password has been inputted more than 7 times, and that works fine. Inside the if statement, I want to set user.is_active to False so they cannot login for 10 seconds. After 10 seconds has passed, I want user.is_active to be set back to True so they can attempt to login again. How would I implement this functionality? Thank you.