Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to install sqlite on MAC for python project
I am trying to install sqlite browser on my MAC.Its installed successfully but after I am opening it ,MAC gives me error " “DB Browser for SQLite” can’t be opened because Apple cannot check it for malicious software. This software needs to be updated. Contact the developer for more information. I am downloading from sqlitebrowser.org website.But still failed.I checked different YouTube videos for MAC version but didn't help.Its little urgent for my Python Project. when I checked on terminal for Sqlite version then it gives me 3.28.0 -
Django Date/Time Enter a Valid Date/Time Form validation
When submitting a form I keep getting Enter a valid date/time The code forms.py class LessonsForm(forms.ModelForm): class Meta: model = models.Lessons # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_of_lesson': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), 'end_of_lesson': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = '__all__' def __init__(self, *args, **kwargs): super(LessonsForm, self).__init__(*args, **kwargs) # input_formats to parse HTML5 datetime-local input to datetime field self.fields['start_of_lesson'].input_formats = ['%Y-%m-%dT%H:%M'] self.fields['end_of_lesson'].input_formats = ['%Y-%m-%dT%H:%M'] settings.py DATE_INPUT_FORMATS = ["%d/%m/%Y", "%d-%m-%Y", '%Y-%m-%d', '%Y/%m/%d', '%Y-%m-%dT%H:%M', '%Y/%m/%dT%H:%M', '%d-%m-%Y %H:%M', '%d/%m/%Y %H:%M', '%d/%m/%YT%H:%M', '%d-%m-%YT%H:%M',] DATE_FORMAT = "d/m/Y" DATETIME_FORMAT = "d/m/Y H:i" TIME_FORMAT = "H:M" I feel like I have messed around with the input formats everywhere and changed them to everything but it just won't validate when I save the form start_of_lesson = forms.DateTimeField(input_formats = ['%d/%m/%Y'], widget=forms.DateTimeInput(attrs={'class':'form-control form-control-lg','type':'datetime-local'})) Is an example of something I have tried. -
ElasticSearch Suggester full-text-search
I'm using django_elasticsearch_dsl. My Document: html_strip = analyzer( 'html_strip', tokenizer='standard', filter=["lowercase", "stop", "snowball"], char_filter=["html_strip"] ) class Document(django_elasticsearch_dsl.Document): name = TextField( analyzer=html_strip, fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), } ) ... My request: _search = Document.search().suggest("suggestions", text=query, term={'field': 'name.suggest'}).execute() I have the following document "names" indexed: "This is a test" "this is my test" "this test" "Test this" Now if search for This is my text if will receive only "this is my text" However, if I search for test, then all I get is "Test this" Even though I want all documents, that have test in their name. What am I missing? -
Knowing when's best to use Wagtail Pages or Django Models for Wagtail website
I am making a website running wagtail as the CMS/backend and use Page for things that are actual web pages on the site. In addition to this I will need an Events section and I am unsure whether to make it as a Wagtail Page or Django models.Model. The way I would like this to work for the user is to have an Events section in the admin panel using ModelAdmin so that the user can easily find and navigate to all Events, and, for those events to be displayed in various sections of the site - Home Page, Events Page, Article Page for example. I think using Page for this and requiring the user to navigate to it (Home > Events Listing > Event Detail) each time is rather a waste of time and cumbersome as opposed to having it use ModelAdmin paired with Django models.Model and that being 1 or 2 clicks away. Reading through my question it's obvious I am leaning towards using Django model for this, so my question is: what is the trade-off between the two? Is there a set use case for using one or the other? Would using one mean having more/less functionality … -
Pass variable which consists the name of the function to call, onclick="location.href='{% url '{{var}} ' %}'"?
I am trying to built a Port Scanner website on django. Problem Statement: What I need is the User will be selecting anyone of the radio button (full Scan or Quick Scan) and after that when the user click on Start Now button, that python function should be called from urls.py of views.py which the radio button holds the value of. I saw on the internet that functions of views.py can be called using onclick="location.href='{% url ' radio value variable ' %}'" from the templates but nothing passing radiobuttons value at url ' ' base.html <form id="suggestion_form" name="gs" method="get" action="home"> <div class="searchText"> <input type="text" name="q" class="searchText" placeholder="{% block title %} {% endblock %}" readonly="readonly"> <ul> <li><label><input type="radio" name="ext_com" value="Full Scan"><span>Full Scan</span></label></li> <li><label><input type="radio" name="ext_com" value="Quick Scan"><span>Quick Scan</span></label></li> </ul> </div> <input type="submit" name="results" class="main-button" value=" Start Now " onclick="location.href='{% url ' radio value variable ' %}'"> </form> urls.py from django.conf.urls import url from . import views urlpatterns = [ url('',views.home), url('',views.fullscan,name="fullscan"), url('',views.quickscan,name="quickscan"), ] views.py ..... def fullscan(): If fullscan radio button is selected then this should be called an output will be rendered def quickscan(): If quickscan radio button is selected then this should be called an output will be rendered -
updating a model with respect to a field django
I m doing a bet app and if the admin verify the screenshot sent by the won he will set the verified field to be true . this is how both the models look like : class ScreenshotVerification(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="screenshot") user_accepted_bet =models.ForeignKey(AcceptBet,on_delete=models.CASCADE,related_name='screenshotPost') user_bet =models.ForeignKey(CreateBet,on_delete=models.CASCADE,related_name='screenshotBet') screenshot_img = models.ImageField(upload_to = 'media/screenshot',blank = True) created_at = models.DateTimeField(auto_now=True) verified = models.BooleanField(default=None) class Won(models.Model): won_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="won_user") loss_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="loss_user") created_time = models.DateTimeField(auto_now=True) so whenever verified field set to true I want the value of won_user and loss_user to be automatically be created thanq in advance . -
Can I run a django view function automatically?
Is this possible to run a django view function automatically daily after deploying it on heroku.? I mean.. I have a database where I have datefield. I have a view function, which matches that date with today's date and sends an email. Is it possible..that view function runs daily automatically and matches the dates and does the task.?? -
how to action djago button
I am developing to provide face recognition automatic door service in django by receiving images from a raspberry camera to a computer. I want to capture the screen displayed in django when I click the button in the picture below, but I don't know how to write view.py. Help me.. enter image description here this is picamera code import socket import cv2, os, urllib.request import numpy as np from django.conf import settings #from django.apps import AppConfig face_detector = cv2.CascadeClassifier(r'C:\Users\Desktop\University\last\django\face_project\picamera\haarcascade_frontalface_default.xml') global frame, gray #socket에서 수신한 버퍼를 반환하는 함수 def recvall(sock, count): # 바이트 문자열 buf = b'' while count: newbuf = sock.recv(count) if not newbuf: return None buf += newbuf count -= len(newbuf) return buf class streaming_pi_camera(object): def __init__(self): HOST='my_ip' PORT=8485 #TCP 사용 global s s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #서버의 아이피와 포트번호 지정 s.bind((HOST,PORT)) # 클라이언트의 접속을 기다린다. (클라이언트 연결을 10개까지 받는다) s.listen(10) print('Socket Ready') #연결, conn에는 소켓 객체, addr은 소켓에 바인드 된 주소 global conn conn,addr=s.accept() def __del__(self): conn.close() s.close() cv2.destroyAllWindows() def get_frame(self): while True: # client에서 받은 stringData의 크기 (==(str(len(stringData))).encode().ljust(16)) length = recvall(conn, 16) stringData = recvall(conn, int(length)) #data = np.fromstring(stringData, dtype = 'uint8') frame = cv2.imdecode(np.fromstring(stringData, dtype=np.uint8),cv2.IMREAD_COLOR) #face detector and label gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces_detected = face_detector.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for … -
I'm having a program when I'm trying to run my server it's a pretty simple server because I'm quite new with Django
This is the error I get: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I tried removing the include() function but I still get the error, what should I do? Here is the code: This is the main urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('learning_logs.urls', namespace='learning_logs')), This is the secondary: from django.conf.urls import url from . import views urlpatterns = [ # Home page url(r'^$', views.index, name='index'), ] -
NameError : name 'xxx' is not defined in plotly_dash
I am new to programming and still learning the basics of it. I am building a dashboard using plotly dash and I get error as "NameError: name 'plot_data_raw' is not defined" Below is the code: Preprocessing.py (file) def import_agg(days=100): ... ... return dff def import_pda(days=100): ... ... return dff def filter_clearcoat(dff_agg, dff_pda): ... ... return dff_agg def moving_average(dff, cols, dt=30, wsize=9, iqr=90): ... ... return dff def main(days_data=5, days_mean=30, features=['d_50', 'N']): df_agg = import_agg(days_mean) df_agg = df_agg.rename(columns={'LocalTS': 'Timestamp'}) df_agg['Timestamp'] = [x[:19] for x in df_agg['Timestamp']] df_agg['Timestamp'] = df_agg['Timestamp'].apply(pd.Timestamp) # --- import pda: ----------------------------------------------------------------------- df_pda = import_pda(days_mean) df_pda = df_pda.rename(columns={'ZeitErw': 'Timestamp'}) # --- filter droplet number: ------------------------------------------------------------ df_agg = df_agg.loc[df_agg['N']!=0] # --- filter clearcoat type: ------------------------------------------------------------ df_agg = filter_clearcoat(df_agg, df_pda) # --- smoothe: -------------------------------------------------------------------------- df_agg_sm = moving_average(df_agg, features) # --- prepare output (plot data): ------------------------------------------------------- is_in_range = df_agg['Timestamp'] >= (pd.Timestamp.now()-pd.Timedelta(days_data, 'days')) plot_data_raw = df_agg.loc[is_in_range, ['Timestamp']+features].copy() plot_data_smoothed = df_agg_sm.loc[is_in_range, ['Timestamp']+features].copy() # --- prepare output (percentiles & mean): ---------------------------------------------- plot_parameters = pd.DataFrame(columns=features) plot_parameters.loc['pct75'] = [df_agg[x].quantile(q=0.75) for x in features] plot_parameters.loc['mean'] = [df_agg[x].mean() for x in features] plot_parameters.loc['pct25'] = [df_agg[x].quantile(q=0.25) for x in features] # --- output: --------------------------------------------------------------------------- return plot_data_raw, plot_data_smoothed, plot_parameters I want to plot this data on a graph from another file. … -
How to filter a queryset in django by excluding with two parameters
I have a view in django that looks as follows: class ExploreListingView(generics.ListAPIView): serializer_class = ListingSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Listing.objects.exclude(user=self.request.user, claimed=True) The result I expect is to filter out any listings that are assigned with the current user and are claimed, however the filter doesn't work, but when I remove either parameter it works just fine. How do I exclude it so I can use more than one parameter. -
How can i call the fields of a foreignkey in the template html django
how can i call the movie_details and actor fields or variables from the MovieDetail class in the model.py to my html template. Thank you very much i am new to django will be loving solutions from here. Models.py from django.db import models from datetime import datetime # Create your models here. class MoviePosters(models.Model): image = models.ImageField(upload_to = "pics") Title = models.CharField(max_length=50) Description = models.CharField(max_length = 150) class MovieSection(models.Model): image_side = models.ImageField(upload_to = "pics") title_side = models.CharField(max_length=50) movie_link = models.CharField(max_length=20) class meta: verbose_name_plural = "Section" def __str__(self): return self.title_side class MovieDetails(models.Model): movie_section = models.ForeignKey(MovieSection, on_delete= models.CASCADE) movie_details = models.CharField(max_length= 200) actors = models.CharField(max_length= 200) class meta: verbose_name_plural = "movie_details" def __str__(self): return self.movie_details Views.py from django.shortcuts import render from django.http import Http404 from django.http import HttpResponse from .models import MoviePosters, MovieSection,Ticket, MovieDetails def single_link(request, single_link): movie_details = MovieSection.objects.get(pk=single_link) return render(request, "reviewmovie.html", {"part_ones": movie_details}) -
TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'
Can anyone help me with this error. I got this error when I was adding new app in my project and tried to run python manage.py makemigrations After that when I couldn't solve it then I decided to start from 0. I deleted all migration file from all apps except init.py Then created a new postgresql server. but when I run python manage.py makemigrations This error is still there. (backend-T2FJqQ31) C:\Users\Rahul\Desktop\reactblog\backend>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\management \__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\noob\.virtualenvs\backend-T2FJqQ31\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
Add csv data uploaded from user file to django models
Sorry if it's a silly question, but I can't find a simple/up-to-date way of populating Django models from a .csv file updated on the frontend (React) by the user. I manage to send the uploaded file from react frontend to the backend using axios, I can catch the file on the backend, but I dont know the proper way to populate the model with the csv data... Thanks!! App.js // frontend/src/App.js import React, { Component } from "react"; import axios from "axios"; import { Button, FormGroup, Form } from "react-bootstrap"; class App extends Component { handleFile = (event) => { event.preventDefault(); const fileToUpload = event.target.files[0]; this.setState({ fileToUpload: fileToUpload, }); }; handleSubmitData = (event) => { event.preventDefault(); let formData = new FormData(); formData.append("file", this.state.fileToUpload); axios .post("data/", formData) .then((response) => { console.log(response); }) .catch((error) => { console.log(error.response); }); }; render() { return ( <main className="content"> <h1 className="text-white text-uppercase text-center my-4"> Price comparison </h1> <form onSubmit={this.handleSubmitData}> <FormGroup> <Form.Label>Upload file</Form.Label> <Form.Control type="file" onChange={this.handleFile}></Form.Control> </FormGroup> <Button block bssize="large" type="submit"> Submit </Button> </form> </main> ); } } export default App; models.py from django.db import models class Data(models.Model): city = models.CharField(max_length=200, null=True) wheel_type = models.CharField(max_length=200, null=True) order_status = models.CharField(max_length=200, null=True) order_ID = models.IntegerField(null=True) client_ID = models.IntegerField(null=True) placed_time … -
Django, smart-select, chained select doesn-t work from html
I try to use chained select (smart-select), it works from the admin panel, but doesn't work from template (html). settings: JQUERY_URL = False USE_JQUERY_DJANGO = True html: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{% block title%}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css'%}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> <script src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> </head> class Tasks(models.Model): type = models.ForeignKey(TypeServices,on_delete=models.CASCADE,default='0') site = ChainedForeignKey( Services, chained_field="type", chained_model_field="type", show_all=False, sort=True) -
Django deployment with required temporary model data
First of all, I am very new to deployment. I have built a new newspaper project using Django in my windows machine. It runs fine in localhost. Now I want to deploy it in pythonanywhere. I am using the default db.sqlite3 as my database. But in production, I am going to use MySql, (for which they have easy settings and support) Problem: As a newspaper, my website needs a lot of specialized filtering. To find a single value I had to, sometimes, use list indexing on filtered data like-(inside get context data): context['main_lead_news']=SingleNews.objects.filter( published_date__lte=timezone.now(), news_extras__icontains='main_lead_news').order_by('-published_date')[0] As you can see if 'filter' does not find anything, it will raise an error as- List index out of range. Overall, my code will break without any temporary model data( currently, though most of them are lorem ipsum.) I have populated them before my code was complete. now, how can I deploy my project, as I may not have a chance to populate them online again because of those errors.also my debug will be false, it will be near impossible to run my code without finding errors! I have two (half!) ideas- 1.somehow upload the sqlite3 database when deploying, then after configuring MySQL, transfer … -
Django use only one column of Model1 as a foreign key in second model
I have two Django Models (Events and GMSEvents). I want to use the eventAcronym of Events model as a foreign key in GMSEvents. I tried as below, but I get the error AssertionError: ForeignKey(<django.db.models.query_utils.DeferredAttribute object at 0x000002032DA1E8C8>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' Models class Events(models.Model): eventAcronym = models.CharField(max_length=4, blank=False, null=False) eventName = models.CharField(max_length=30, blank=False, null=False) def __str__(self): return f"{self.eventAcronym} - {self.eventName}" class GMSEvents(models.Model): gateNo = models.IntegerField(blank=False, null=False) aircraftName = models.CharField(max_length=15, blank=False, null=False) detectEvent = models.ForeignKey(Events.eventAcronym, on_delete=models.CASCADE) timeStamp = models.DateTimeField() -
How to add Token to a model that extends the User Model in Django Rest Framework?
I have the following to create a user and add a Token to it: User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email') extra_kwargs = {'passwords': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) token = Token.objects.create(user=user) return user I would like to be able to do the same thing for a Player: class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = '__all__' def create(self, validated_data): # what to do here? How to create a new token for 'Player'? The Player model extends the 'MyUser' model: class MyUser(AbstractUser): pass class Player(MyUser): national_id = models.CharField(max_length=10) def save(self, *args, **kwargs): self.username = self.email return super().save(*args, **kwargs) -
How to fetch and count duplicate objects in (merged) querysets? [Django]
I am trying to find all duplicates between the current and previous project(s) and count them in order to show the number of the duplicates (or in my case the "returning" visitors from a previous project). The following code works as intended partially, but the issue here is that it will return the correct number of "returning visitors" only if there are two projects available, and it will mess up the things if there is a next project added. For example: The first project have 5 unique visitors. In the second project there are 5 visitors as well, but 3 of them are returning from the first project. At this point the app will show 3 returning visitors which is correct. But if I add the third project, that will have 5 new visitors but only 1 of them is returning from both previous projects and the remaining 4 are new visitors - it will return result as if there are 3 returning visitors again. In this example, my goal would be to show that for the third project, there is only 1 returning visitor from the previous projects (any of the previous or both). So far I have this … -
How can I make a reservation with Django rest framework?
I'm coding a rest API with Django rest. I have a Room model I want to users can reserve the rooms. the rooms have price, reserve days. I created two another models named "order" and "order-item" they are linked together with Stacked Inline in admin.py . with these two models I want to create a order and with a total price function I want to calculate the total price of the reservation ("room price" * "reserve days") . I used Model Serializer for serializing my models. I can't write views.py please help me write my view. from django.contrib.auth.models import User from django.db import models from eghamat.models import Room class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user} - {str(self.id)}' def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) return total class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='order_items') price = models.IntegerField() quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity -
Mysql is not connecting Docker
I am trying to connect mysql docker container on live server but Its not working My docker-compose file is db: image: mysql:5.7 restart: always env_file: - ./todolist/todolist/.env volumes: - ./mysql-data:/var/lib/mysql ports: - "3302:3306" and my env file is like MYSQL_PORT=3306 MYSQL_DATABASE=mydb MYSQL_USER=root MYSQL_PASSWORD=root MYSQL_ROOT_PASSWORD=root and my Django settings.py is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': mydb, 'USER': root, 'PASSWORD': root, 'HOST': db, 'PORT': 3306, } } and error log on gitlab CI is Creating test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") -
how to update a table field after BooleanField is clicked
lets think you have a table like this MODELS.PY class test(models.Model): name = models.CharField(max_length=20) pluspoints = models.BooleanField(default=False) minuspoints = models.BooleanField(default=False) total_points = models.IntegerField() def __str__(self): return str(self.name) points.html <form id="points_form"> {% csrf_token %} <div class="row"> <div class="col-3"> {{ form.name|as_crispy_field }} </div> <div class="col-3"> {{ form.pluspoints|as_crispy_field }} </div> <div class="col-3"> {{ form.minuspoints|as_crispy_field }} </div> </div> <br> <input class="btn btn-outline-primary" type="submit" name="submit" value="give the points" /> </form> now, I want to update the "total_points" -1 when I click on minuspoints and +1 when I click on pluspoints. Is this possible? or what could I do else. -
How to send a CSRF token from Django to Vue
My web app is divided into two directories, front-end and back-end, and they hosted on a different domains, because the domains are different, I can't get a CSRF token from cookie file, for Vue to send a post request. How can I get this token in that case? -
DRF: Source reference without re-define field
I'd like to change field name in DRF ModelSerializer without the need to re-define the field I am pointing to. According a post on SO (ref), one can re-name a field name within the serializer by using source, such as: location = serializers.CharField(source='alternate_name') However, this method takes away the benefits of using a ModelSerializer as you essentially need to re-write the field completely, which is a pain when you have many fields. in my case, I have a model field such as: product_uid = models.UUIDField(primary_key=False, unique=True, default=uuid.uuid4, editable=False) In the API, I'd like the field to be called 'uid'. If I would do the following: uid = serializers.UUIDField(source=product_uid) would result in editable=True Is there a way to reference to a ModelField and keep its definition intact according the Model (as you normally do when using serializers.ModelSerializer) but only change the name, e.g. something like: uid = serializers.ModelField(source=product_uid) ? -
why signal triggered in wrong time?
I'm creating a signal which creates a profile for the user considering the group they are in. For example if they user is in TEACHER group the teacher_profile would be created for it. The problem is that the signal triggered before the group of user has been set and gives me the error 'NoneType' object has no attribute 'name'. #views.py def register_page(request): if request.POST: password = request.POST['password'] repassword = request.POST['repassword'] username = request.POST['username'] GROUP = request.POST['group'] if password == repassword: #creating user user = User.objects.create(is_superuser=False, username=username) user.groups.set([Group.objects.get(name=GROUP), ]) user.set_password(password) user.save() #authenticating user user = authenticate(username=username, password=password) if user: login(request, user) return redirect('/esadra/user/dashboard/') else: messages.error(request, 'پسورد ها مطابقت ندارند') messages.error(request, 'فرم را درست پر کنید') #models.py @receiver(post_save, sender=User) def user_profile_creator(sender, instance, created, *args, **kwargs): if created: if instance.groups.first().name == 'TEACHER': profile = teacher.objects.create(user=instance) elif instance.groups.objects.first().name == 'Student': profile = student.objects.create(user=instance) I have tried `m2m_changed` that made other problems for `set_password` , it made the user instance `None type` because it should be saved to trigger the `m2m_changed` signal.