Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError while importing a class from different app
In my django project LibraryManagement I have two apps 'book' and 'authors'. I am trying to establish relationship between two apps using foreign key. While I try to import class Authors in the book I got error ModuleNotFound:No module named 'LibraryManagement.authors' Below is my project structure LMS -LibraryManagement -authors -book -LibraryManagement -venv Code of models.py from authors app from django.db import models class Authors(models.Model): author_name = models.CharField(max_length=100) description = models.TextField(max_length=300) Code of models.py from book app from django.db import models from LibraryManagement.authors.models import Authors class Book(models.Model): book_name = models.CharField(max_length=100) author = models.ForeignKey(Authors) remarks = models.TextField(max_length=300) -
Default HyperlinkedModelSerializer not finding the endpoints
I am trying to simply change my ModelSerializer to HyperlinkedModelSerializer to include the url to each of the objects listed in the ListView of the default Browsable API. According to the docs, since I am using default 'pk' for the lookup, I just change the class I inherit the serializer from: # class SeasonSerializer(serializers.ModelSerializer): class SeasonSerializer(serializers.HyperlinkedModelSerializer): # url = serializers.HyperlinkedIdentityField( # view_name='season', lookup_field='pk') ---> Not needed according to docs but have also tried with this class Meta: model = Season fields = ('id', 'url', 'years', 'active') And add the context when instantiating it in the view: class SeasonListView(APIView): def get(self, request, *args, **kwargs): queryset = Season.objects.all().order_by('years') serializer = SeasonSerializer( queryset, many=True, context={'request': request}) print('INFO: ', serializer) permission_classes = [ ] authentication_classes = [ ] return Response({"Seasons": serializer.data}) class SeasonDetailView(APIView): def get(self, request, *args, **kwargs): pk = kwargs['pk'] season = get_object_or_404(Season, pk=pk) serializer = SeasonSerializer(season, context={'request': request}) # print('Data: ', serializer.data) --> this breaks return Response(serializer.data) And my endpoints are the same as when using ModelSerializer: urlpatterns = [ path(r'seasons/', SeasonListView.as_view(), name='season-list'), path(r'seasons/<int:pk>/', SeasonDetailView.as_view(), name='season-detail'), ] The error is the following: For http://localhost:8000/api/seasons/1/ Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "season-detail". You may … -
How to ensure all custom values from settings.py are avaibalable in Django project?
I defined a few custom values in my Django project "settings.py" file. I need to load those values into my views ans other project files, but not all values defined in settings.py seem to be available. settings.py # My custom settings API_URL = 'http://10.0.0.1' EMAIL_DEFAULT_RECIPIENT = 'foo@bar.tld' I load the whole settings.py file content using the following in my view: views.py my_view(request,foo_id): from django.conf import settings as project_settings # First log output logger.debug('API_URL: ' + project_settings.API_URL) # Second log output logger.debug('EMAIL_DEFAULT_RECIPIENT: ' + project_settings.EMAIL_DEFAULT_RECIPIENT) The first log output (API_URL value) is correct: [2020-00-00 00:00:00 +0000] [16381] [DEBUG] (my_app.views) API_URL : http://10.0.0.1 Strangely the second log output (EMAIL_DEFAULT_RECIPIENT value) throws an exception: AttributeError: 'Settings' object has no attribute 'EMAIL_DEFAULT_RECIPIENT' Django project layout my_project ├── my_app │ ├── migrations │ ├── __pycache__ │ └── templates ├── my_project │ ├── __pycache__ │ ├── static │ └── templates ├── __pycache__ └── venv ├── bin ├── include ├── lib └── lib64 -> lib My Django project is served through NGINX/Gunicorn started by a systemd service unit within a venv. It worth mentionning that I restarted this service after changing settings.py content. I also cleared __pycache__ project directory content manually but this has no effect on … -
Get group name of the user in Django keycloak
I am using keycloak and django for authentication of users via django-keycloak package. I want to get the group name of a user belonging to in keycloak in django. Also I am new to keycloak authorization service -
Axios post request with nested object
I need help with axios post with multiple student objects in one single class. Class form has various fields with an option to add dynamically multiple students. Add only student names for the objects but be able to edit the student details to give full details.Backend is Django. { "students": [ { "stud_fname": "First Name", "inter_lname": "Last Name", "class_section": "class", }, { "stud_fname": "First dsfdsfName", "inter_lname": "Last sdfName", "class_section": "cladsfdfss", } ], "ClassName": "eqwe", "TeacherName": "eqw", "SchoolNAme": "eqw", } -
Setting up router with APIView and viewset in Django Rest Framework
It's my first question on Stackoverflow ! I'm new to Django and following some tutorials. I'm trying to understand if there is a way to set up the routing of an API from different view classes like APIView and viewsets.ModelViewSet (please tell me if I do not use the good wording) In views I have : from rest_framework import viewsets from post.models import UniquePost from .serializers import UniquePostSerializers from rest_framework.views import APIView class UniquePostViewSet(viewsets.ModelViewSet): serializer_class = UniquePostSerializers queryset = UniquePost.objects.all() class FileUploadView(APIView): some code here but no queryset nor serialized data...and no model In urls I have : from post.api.views import UniquePostViewSet from django.urls import path, include from rest_framework.routers import DefaultRouter from post.api.views import FileUploadView router = DefaultRouter() router.register('UniquePost', UniquePostViewSet, base_name='uniquepostitem') router.register('demo', FileUploadView, base_name='file-upload-demo') urlpatterns = router.urls But it seems that I can register FileUploadView this way. Because I don't have a queryset to render. I have : AttributeError: type object 'FileUploadView' has no attribute 'get_extra_actions' I realized that (well I think) that I can use APIView for FileUploadView (and add ".as_view()) but I think I have to rewrite UniquePostViewSet using APIView as well and defining exactly what I want to see in details like POST, PUT etc... My question … -
How do I build a voice message app in Django? I am a beginner in Django and only know the basics. Where do I start?
I want to buid a voice message app, plan to build on Django, but I am a beginner in Django, how do I start the project? Django is suitable for this project? -
How do I fetch the row associated with the currently logged in user in django and display specific fields in template?
I have a table account that is tied up to the User model by a One to One relationship in django, this account table is meant to store additional information related to the users in the User model. I want to fetch the row in account table of the current user that is logged in/active and display specific data of the user like "designation" or "ac_type" in my template. models.py class account(models.Model): username=models.ForeignKey(User, on_delete=models.CASCADE) first_name=models.CharField(max_length=100) ac_type=models.CharField(max_length=100) designation=models.CharField(max_length=100) drone_id=models.ForeignKey(asset,null= True, on_delete=models.CASCADE) def __str__(self): return self.first_name views.py def dashboard(request): as_data = asset.objects.filter(status=True) #where context = {'as_data':as_data} return render (request, 'dashboard.html',context) def dash_2(self): u=self.request.user ac_data = account.objects.filter(id__in=u).values() context2 = {'ac_data':ac_data} return render (self, 'dashboard.html',context2) dashboard.html <html> <body> My designation is: <br> <p>{{ac_data.designation}}</p> </body> </html> I am a newbie in django so any help would be really helpful. Thanks in advance ! -
Django search form, disambiguation page
Hello everybody I keep having this problem with my search form in my website. The thing is that, based on the user input, i check if in the database there're some results. But if the input is both in band column and album colum I'd like the user to be redirected to a 'disambiguation' html page. This is my views.py but it doesn't work. Hope someone could help me, thanks! Views.py class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch)) sd = Info.objects.filter(Q(disco__icontains=srch)) if sr is sd: return render(self.request, 'search/disambigua.html') else: paginator = Paginator(sr, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sr':sr, 'sd': sd, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') -
the value inside the class modal-body is showing only the first object of the Django model 'hostels'
the value inside the class modal-body is showing only the first object of the Django model 'hostels' , but when 'edit' in this code is replaced with {{hostel.hostel_name}} its working fine. what's the issue {% for hostel in hostels %} <div class="container" style="width: 48%;margin: 10px;height: 140px;background-color: white;display: inline-block;position: relative;"> <a href="{{hostel.pk}}/deletehostel/" style="color: white;position: absolute;top: 0px;right: 0px;margin: 0px;padding: 0px;padding-right: 5px;padding-left: 5px;background-color: red"> X </a> <a href="{{hostel.pk}}" style="text-decoration: none"> <h1 style="text-align: center;">{{hostel.hostel_name}}</h1> <p style="text-align: center;">total beds: {{hostel.capacity}}</p> </a> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter" style="display: block;margin: auto">edit</button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Edit details here</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <input type="text" class="form-control" value="{{hostel.hostel_name}}" name="" placeholder="hostel name"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %} -
How to write a query to get the number of times a choice is selected by users
I want to count the number of times a choice is selected by users. Here is my model models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from multiselectfield import MultiSelectField class MedicalHistory(models.Model): Anxiety = 'Anxiety' Arthritis = 'Arthritis' Asthma = 'Asthma' Anemia = 'Anemia' Cancer = 'Cancer' Corona_virus = 'Corona_virus' Diabetes = 'Diabetes' Ebola = 'Ebola' HIV = 'HIV' ILLNESS_CHOICES = ( (Anxiety, "Anxiety"), (Arthritis, "Arthritis"), (Asthma, "Asthma"), (Anemia, "Anemia"), (Cancer, "Cancer"), (Corona_virus, "Corona_virus"), (Diabetes, "Diabetes"), (Ebola, "Ebola"), (HIV, "HIV"), ) user = models.ForeignKey(User, on_delete=models.CASCADE) illness = MultiSelectField(choices=ILLNESS_CHOICES, max_length=50) symptoms = models.CharField(max_length=100) additional_info = models.CharField(max_length=100) disability = models.BooleanField(default=False) medications = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Medical History' Here I have a number of illnesses I want users to select from. A user can select more tan one illness. I want each illness to have a count, and every time the illness is selected it adds to the count. In my view I have views.py def pie_chart(request): labels = [] data = [] queryset = MedicalHistory.objects.values('illness').annotate(count=Sum('user')).order_by('-count') for entry in queryset: labels.append(entry['illness']) data.append(entry['count']) return JsonResponse(data={ 'labels': labels, 'data': data, }) <QuerySet [{'illness': ['Asthma', 'Diabetes', 'Ebola'], 'count': 3}, {'illness': ['Anemia', 'Covid-19'], 'count': 2}]> The query … -
Django setup elasticsearch client with password auth
My Django application uses elasticsearch to index several ressources. Now I wanted to protect my elasticsearch instance with as password wich is working fine if I use "curl -u" or so. Anyways from the elasticsearch_dsl documentation, found here: https://elasticsearch-dsl.readthedocs.io/en/latest/configuration.html I do not understand what I have to do in order to setup elasticsearch that way that it uses a password for authentication and where do I have to place this code?! Is smb. maybe able to pass show me some snippets of his configuration? My current state looks like this: settingy.py ELASTICSEARCH_DSL = { 'default': { 'hosts': env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT'), }, } ELASTICSEARCH_DSL_SIGNAL_PROCESSOR = 'django_elasticsearch_dsl.signals.RealTimeSignalProcessor' documents.py from django_elasticsearch_dsl import Document, Index, fields from elasticsearch_dsl import analyzer from App.models import Post # elasticsearch index posts = Index('posts') html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @posts.document class PostDocument(Document): ... more index stuff According to the docs I have to manually setup a default client connection where I can also pass the password and username for authentication wich to me seems not to be possible at settings.py at moment. Kind regards -
image is not showing in django templates am new in django and working on a project...i idid lots of rid of this error but nothing happen
am trying to show pic in django tempate but its not working here is my settings.py where the path of static and media file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR , "media") this is my model.py the image is store under static/img folder class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) this is my html template for showing user posted data {% extends "post.html" %} {% block content %} {% load static %} {% for loader in Loader %} <h4>Loader Id- {{loader.id}}</h4> Username-{{user.username}} <h3>Sender name-{{loader.sender_name}}</h3> </h4> <p class="card-text"> <h4>pick up station-{{loader.pick_up_station}}</h4> </p> <img src="{{ loader.image.url }}" alt="image"> <p class="card-text">{{loader.destination_station}}</p> <p class="card-text">{{loader.phone_number}}</p> <p class="card-text">{{loader.receiver_name}}</p> <p class="card-text">{{loader.sending_item}}</p> <p class="card-text">{{loader.weight}}</p> <p class="card-text">{{loader.quantity}}</p> <p class="card-text">{{loader.pick_up_time}}</p> <p class="card-text">{{loader.drop_time}}</p> <p class="card-text">{{loader.paid_by}}</p> <p class="card-text">{{loader.created_at}}</p> <a class="btn btn-primary" href="{% url 'Loader:Delete' loader.id %} ">delete</a> <a class="btn btn-primary" href="{% url 'Loader:Update' loader.id %} ">update</a> </div> {% endfor %} {% endblock content %} … -
WebSocket connection to <heroku-app>' failed: Error during WebSocket handshake: Unexpected response code: 500
I deployed django-channels project on heroku. The project works fine locally but on heroku it doesn't function, i-e no websocket connection is established. my consumers.py is: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'quiz_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) my routing.py is: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import quiz_app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( quiz_app.routing.websocket_urlpatterns ) ), }) my Procfile is : web: daphne quizbackend.asgi:application --port $PORT --bind 0.0.0.0 -v2 And I am using in-memory layer for testing purpose, which is : CHANNEL_LAYERS={ "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } also my heroku logs --tail are : 2020-04-09T11:16:08.616718+00:00 app[web.1]: ^ 2020-04-09T11:16:08.616718+00:00 app[web.1]: 2020-04-09T11:16:08.616903+00:00 app[web.1]: 2020-04-09 11:16:08,616 INFO failing WebSocket opening … -
Django CSRF Token is not getting set
So i am using VueJS and Django. Axios to make a get request. When i try to retrieve the CSRF token and log it, it shows me it is null. here is my serializer: class VehicleSerializer(serializers.ModelSerializer): seller = serializers.SerializerMethodField() class Meta: model = Vehicle fields = ('vehicle_id', 'color', 'model', 'year', 'category', 'manufacturer', 'seller') def get_seller(self, instance): return instance.seller.customer.username My Viewset: class VehicleListCreateAPIView(ListCreateAPIView): serializer_class = VehicleSerializer permission_classes = [IsAuthenticated] queryset = Vehicle.objects.all() def perform_create(self, serializer): request_user = self.request.user try: seller = Seller.objects.get(customer = request_user) except Seller.DoesNotExist: seller = Seller.objects.create(customer = request_user) serializer.save(seller = seller) My urlpattern: path('vehicles/', VehicleListCreateAPIView.as_view()), The code from django documentation to retrieve a token: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); export { csrftoken }; -
Django admin page and CSS
I'm very new to django. I just did the very basic step for creating a project which has one application. I started the server using python manage.py runserver which ended up giving me my home page. but when I opened the admin page it was not with proper CSS as it is supposed to be. I went through some solutions like adding the following code so that my static files are added correctly. STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' But this doesn't reflect anything after running python manage.py collectstatic. Do I need something else to done further? This is the settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(9szxe#x0q67)^wc6us01*i$=1)!&f7)530%73=pvzzhwp23gp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { … -
attempt to write a readonly database - Django app deployed on App Engine (SQLite3 DB)
I have hosted Django app using App Engine standard environment. When I try to login, it gives me 'attempt to write a readonly database' error . I have added URL to ALLOWED HOSTS and added in admin credentials in DATABASE in settings.py. Everything else works as intended. app.yaml # [START django_app] runtime: python37 service: hellotest1 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # [END django_app] settings.py - DATABASES and ALLOWED_HOSTS ALLOWED_HOSTS = ['url'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'admin', 'PASSWORD': 'admin', } } -
Django IIS Active Directory Single Sign On (SSO)
I have application written in Django, hosted with IIS on my intranet with Active Directory. Following this stackoverflow topic https://stackoverflow.com/a/26987622/4992056 I managed to create basic domain authentication. Unfortunately this solution reqiures login with domain account credentials everytime I rerun browser what is not ideal user experience and brings security issues (browser prompts user to save their domain account credentials). I would like to have true single sign-on feature that means: when user is signing in with his domain account, he/she should also be signed in to the web app without prompting for password. Thanks in advice for your answers. Best regards, Wojtek -
IntegrityError in database stored vlaues in django?
''' My problem is database values can't stored properly In below I uploded views functions file,model file as an images. so in model there are three fields but database stored only image stored and other vlaues strored by default get null values so can you help to solving my problem.. ''' userproblem.html <form method="POST" action="/uploadoc/" enctype="multipart/form-data" data-toggle="validator"> {% csrf_token %} <div id="progressbarwizard"> <ul class="nav nav-pills bg-light nav-justified form-wizard-header mb-3"> <li class="nav-item"> <a href="#account-2" data-toggle="tab" class="nav-link rounded-0 pt-2 pb-2"> <i class="mdi mdi-account-circle mr-1"></i> <span class="d-none d-sm-inline">Query Form</span> </a> </li> </ul> <div class="tab-content b-0 mb-0"> <div class="tab-pane" id="account-2"> <div class="row"> <div class="col-md-5"> <label class="col-md-12 col-form-label">Query Types: <span class="text-danger">*</span></label> <div class="col-md-8"> <input type="text" class="form-control" data-validate="true" name="queryn" placeholder="Enter Query Types"> </div> </div> <div class="col-md-5"> <label class="col-md-12 col-form-label">Description of Query: <span class="text-danger">*</span></label> <div class="col-md-12"> <textarea type="text" class="form-control" data-validate="true" name="querydec" placeholder="Description of Query"></textarea> </div> </div> </div><!-- /.First row end --><br> <div class="row"> <div class="col-md-5"> <label for="Emailadrress" class="col-md-12 col-form-label">Upload Your File: <span class="text-danger"></span></label> <div class="col-md-12"> <div class="input-group-append"> <input type="file" id="img" name="img" accept="image/*"> </div> </div> </div> <div class="col-md-6"> <label for="Emailadrress" class="col-md-12 col-form-label">Solutions: <span class="text-danger"></span></label> <div class="col-md-12"> <div class="input-group-append"> <textarea type="text" name="querysol" placeholder="Solutions of Query"></textarea> </div> </div> </div> </div> <!-- /.second row end --> </div><br> <div class="row"> <div class="col-12"> … -
How to run a function witth (request) every hour?
i have function: def coins_costs_load(request): response = requests.get( 'https://explorer-api.minter.network/api/v1/coins').json()['data'] for coin in response: coin_crr = coin['crr'] coin_id = coin['symbol'] obj = CoinCosts.objects.create( crr=coin_crr, coin_id_id=coin_id) obj.save() It works great and everything is fine. But how to automatically run a function every hour? I tried all the methods, and the shedule plugin, and the built-in tools. They do not work with the request argument. Gives an error message. And if you remove the argument, also an error... Please help! Thanks! -
Django ModelForm save to another database
I have a set up with multiple databases: let's call them db1, db2 and db3. db1 is default. I now have a ModelForm that is meant to save an object Customer to db2. class CustomerCreateForm(ModelForm): class Meta: model = Customer fields = ["name", "type"] My view: if "create" in request.POST: f = CustomerCreateForm(data=request.POST) customer = f.save(commit=False) # Error -> no table 'customer' on database 'db1' customer.date_joined = datetime.now() customer.save(using='db2') It appears that the save() method does not have a using argument. How can I save an instance of Customer to db2? -
saving to django models using ajax
I am trying to save a users data into the database. Iam trying to get one input from the user that is the answer, then I want to get the question that has been assigned to the user that is the First_question variable. I tried to track if the selected_answer and assigned_question has been parsed to the view and it did. but then I get an error: NOT NULL constraint failed: study_answer.question_id [246, None, None, 30.0, '2020-04-09 13:53:36.008824', '2020-04-09 13:53:36.008849'] self sql ('INSERT INTO "study_answer" ("participant_id", "question_id", "answer", ' '"completion_time", "created_at", "updated_at") VALUES (%s, %s, %s, %s, %s, ' '%s)') from my understanding it seems that both question_id and answer_id are not being able to be parsed. although when I printed them I got the answer as in text and the question id. views.py participant = get_object_or_404(Participant, user=request.user) selected_choice = request.POST.get('selected_choice') assigned_question = request.POST.get('assigned_question') completion_time = 30 answer = Answer(participant=participant, question=assigned_question, answer=selected_choice, completion_time=completion_time) answer.save() template.html <p name="question" id="{{First_question.id}}"> {{First_question}} </p> {% for i in all_choices %} <input type="radio" id="{{ i.id }}" name="choice" value="{{ i.choice_text }}"> <label for="{{ i.id }}">{{ i.choice_text }}</label> {% endfor %} <button type="button" id="Submitbutton" class="btn btn-primary" onclick=Nextquestion() >Next</button> </div> <script> function Nextquestion(){ selected_choice = $("input[type='radio'][name='choice']:checked").val(); assigned_question = … -
how to Convert ruby on rails code to Django?
i want convent this code from ruby on rails to django just example class HomeController < ApplicationController include BusinessPlans include CreditRepairPlan include FinancePlan skip_before_action :verify_authenticity_token, only: [:get_plan,:get_credit_repair_plan, :get_finance_plan] before_action :authenticate_user! def index end def upgrade end -
Matching database columns in the filtering in Django
I'd like to match database columns in the query. How is this possible? For example select * from docs where mlal_id_no=8 AND column1= column2 qs = docs.objects.filter(mlal_id_no=8,column1=column2) -
Can't use django 2.2 with django-oscar-wagtail for wagtail cms
I am using: django 2.2 django-oscar 2.0.4 I can't use wagtail<2.6 since I am using django 2.2( django2.2 support is with wagtail 2.6 ). And django-oscar-wagtail require wagtail <2.4. Can you give me some ideas to use wagtail with django-oscar?