Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AllAuth with Twitter Error: "No access to private resources at api.twitter.com"
I'm trying to setup the Django AllAuth Twitter login. When the user authenticates with Twitter and is redirected to my website, Django AllAuth raises the Error "No access to private resources at api.twitter.com" and I'm pretty lost here. I have the following settings in my settings.py: SOCIALACCOUNT_PROVIDERS = { "twitter": { # From https://developer.twitter.com "APP": { "client_id": os.environ["TWITTER_API_KEY"], "secret": os.environ["TWITTER_API_SECRET"], } }, } My app has the following privilege rights in the developer portal: OAuth1 Endpoints OAuth2 Endpoints User Email Read Tweets and Profiles Any ideas why this could be happening? Thanks in advance! -
Celery beat service showing inactive (dead) in python3
here i am using celery version 5.1.2 on Ubuntu 16.04 with python version 3.7 and Django version 3.0 here i am unable to schedule tasks and i couldn't understand why its showing inactive(dead) here are the commands what i am using and the result what i am getting sudo systemctl daemon-reload sudo systemctl reset-failed celeryd.service sudo systemctl restart celeryd sudo systemctl status celeryd ● celeryd.service - Celery Beat Service Loaded: loaded (/etc/systemd/system/celeryd.service; enabled; vendor preset: enabled) Active: inactive (dead) since Fri 2022-04-01 13:08:11 BST; 2min 20s ago Process: 4520 ExecStart=/home/ravi/.virtualenvs/lightdegree/bin/celery multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_F Main PID: 4520 (code=exited, status=0/SUCCESS) Apr 01 13:08:10 ip-xxx systemd[1]: Started Celery Beat Service. Apr 01 13:08:11 ip-xxx celery[4520]: celery multi v5.1.2 (sun-harmonics) Apr 01 13:08:11 ip-xxx celery[4520]: > Starting nodes... Apr 01 13:08:11 ip-xxx celery[4520]: > worker1@ip-xxx: OK here i am sharing my celery log file result also Apr 1 13:20:08 ip-xxx systemd[1]: Reloading. Apr 1 13:20:08 ip-xxx systemd[1]: Started ACPI event daemon. Apr 1 13:20:17 ip-xxx systemd[1]: Stopped Celery Beat Service. Apr 1 13:20:17 ip-xxx systemd[1]: Started Celery Beat Service. Apr 1 13:20:18 ip-xxx celery[4868]: #033[1;36mcelery multi v5.1.2 (sun-harmonics)#033[0m Apr 1 13:20:18 ip-xxx celery[4868]: > Starting nodes... Apr 1 13:20:18 ip-xxx celery[4868]: … -
What is the proper way to upload files using FileField in Models and Serializers in Django Rest Framework?
I am making a simple DRF Login App which will let the user to upload a CSV file and its description upon registration. It is working fine but when I upload the file, it gives the error The submitted data was not a file. Check the encoding type on the form.. I have searched around stackoverflow but there are questions related to only ImageField (that is image) not FileField. SO I was unable to solve the issue. My Models.py is: class Detail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) file = models.FileField(verbose_name="CSV File", upload_to='csv_files') file_desc = models.TextField("CSV File Description") def __str__(self): return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name)) My Serializers.py is: class MainRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') class RegisterSerializer(serializers.ModelSerializer): register = MainRegisterSerializer() class Meta: model = Detail fields = ['register', 'file', 'file_desc'] optional_fields = ['file', 'file_desc'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['register']['username'], validated_data['register']['email'], validated_data['register']['password']) user.first_name = validated_data['register']['first_name'] user.last_name = validated_data['register']['last_name'] user.save() detail = Detail(user=user, file=validated_data['file'], file_desc=validated_data['file_desc']) detail.save() return user My Views.py is: class RegisterAPI(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'accounts/register.html' def get(self, request): serializer = RegisterSerializer() return Response({'serializer': serializer}) def post(self, request): serializer = RegisterSerializer(data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer}) … -
Python - FastAPI vs Django [closed]
Based on benchmarks, FastAPI has better performance than Django. FastAPI is also an ASGI app, as opposed to Django being WSGI. Django projects are also much heavier and you have to do a lot using python3 manage.py. I personally find that FastAPI is nicer to use in terms of API and documentation. Is there any benefit of Django that I am missing, or is it just personal preference? -
Get id of FactoryBoy factory with LazyAttribute when using DjangoModelFactory
I have the following factory and want to access the id of an instance that will be created from it: class PlatformFactory(factory.django.DjangoModelFactory): type = factory.fuzzy.FuzzyChoice(Platform.Type) name = factory.fuzzy.FuzzyText(length=30) user = factory.SubFactory(UserFactory) ext = factory.LazyAttribute(lambda self: f"{self.user.key}|{self.id}") class Meta: model = Platform exclude = ["user", ] Unfortunately it gives me the error AttributeError: The parameter 'id' is unknown. Evaluated attributes are {'type': <Type.OTHER: 2>, 'name': ... But since it is a django model there is an id present. Why is this not recognized by factory boy and how can I solve this? Thanks and regards Matt -
Python Django Class based views - accessing data
I've created a ListView # views.py from django.views.generic import ListView class ReportListView(ListView): model = ReportList context_object_name = 'reportitems' template_name = "reports.html" # urls.py path('reports/', login_required(views.ReportListView.as_view()), However, when I try to check length of reportitems I get this error `Could not parse the remainder: '(reportitems)' from 'len(reportitems)' # my html file {{ len(reportitems) }} or {{ len(object_list) }} I get the same error with object_list too. What am I doing wrong? Just to confirm. ReportList model doesn't have any data in it. Is that the reason it's failing? If yes, how could I check that if there is any data or not yet? I tried to look at Django docs and Google search. However, it seems like I should have access to object_list variable or unless when I change it's name. -
Static files don't load in django framework
Settings SITE_ID = 1 STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Template home-page.html {% load static %} piece of code <!-- JQuery --> <script type="text/javascript" src="{% static 'app1/js/jquery-3.4.1.min.js' %}"></script> <!-- Bootstrap tooltips --> <script type="text/javascript" src="{% static 'app1/js/popper.min.js' %}"></script> <!-- Bootstrap core JavaScript --> <script type="text/javascript" src="{% static 'app1/js/bootstrap.min.js' %}"></script> <!-- MDB core JavaScript --> <script type="text/javascript" src="{% static '../js/mdb.min.js' %}"></script> <!-- Initializations --> <script type="text/javascript"> // Animations initialization new WOW().init(); urls from commercemag import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls', namespace='item-list')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) idk what i should do, please help me -
How to annotate an object with the sum of multilplication of two fields from a related object to a realated object in Django
Given these three classes class User(BaseModel): name = models.CharField(..) class Order(BaseModel): user = models.ForeignKey(User,...,related_name='orders') class OrderItem(BaseModel): order = models.ForeignKey(Order,...,related_name='items' quatity = models.IntegerField(default=1) price = models.FloatField() and this is the base class (it is enough to note that it has the created_at field) class BaseModel(models.Model): createt_at = models.DateTimeField(auto_now_add=True) Now each User will have multiple Orders and each Order has multiple OrdeItems I want to annotate the User objects with the total price of the last order. Take this data for example: The User objects should be annotated with the sum of the last order that is for user john with id=1 we should return the sum of order_items (with ids= 3 & 4) since they are related to the order id=2 since it is the latest order. I hope I have made my self clear. I am new to Django and tried to go over the docs and tried many different things but I keep getting stuck at getting the last order items -
How to ignore html tags/code stored in JavaScript variables?
Hi I am currently working on a django project wherein I send multiple plotly charts as html code to the client side and try to store this html code in a dictionary I first make the chart and convert to HTML code prediction_graph = prediction_graph.to_html(full_html=False) then I send multiple such charts to client side. Here please note that charts itself is a dictionary. return render(request, 'charts.html', { "tickerList": charts["tickerList"], "charts": json.dumps(charts)}) On client side I try to store it in a javascript variable charts = {{ charts|safe }}; However the html tags/code present in this variable causes error. Is there any way to solve this? like make it ignore the html tags/code -
Can't open localhost in the browser on port given in docker-compose
I am trying to build and run django application with docker and docker-compose. docker-compose build example_app and docker-compose run example_app run without errors, but when I go to http://127.0.0.1:8000/ page doesn't open, I'm just getting "page is unavailable" error in the browser. Here is my Dockeffile, docker-compose.yml and project structure Dockerfile FROM python:3.9-buster RUN mkdir app WORKDIR /app COPY ./requirements.txt /app/requirements.txt COPY ./requirements_dev.txt /app/requirements_dev.txt RUN pip install --upgrade pip RUN pip install -r /app/requirements.txt docker-compose.yml version: '3' services: example_app: image: example_app build: context: ../ dockerfile: ./docker/Dockerfile command: bash -c "cd app_examples/drf_example && python manage.py runserver" volumes: - ..:/app ports: - 8000:8000 project structure: ──app ──app_examples/drf_example/ ────manage.py ────api ────drf_example ──requirements.txt ──requirements_dev.txt ──docker/ ────docker-compose.yml ────Dockerfile -
Django- iterate a through a for loop
I have the following for loop in my django template displaying the items in my 'question' list.I want to print the value according to the index position of the list.However when I am trying to print it , nothing is showing in my browser. I have use a range function in my context and initialize it with a value of 2 in a key name 'n'. This is my context context = {'range' : range(2), 'question': input_question, 'most_sim_Q': result[6], 'question_scores': question_scores} return render(request, 'predict/result.html', context) this is the template {% extends 'predict/base.html'%} {% block content %} {% for text in range %} <!--parsing the input question--> <h2>Input Question: </h2><br> {{question.text}} <!--Parsing the most similar question--> <h2>most similar question's are: </h2><br> {{most_sim_Q.n.most_sim_Q}} <!--parsing the top 10 most smilialr question--> <h2> Top 10 most similar questions found are : </h2><br> {%for ques_key, values in question_scores.items%} {% for que, score in question_score.i.items %} <h3> {{ que }} ==> {{score}} </h3> {% endfor %} {% endfor %} <h3>--------------------------------------------------</h3> {% endfor %} {% endblock content %} I am printing question.text where question is the list containing two values but {{question.text}}.This is my output Input Question: most similar question's are: Top 10 most similar questions found … -
Django infinite loading after multiple requests on apache using mod_wsgi
I recently added a second Django application to my functional set of websites, 1 Django 1 PHP on apache (3.3.0) using mod_wsgi. All the Django applications work fine, however, when I added a second Django application to my apache config file as a virtual host, it stopped responding after I refreshed the page a couple of times (give or take). I have played around with my WSGI files, deleted .htaccess files and changed virtual host configurations, alas it still does the same thing. Here is the necessary information (I hope) for anyone to take a look and help, any help is appreciated My vhost file LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310" WSGIApplicationGroup %{GLOBAL} ################################################################################################## # MAIL.NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName mail.neostorm.us.to SSLEngine on SSLCertificateFile "conf/ssl.crt/neostorm.us.to-chain.pem" SSLCertificateKeyFile "conf/ssl.key/neostorm.us.to-key.pem" DocumentRoot "C:/xampp/htdocs/webmail" <Directory "C:/xampp/htdocs/webmail"> Require all granted </Directory> </VirtualHost> ################################################################################################## # ASTINARTS.UK.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName astinarts.uk.to SSLEngine on SSLCertificateFile "conf/astinarts/astinarts.uk.to-chain.pem" SSLCertificateKeyFile "conf/astinarts/astinarts.uk.to-key.pem" Alias /static "C:/xampp/htdocs/astinarts/static" <Directory "C:/xampp/htdocs/astinarts/static"> Require all granted </Directory> Alias /media "C:/xampp/htdocs/astinarts/media" <Directory "C:/xampp/htdocs/astinarts/media"> Require all granted </Directory> Alias /.well-known "C:/xampp/htdocs/astinarts/.well-known" <Directory "C:\xampp\htdocs\astinarts\.well-known"> Require all granted </Directory> Alias /sitemap.xml "C:/xampp/htdocs/astinarts/sitemap.xml" Alias /robots.txt "C:/xampp/htdocs/astinarts/robots.txt" <Directory "C:/xampp/htdocs/astinarts/astinarts"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/astinarts/astinarts/wsgi.py" application-group=astinarts <Directory "C:/xampp/htdocs/astinarts/astinarts"> … -
Selection box answer and value
I have a Questionnaire model that has a selection dropdown boxes, the available choices to select from a formed from another model Choices The choices model has a choice_text field and a choice_value. When a user selects a choice_text it is posted to the database, but i also need to choice_value to be added to but this value is not visible. So basically the question would be "what is the marketing like" and choice would be good, bad or average. But the value would be 1 2 3 Im not sure of the best way to post both the choice and value. def get_questionnaire(request, project_id, questionnaire_id): # Get or Create the Response object for the parameters next = request.POST.get('next', '/') response, created = ProjectQuestionnaireResponse.objects.get_or_create( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(ProjectQuestionnaireAnswer, form=AnswerForm, fields=('answer','notes',), extra=0) answer_queryset = ProjectQuestionnaireAnswer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': formset = AnswerFormSet(request.POST, form_kwargs={'question_id': questionnaire_id}) instances = formset.save() return HttpResponseRedirect(next) else: pass # Get the list of questions for which no Answer exists new_answers = ProjectQuestionnaireQuestion.objects.filter( questionnaire__projectquestionnaireresponse=response ).exclude( projectquestionnaireanswer__response=response ) # This is safe to execute every time. If all answers exist, nothing happens for new_answer in new_answers: ProjectQuestionnaireAnswer(question=new_answer, response=response).save() ### getting all questions related to a given … -
How check empty variable in template? Exception Value: Could not parse the remainder
{% extends 'pygiustizia/base.html' %} {% block body %} <div class="wrapper"> <h2>Login</h2> <p>Prego, inserisci le tue credenziali di login.</p> <div class={% if len(tmplVar.loginErr) > 0 %} "alert alert-danger" {% endifequal %}> {% if tmplVar.loginErr is not None %} {{tmplVar.loginErr}} {% endif %}</div> <form action="{% url 'login' %}" method="post"> <div class="form-group"> <label>Username</label> <input type="text" name="username" class="form-control {% if tmplVar.usernameErr is not None %} is-invalid {% endif %}" value="{{tmplVar.username}}"> <span class="invalid-feedback">{% if tmplVar.usernameErr is not None %} {{tmplVar.usernameErr}} {% endif %}</span> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" class="form-control {% if tmplVar.passwordErr is not None %} is-invalid {% endif %}" value="{{tmplVar.password}}"> <span class="invalid-feedback">{% if tmplVar.passwordErr is not None %} {{tmplVar.passwordErr}} {% endif %}</span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> </form> </div> {% endblock %} Exception Value: Could not parse the remainder: '(tmplVar.loginErr)' from 'len(tmplVar.loginErr)' What I miss? How can I check if variable is empty or lenght 0? -
Object of type EnumMeta is not JSON serializable - Graphene Django
I am trying to develop an api in graphql and was using enums but while creating its throwing an error. Object of type EnumMeta is not JSON serializable Below are the types and objects I have created for the mutation. class TypeEnum(graphene.Enum): small = 1 medium = 2 big = 3 class ModelEnum(graphene.Enum): students = 1 teachers = 2 class FieldEnum(graphene.Enum): name = 1 class = 2 section = 3 class InputObject(graphene.InputObjectType): type = TypeEnum(), model = ModelEnum(), field = FieldEnum(), name = graphene.String() class Meta: fields = "__all__" class OutputObject(DjangoObjectType): id = graphene.String(source="pk", required=True) is_active = graphene.Boolean() input = graphene.JSONString() (graphene.Field(OutputObject) - same fields with InputObject but graphene.ObjectType ) class AddMutation(graphene.Mutation): class Arguments: input = graphene.Argument(InputObject) is_active = graphene.Boolean() response = graphene.Field(OutputObject) def mutate(self, info, input, is_active): payload = dict(is_active=is_active, input=input) model.objects.create(**payload) return AddMutation(response=qs) I have tried json.dumps(input, default=str) but that converted the input object into a string like this. "{\"type\": \"EnumMeta.small\", \"model\": \"EnumMeta.studens\", \"field\": \"EnumMeta.name\", \"name\": \"jane dow\"}" I am assuming input = graphene.JSONString() is the part that throws an error but is not sure how to resolve it. Can somebody help me with this? -
django AttributeError: 'AdminSite' object has no attribute 'prime'
AttributeError: 'AdminSite; object has no attribute 'prime' admin.py from django.contrib import admin from tsite.models import index from tsite.models import subscrib from tsite.views import tbook class indexAdmin(admin.ModelAdmin) : list =['First_Name',' Last_Name ','Department_Name',' Mobile_Number',' Email_Field'] class subscribAdmin(admin.ModelAdmin): list = ['subscribmode ','onlytest'] class tbookAdmin(admin.ModelAdmin): list =['Subscriptionfee' 'Contribution' 'Additionalpasses' 'Totalpay' ] admin.site.index(index, indexAdmin) admin.site.subscrib(subscrib,subscribAdmin) admin.site.tbook(tbook,tbookAdmin) models.py i give models in djangoin frame work here and i register from tkinter import TRUE from django.db import models from django.forms import modelform_factory class index(models.Model): First_Name = models.CharField(max_length=30) Last_Name = models.CharField(max_length=15) Department_Name = models.CharField(max_length=30) Mobile_Number= models.IntegerField() Email_Field=models.EmailField(max_length=254) class subscrib(models.Model) : subscribmode = models.CharField(max_length=3) onlytest = models.CharField(max_length=3) class tbook( models.Model) : Subscriptionfee = models.IntegerField() Contribution = models.IntegerField() Additionalpasses = models.IntegerField() Totalpay = models.IntegerField() urls.py from django.contrib import admin from django.urls import path from django.urls import include from tsite import views urlpatterns = [ path('Register/',views.index), path('Prime/',views.subscrib), path('Tbook/',views.tbook), path('Cooki/',views.cookies_count), path('admin/', admin.site.urls), ] -
Many-to-many relationships in Django
I'm currently doing a personal project to have a better understanding of how the Django REST framework works. Essentially, I'm trying to build a web application that allows users to share files, kind of a simplified version of Google Drive/Dropbox. However, I'm having some trouble with many to many relationships in my models. Essentially, I want each user to have its own folders, in each folder they would have zero or more files. A user could then share (read only access or allow write/delete) an entire folder or only individual files. A user can have one (home folder) or more folders A folder can have zero (empty folder) or more files A folder can be read by one (owner) or more users, and the same goes for files Many users can access (read only or write) depending on their permission level a folder/file I'm trying to model this relationships as follows: from django.db import models from django.contrib.auth.models import User class Folder(models.Model): title = models.CharField(max_length=50) description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) users_can_edit = models.ManyToManyField(User) users_can_see = models.ManyToManyField(User) class File(models.Model): title = models.CharField(max_length=50) description = models.TextField() folder = models.ForeignKey(Folder, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now=True, editable=False) users_can_edit = models.ManyToManyField(User) users_can_see = models.ManyToManyField(User) However, … -
No Reverse Match at /showing file i just got the error of it
got an error while doing the code.I want to redirect by button to other page but it is showing me the error I have not done any more coding just the simple code that we use to do I had written it nothing more NoReverseMatch at /showing Reverse for '<WSGIRequest: GET '/showing'>' not found. '<WSGIRequest: GET '/showing'>' is not a valid view function or pattern name. my code of views.py from django.shortcuts import redirect, render from django.contrib.auth import authenticate,login from user.forms import * from django.contrib import messages from user.models import * from user.models import Orders # Create your views here. def home(request): return render(request,'home.html') def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] userm=authenticate(user=username,passe=password) if userm is not None: login(request,userm) messages.success(request,"You have login successfully...") return redirect("home") else: messages.error(request,"Invalid Username or password...") return redirect("login") else: return render(request,'base.html') def register(request): if request.method=='POST': fm=Userregistration(request.POST) if fm.is_valid(): fm.save() else: fm=Userregistration() return render(request,'register.html',{'form':fm}) def Orderreg(request): if request.method=='POST': fm=Orderbook(request.POST) if fm.is_valid(): pi=fm.cleaned_data['parcel_info'] pq=fm.cleaned_data['parcel_qty'] pw=fm.cleaned_data['parcel_weight'] um=fm.cleaned_data['unit_mass'] d=fm.cleaned_data['desti'] ord=Orders(parcel_info=pi,parcel_qty=pq,parcel_weight=pw,unit_mass=um,desti=d) ord.save() fm=Orderbook() return redirect('service') else: fm=Orderbook() u=Orders.objects.all() return render(request,'service.html',{'form':fm,'us':u}) def contact(request): return render(request,'contact.html') def about(request): return render(request,'about.html') def show(request): return redirect(request,'showing.html') urls.py from django.urls.conf import path from user import views urlpatterns = [ path('',views.home,name='home'), path('home',views.home,name='home'), path('login',views.login,name='login'), path('register',views.register,name='register'), path('about',views.about,name='about'), path('service',views.Orderreg,name='service'), path('contact',views.contact,name='contact'), path('showing',views.show,name='show'), ] … -
Get count of users registered pey day in django app
I need to create a simple chart (using chart.js),so the should chart like this: On the Y-axis - the number of registered users,X-axis - date Screen below: My model: class User(AbstractBaseUser, PermissionsMixin): uid = models.CharField(max_length=36, unique=True, default=make_uid) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) activation_token = models.CharField(null=True, blank=True, max_length=100) date_joined = models.DateTimeField(default=now, editable=False) View: @staff_member_required() @login_required() def index(request): users = User.objects.all() context = { "users": users, "users_count": users.count } return render(request, "backoffice/backoffice_index.html", context) Template part with chart: <script> $(document).ready(function () { var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for user in users %} '{{ user.date_joined }}', {% endfor %}], datasets: [{ label: '# of users registered per day', data: [], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> <canvas id="myChart" … -
Django : "internal" (not views) functions. How to redirect and pass message when no Request?
I have understood how requests and URLs work in Django. I understood either that most of thing works with request. But coming from PHP, there is something missing in my Django understanding. I need to create (what I'm calling) internal functions or classes for doing repetitive tasks. Sometimes, some of them are even interconnected. In the present case : check if a CSV file is (still) existing. Otherwise, I want to stop the execution of my view and redirect to a page with an alert. However, I've read everywhere that messages system in Django works with request. But in my case, I ain't got request. So, what is the solution for passing messages with redirect or HttpResponseRedirect (or something else I don't already know) without request ? Do I need to always attach my functions on an URL and treat them like a view ? After long researches, still haven't found those answers. -
how to post data in a nested serializer in Django rest framework
I am working on an app and need help I want to authenticate LinkedIn and save the access token in a table and then collect the LinkedIn user details in another table below is my model.py class LinkedInUserCode(models.Model): """ Credentials for the user to give access to LinkedIn. """ user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.CharField(max_length=1024) expires_in = models.IntegerField() def __str__(self): return f'{self.token}' class Meta: db_table = 'linkedin_user_code' verbose_name_plural = "LinkedIn User Codes" class LinkedInProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) linkedin_id = models.CharField(max_length=1024, blank=True, null=True) first_name = models.CharField(max_length=1024, blank=True, null=True) last_name = models.CharField(max_length=1024, blank=True, null=True) profile_image_url = models.CharField(max_length=1024, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.linkedin_id}' class Meta: db_table = 'linkedin_profile' verbose_name_plural = "LinkedIn Profiles" I am using a nested serializer and this is my serialiser class LinkedInProfileSerializer(ModelSerializer): """ Serializer for the LinkedInProfile model. """ id = IntegerField(required=False) user = ReadOnlyField(source='user.email') linkedin_access = ReadOnlyField(source='linkedin_access.token') class Meta: model = LinkedInProfile fields = '__all__' def create(self, validated_data): """ Create a new LinkedInProfile instance. """ return LinkedInProfile.objects.create(**validated_data) def update(self, instance, validated_data): instance.linkedin_id = validated_data.get('linkedin_id') instance.first_name = validated_data.get('first_name') instance.last_name = validated_data.get('last_name') instance.profile_image_url = validated_data.get('profile_image_url') instance.linkedin_access = validated_data.get('linkedin_access') instance.save() return instance class LinkedInUserCodeSerializer(ModelSerializer): user = ReadOnlyField(source='user.email') profiles = LinkedInProfileSerializer(many=True, read_only=True) class Meta: … -
How to use Javascript variable in an if condition in Django template?
I am currently working on a django template wherein I want to use a javascript variable in the if condition. My code is as follows {% extends 'base.html' %} {% block content %} <br> <div class="buttonRow"> {% for t in tickerList %} <button class="btn btn-dark" onclick="changeChart(this.value)" value="{{ t }}">{{ t }}</button> {% endfor %} </div> <br><br> {% if {{ currentTicker }} %} {{ currentTicker |safe }} {% else %} <p>NO Graph</p> {% endif %} {% endblock %} <style> .buttonRow { width: 100%; float: left; border: solid 1px blue; text-align: center; } button { background: black; color: white; } </style> <script> var currentTicker = {{ tickerList.0 }} function changeChart(ticker) { currentTicker = ticker; } </script> Here the dictionary I send from the server-side may look like this { "tickerList" : ["GOOGL","TSLA"], "GOOGL" : (plotly object), "TSLA" : (plotly Object) } Depending on the button clicked by the user I want to change the graph (plotly object) on the screen. As you can I have made the necessary buttons and I change ```currentTicker`` variable but I am not sure how I can change the graph in real-time on the screen when the user clicks the button. Could anyone help with this? -
Django change ListView query based on selected option from dropdown menu without reloading page
I want to create a ListView that displays items from the Inventory model based on the selected Site from the dropdown menu without reloading the page as shown here: I tried passing in site.pk into the ListView filter which comes from the HTML template, but I believe this would reload the page and would pass it into the url (we prefer it not to). inventory.html {% for site in data.project_sites %} <a href="{% url 'inventory:list-inventory' site.pk %}"> <option value="{{site.pk}}">{{ site.siteName }}</option> </a> {% endfor %} views.py class InventoryListView(LoginRequiredMixin, generic.ListView): ... model = Inventory def get_queryset(self): qs = { "inventory": Inventory.objects.filter(id=self.request.GET.get('site.pk')), "project_sites": Site.objects.all(), } return qs I understand that this requires Javascript, but my group does not have much experience with Javascript and we have a short timeline for this. -
Unble to query django model using regex on live web server
I am working on querying django models using react axios get method and using regular expression to get the desired results. There is strange behaviour when request is made by the react axios get method. So, when I test on my local enviroment it works fine but when I put it on live web server it gives me 500 Internal Server Error. My tastypie resource: class ReportEmployeeResource(ModelResource): class Meta(CommonMeta): queryset = Employee.objects.all() resource_name = 'report-employee' filtering = { 'fname': ALL, 'lname': ALL, 'date': ALL } My Django Model: class Employee(models.Model): fname= models.CharField(max_length=50) lname = models.CharField(max_length=50) date = models.DateField(db_index=True) class Meta: db_table = 'employee' unique_together = ('date','fname') My react axios get request: axios.request({ method: 'GET', url: generateUrl('report', 'report-employee', [ { key: 'lname__regex', value: '^((?!\\w+).)*$' }, { key: 'date', value: startDate.format('YYYY-MM-DD') }, ]), headers: { 'Content-Type': 'application/json', }, }).then(response => { console.log(response.data); }); I have to use regex to check if lname has no words present in it. The request is working on local perfectly, but after putting it on live server it does not work. When I removed lname__regex from the url it returns the response. I am using Django 3.1.13 version, react 16.12.0 version, Live server is AWS EC2 with … -
Multiple filter option in Django Admin Charfield
How to filter multiple option in a admin.py, Models.py banana_name = models.CharField(max_length=255, verbose_name=_("Banana Name")) Admin.py list_filter = [ "banana_name", ] in banana_name there are multiple banana name , right now i can select one banana name at a time or all or none at a time.