Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dropdown change values are not reflected
I have the following views: def home(requests): return render(requests,'home/welcome.html',{"ConfNames":getConfTitles()}) def getListValues(request): dropdown_value = "Teaching the unteachable: on the compatibility of learning analytics and humane education" t1=request.POST.get('exampleFormControlSelect2') t2=t1.replace("'","") print("The value is" ,t2) val=getConfData(t2) print("data is:",val) return render(request,'home/welcome.html',{"ConfDetails":val}) I have the following urls.py: urlpatterns=[ path('',views.home,name='home'), path('confs/',views.getListValues,name='listvals') ] I have the following data function,to get the data into context" import pandas as pd import numpy as np data_conf = pd.read_csv(r"dataset.csv") data_conf['ProcessedTitle'] = data_conf['title'].map(lambda x: x.replace(",","")) #data_conf['ProcessedTitle'] = data_conf['ProcessedTitle'].map(lambda x: x.replace("'","")) def getConfTitles(): list_years=list(data_conf['year'].values) list_titles=list(data_conf['ProcessedTitle'].values) dictionary = {} for i, j in zip(list_years, list_titles): dictionary.setdefault(i, []).append(j) return dictionary def getConfData(title): print("The value inside function is :",title) #data_conf.set_index('ProcessedTitle') #print("the df is",data_conf.loc[title,:]) values_title=data_conf.query('ProcessedTitle=="'+title+'"') values_title1=data_conf.loc[data_conf['ProcessedTitle'] == title] print(values_title) print("The values title is:",values_title) values_dic=values_title.set_index('ProcessedTitle').T.to_dict('list') return values_dic I have the following welcome.html template: <form method="POST" action="http://localhost:8000/confs/" id="sysform"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlSelect1">Select the Conference</label> <select class="form-control" id="exampleFormControlSelect1" onchange="populateValues()"> {% for key,value in ConfNames.items %}: <option value="{{value}}">LAK{{key}}</option> {% endfor %} </select> </div> <div class="form-group"> <label for="exampleFormControlSelect2" ></label> <select class="form-control" name="exampleFormControlSelect2" id="exampleFormControlSelect2" style="overflow-y: scroll;overflow-x: scroll;"> </select> </div> <button type="submit" class="btn btn-primary mb-2" form="sysform">Get Insights!</button> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">Confdata</h1> {% for key,value in ConfDetails.items %} {% for val in value %} {% with counter=forloop.counter %} {% if … -
Alternatives for serving Django App as SPA
I have a personal project undergoing currently, and I really want to make it SPA smooth. I would like to know if there is packages out of the box that can integrate with a minimum change on Django templates files (I got around 15 templates, a css file and a big js file). Many answers shows the need of rewriting the entire template system which I want to avoid to. If above not possible, what front-end framework can be used for switching to SPA quickly, I heard of Vue.js integrated inside Django templates, but it would bundle all my files into a single file (correct me if I am wrong). A list of libraries/packages/framework would be appreciated, and if worked with a front-end framework, what precautions is needed to take upon deployment on Linux. Thanks in advance -
Django path issue where I cannot get the second path to work
I'm getting into django and I've stumbled upon a problem that I have been banging my head against the wall for a while now. I have an app that has models for both "statemachine" and "node". I have a path for each in the url and a view for each that allows an id to be passed along for an individual view. The statemachine will return the request, but the node says there is "no reverse match". I know what that usually means but for the life of me I can't see what I'm missing. The urls... from django.urls import path, re_path from django.conf.urls import url from automation import views urlpatterns = [ path('', views.index, name='automation'), path('node/<int:node_id>', views.node, name='node'), path('statemachine/<int:statemachine_id>', views.statemachine, name='statemachine'), url(r'^ajax/updatestatemachines/$', views.updatestatemachines, name='updatestatemachines'), url(r'^ajax/updatenodes/$', views.updatenodes, name='updatenodes'), url(r'^ajax/updatenodesforstatemachines/(?P<machine_match>[^/]+)/$', views.updatenodesforstatemachines, name='updatenodesforstatemachines'), url(r'^ajax/updatenodesmapforstatemachines/(?P<machine_match>[^/]+)/$', views.updatenodesmapforstatemachines, name='updatenodesmapforstatemachines'), url(r'^node/(?P<node_id>\d+)/ringchart/$', views.ring_chart, name='ring_chart'), url(r'^node/(?P<node_id>\d+)/ringchart/svg/$', views.ring_chart_svg, name='ring_chart_svg'), ] The views.... def index(request): return render(request, 'automation/automation.html') def statemachine(request, statemachine_id): if request.is_ajax(): statemachine = get_object_or_404(StateMachine, id=statemachine_id) context = { 'statemachine': statemachine } return render(request, 'automation/partials/_statemachine.html', context) statemachine = get_object_or_404(StateMachine, id=statemachine_id) context = { 'statemachine': statemachine } return render(request, 'automation/statemachine.html', context) def node(request, node_id): node = get_object_or_404(Node, id=node_id) context = { 'node': node } return render(request, 'automation/node.html', context) next is … -
Django Rest API vs pure Django
I want to build an app that will use a database. I already build few of them, with models, views, urls... But I discovered that I can build my own API using Django Rest and use this API in my Django project. So if I undersand I will have to separate apps: -an API and my Django app and all my models and database related datas will be in my API app. If I want to use vue.js for the frontend in my Django app, using an API will make eveything simplert to implement? -
what is the differences between reverse and reverse_lazey methods in Django?
I can't use reverse() method in a class to generate url for example, reverse() doesn't work in generic views or Feed classes (reverse_lazy() should be used instead) but I can use reverse() in functions. what is the differences ? take a look at following: class LatestPostFeed(Feed): title = 'My Django blog' # link = reverse_lazy('blog:index') description = 'New posts of my blog' def items(self): return models.Post.published.all()[:5] def item_title(self, item): return item.title def item_description(self, item): return truncatewords(item.body, 30) def link(self): return reverse('blog:index') the link attribute above only works with reverse_lazy() method. but the link function works with both reverse_lazy() and reverse() methods -
How to make a ForeignKey field in models, display text name instead of a URL in admin view?
I'm using django 1.4, I have a ForeignKey field in my model and on the admin view it shows the FK field as a URL link to the object in view mode, how can I change it to just show text instead of a url link? Can this be done through widgets in the forms.ModelForm? Thanks! -
Foreign key fields in Django
What is best way to save foreign key fields without letting user to select from the parent model? Let say i have these models Models class Category(models.Model): category_id = models.AutoFiled(primary_key=True) class Brand(models.Model): brand_id = models.AutoFiled(primary_key=True) class Product(models.Model): category = models.ForeignKey(Category) brand = models.ForeignKey(Brand) name = models.CharField(max_length = 10, blank=True) Forms Class ProductForm(forms.ModelForm): class Meta: Model = Product fields = ['name'] Views def create_product(request): if request.method == "POST": form = ProductForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved!', 'alert-success') return redirect('products') else: return render(request, ' manageproducts/create_product.html', {'form':form}) I want a user to enter only a name but in the database i want a form to post category_id, brand_id and name. How can i do that? -
ModuleNotFoundError: No module named 'context'
I get the following error when I try to run a pyVows test: Traceback (most recent call last): File "C:\Program Files\Python38\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Program Files\Python38\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "D:\Programmierung\Python-Projekte\JourneyMap\JourneyMap\tests.py", line 2, in <module> from django_pyvows.context import DjangoHTTPContext File "C:\Users\malo0\AppData\Roaming\Python\Python38\site-packages\django_pyvows\__init__.py", line 11, in <module> from context import DjangoContext, DjangoHTTPContext ModuleNotFoundError: No module named 'context' I installed pyVows and django-pyvows Am I missing something? I found no helpful documentation. -
Data from django model form not being saved to database
I created a model form with a few fields and would like to save the data when a user enters values into the template and clicks submit. However when I click 'submit' the values are not cleared from the form, and the data is not getting saved into the sqlite3 database which I checked using select * from notes_note; I am not getting any error, it simply isn't saving that data. Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Note(models.Model): owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,) title = models.CharField(max_length=100) text = models.CharField(max_length=500) createTime = models.DateTimeField() from django.forms import ModelForm class NoteForm(ModelForm): class Meta: model = Note #fields = '__all__' #fields = ['title', 'text', 'createTime'] exclude = ['owner'] Template <a href="/notes/logout/">Log Out</a> <h2>Dashboard {{ user }}</h2> <table> <tr> <td> <form_name="noteForm" action="/notes/dashboard/" method="post"> {% csrf_token %} {{ form.as_p }} <input type= "submit" value="New Note"/> </form> </td> </tr> </table> Views.py @login_required(login_url="/notes/index/") def dashboard(request): if request.method == 'POST': # d dict is a copy of our request.Post because it's immutable and we need to add owner d = request.POST.copy() d.update({'owner': request.user.id}) form = NoteForm(d) if not form.is_valid(): template = loader.get_template('dashboard.html') context = { 'form': form, } return HttpResponse(template.render(context, request=request)) … -
Display ModelChoiceField in Django form without other fields
I'm trying to display a form with a ModelChoiceField, and use two fields from the model being references to display the options in the form. My view: def managecustomer(request, urlid): customer = Customer.objects.get(id=urlid) AssignManagerForm.base_fields['full_name'] = forms.ModelChoiceField(queryset=Customer.objects.all(), to_field_name="full_name") if request.method == "POST": form = AssignManagerForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return render(request, 'mysite/managecustomer.html', {}) else: form = AssignManagerForm() context = { 'customer': customer, 'urlid': urlid, 'form': form, } return render(request, 'mysite/managecustomer.html', context) My forms.py: class AssignManagerForm(forms.ModelForm): class Meta: model = Customer fields = ('first_name', 'last_name',) And my Customer model class Customer(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) customer_email = models.EmailField(max_length = 254) username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) @property def full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) With how I have done things, My select dropdown modelchoicefield works and displays options populated from my Customer table. However, it also displays the first_name and last_name fields as text boxes. I can't seem to avoid this. I need to specify some fields in forms.py, and excluding all fields resulted in them all being displayed. How can I only show the modelchoicefield and no other fields in my form? -
django Q filter doesn't work.(Conversation matching query does not exist.)
I'm trying to make a chatting room. and here is my code. def make_chatroom(request, user_one, user_two): user_one = user_models.User.objects.get_or_none(pk=user_one) user_two = user_models.User.objects.get_or_none(pk=user_two) if user_one is not None and user_two is not None: try: conversation = models.Conversation.objects.get( Q(participants=user_one) & Q(participants=user_two) ) except models.Conversation.DoesNotExist: conversation = models.Conversation.objects.create() conversation.participants.add(user_one, user_two) return redirect(reverse("conversations:detail", kwargs={"pk": conversation.pk})) but the Q filter doesn't work and this code go to except repeat. when I erase try~except part, it occur error Conversation matching query does not exist. user_one is exist, and user_two also exist. but conversation be made repeatedly. How can I fix it? -
How I need to change my paths to use multiple ids from url but not as params?
I want to have a URL like this 127.0.0.1:8000/classesapp/class/1/student/2/statistics/ so in the backend with a Django class, I will be able to do a raw query using those ids like this: select * from statistics inner join students on statistics.student_id = student.id inner join class on student.student_class_id = class.id where class.id = 1 and student.id = 2 How I could achieve this? I can't figure out what I need to do. I tried this but still didn't work. class/<int:pk>/students/<int:pk>/statistics my paths are: path('class/<int:pk>/', views.ClassesDetailView.as_view(), name="class_detail"), path('about/', views.AboutView.as_view(), name="about"), path('class/<int:pk>/', views.ClassesDetailView.as_view(), name="class_detail"), path('new/', views.ClassesCreateView.as_view(), name="classes_create"), path('class/<int:pk>/update/', views.ClassesUpdateView.as_view(), name="classes_update"), path('class/<int:pk>/delete/', views.ClassesDeleteView.as_view(), name="classes_delete"), path('class/<int:pk>/student/new/', views.StudentsCreateView.as_view(), name="student_create"), path('students/', views.StudentsListView.as_view(), name="students_list"), path('student/<int:pk>/', views.StudentsDetailView.as_view(), name="student_detail"), path('student/<int:pk>/update/', views.StudentsUpdateView.as_view(), name="student_update"), path('student/<int:pk>/delete/', views.StudentsDeleteView.as_view(), name="student_delete"), path('student/<int:pk>/statistics/new/', views.StatisticsCreateView.as_view(), name="statistics_create"), path('statistic/<int:pk>/update/', views.StatisticsUpdateView.as_view(), name="statistic_update"), path('statistic/<int:pk>/delete/', views.StatisticsDeleteView.as_view(), name="statistic_delete"), -
Django virtual env issues with Python and Atom
I've been all over the site trying to find a solution for a problem i am running into with my virtual environment and the python version being used. I have installed mini conda I am on a Mac I have run the conda create myDjangoEnv python=3.6 conda commmand, and i have activated the env with the conda activate myDjangoEnv command. I have confirmed that django is installed in the venv and the version is 3.8.4 The problem I am running into is when trying to execute the command python manage.py runserver, I first get the from exc error. When checking python it says it is running 2.7 version in the atom terminal, however when i check my virenv in my normal terminal the python version returns with 3.6. In the atom terminal, when i execute python3 manage.py runserver, the from exc error goes away but then I run into the ImportError: Django package cannot be found. Has anyone run into this issue specifically with the Atom server? Is there something I am doing wrong when creating the projects in atom that is tripping the virtual environment and resetting the python version to 2.7? -
Aggregate and Group data for chartJS in django
I want to produce some charts from my attendance model. I have a solution but just wondering if there is a more efficient way or not. What I am doing is just a simple nested loops. annotate is not good as I think it will make my missing data disappear. my model ```python``` attn_choice = ( ('1', 'N/A'), ('2', 'No Show'), ('3', 'Present'), ('4', 'Late'), ('5', 'Vacation'), ('6', 'Sick'), ('7', 'Training'), ('8', 'Off-Site Work'), ('9', 'Approved Delay Start'), ('10', 'Not Scheduled'), ('11', 'Other'), ) class Attendance(models.Model): employee = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, limit_choices_to={'is_active': True}, related_name='employee') supervisor = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True, related_name='supervisor', limit_choices_to={'user_type__lte': 2, 'is_active': True}) date = models.DateField() ac = models.ManyToManyField(Ac, related_name='aircraft', limit_choices_to={'active': True}) remarks = models.TextField(blank=True) attendance = models.CharField(max_length=2, choices=attn_choice, blank=True) time_added = models.DateTimeField(auto_now_add=True) time_modified = models.DateTimeField(auto_now=True) Code for my chart class LineChartJSONView(BaseLineChartView): cat = [b for a, b in attn_choice] days = [datetime.today() - timedelta(days=6-a) for a in range(7)] def get_labels(self): return [d.strftime('%d-%b') for d in self.days] def get_providers(self): return self.cat def get_data(self): u = self.request.user emp = CustomUser.objects.filter(team__in=u.sup_team.all(), shift__in=u.sup_shift.all()) data=[] for a, b in attn_choice: c=[] for d in self.days: qry = Attendance.objects.filter(date__gte=d,employee__in=emp,attendance=a) c.append(qry.count()) data.append(c) return data also wondering regardless of having missing values, what is the most … -
How can i resolve this issue: ERROR: unsatisfiable constraints: postgresql-client (missing): required by: world[postgresql-client]?
Please, can someone help me? I just started learning Django-REST-API using Docker. I want to install postgresql-11-alpine but i keep getting this error messages when i run; docker-compose build: WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.12/main/x86_64/APKINDEX.tar.gz: temporary error (try again later) WARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.12/community/x86_64/APKINDEX.tar.gz: temporary error (try again later) ERROR: unsatisfiable constraints: postgresql-client (missing): required by: world[postgresql-client] ERROR: Service 'app' failed to build: The command '/bin/sh -c apk add --update --no-cache postgresql-client' returned a non-zero code: 1 Below is my Dockerfile file FROM python:3.7-alpine MAINTAINER Tboost Technology #set environment variable ENV PYTHONUNBUFFERED 1 #install dependencies COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev python3-dev linux-headers postgresql-dev RUN pip3 install -r /requirements.txt RUN apk del .tmp-build-deps #mkdir to store your apps source code RUN mkdir /app WORKDIR /app COPY ./app /app #create user to run apps in the docker RUN adduser -D user #switch to the user USER user Below is my docker-compose.yml file version: "3" services: app: build: context: . ports: - "8000:8000" extra_hosts: - "host.docker.internal:172.17.0.1" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:11-alpine restart: … -
What to do to get an ip position for my raspberry pi on my website made with django?
I've made a simple web site with django, now I need to receive IP location of raspberry pi (3 rasspberry pi ) on my web site, I don't know how to begin ! Any tutorials or suggestions please -
Django >> Facing problems to execute django models in database
i been developing my first django project.here goes the problem: i am developing a site for my products and special cares.members can register,login and logout.i have done successful login-logout system.but i also have a feature that says only a few members who will give check in between limited amount of time can view a special page that other members who didn't do the same can't visit.Here goes what i have done: src >> ...db.sqlite3 ...manage.py ...mainapp (main module) ...__init__.py ...settings.py ...urls.py ...wsgi.py ...contest (django app) ...Migrations(Folder) ...__init__.py ...admin.py ...apps.py ...models.py ...tests.py ...views.py ...accounts (django app) ...Migrations(Folder) ...__init__.py ...admin.py ...apps.py ...models.py ...tests.py ...views.py ...templates ...static in accounts.models : from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active … -
How to make left outer join for subquery?
Sql query select * from products_product left join ( select * from products_purchase join products_product on products_purchase.product_id = products_product.name where user_id = 1 ) t on t.name = products_product.name where products_product.name like '03%'; I want to write this query on django orm and check on exists rows with user_id Null. -
How merge uploaded multiple chunk file(blob) in Django server
I am trying to upload large file with chunk. From frontend I am passing multiple chunks(file.slice(start, chunkSize + 1)) by ajax call. After receive multiple chunk how can I merge them to get original large file ? -
Testing Django project
I've done a fair bit of reading about unit and functional testing in Django but I'm a little bit confused as to where to draw the line between them and, ultimately, what the point of most of the unit tests are. I see unit tests like this:- def test_get_absolute_url(self): self.assertEqual( reverse('articles:detail', args=[self.article.slug]), self.article.get_absolute_url() ) and I wonder what the point of having that test is. The get_absolute_url method on the Article model just does the same thing, so why bother testing it separately? To my mind, the main reason for testing is to make sure that the whole application does what it's supposed to do and, with this in mind, I'd like (for example) to be able to test to make sure that, when someone registers to join an event, they do (or do not, depending on certain logic within the project) get signed up to it properly. So, for example, if there is an event which is restricted to certain people until a specific time, someone else trying to sign up to it wouldn't be allowed in. Would this be seen as more of a functional/integration test? Should I be focussing more on these kinds of tests rather than … -
how to i debug unable to import 'adoptions.models'?
The error says Unable to import 'adoptions.models' and No value for argument 'dt' in unbound method call. This is the program. from csv import DictReader from datetime import datetime from django.core.management import BaseCommand from adoptions.models import Pet, Vaccine from pytz import UTC DATETIME_FORMAT = '%m/%d/%Y %H:%M' VACCINES_NAMES = [ 'Canine Parvo', 'Canine Distemper', 'Canine Rabies', 'Canine Leptospira', 'Feline Herpes Virus 1', 'Feline Rabies', 'Feline Leukemia' ] ALREADY_LOADED_ERROR_MESSAGE = """ If you need to reload the pet data from the CSV file, first delete the db.sqlite3 file to destroy the database. Then, run python manage.py migrate for a new empty database with tables""" class Command(BaseCommand): # Show this when the user types help help = "Loads data from pet_data.csv into our Pet model" def handle(self, *args, **options): if Vaccine.objects.exists() or Pet.objects.exists(): print('Pet data already loaded...exiting.') print(ALREADY_LOADED_ERROR_MESSAGE) return print("Creating vaccine data") for vaccine_name in VACCINES_NAMES: vac = Vaccine(name=vaccine_name) vac.save() print("Loading pet data for pets available for adoption") for row in DictReader(open('./pet_data.csv')): pet = Pet() pet.name = row['Pet'] pet.submitter = row['Submitter'] pet.species = row['Species'] pet.breed = row['Breed'] pet.description = row['Pet Description'] pet.sex = row['Sex'] pet.age = row['Age'] raw_submission_date = row['submission date'] submission_date = UTC.localize( datetime.strptime(raw_submission_date, DATETIME_FORMAT)) pet.submission_date = submission_date pet.save() raw_vaccination_names = row['vaccinations'] … -
GraphQl doesn't authorize using JWT token
I am following this blog tutorial...well so far so good and i am generating then token...using GraphQl's default template input-> mutation{ tokenAuth(username:"riyad", password:"1234"){ token } } output-> { "data": { "tokenAuth": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InJpeWFkIiwiZXhwIjoxNTkzNTI0Nzk5LCJvcmlnX2lhdCI6MTU5MzUyNDQ5OX0.DjploWeEwLpRBZX0wz5_NSqz22qDHbgNI26uXs6fuXE" } } } but when i am fetching using insominia i am not getting the user authorize....rather it raise exception that i created... my schema file -> class UserType(DjangoObjectType): class Meta: model = get_user_model() class Query(graphene.ObjectType): me = graphene.Field(UserType) users = graphene.List(UserType) def resolve_users(self, info, **kwargs): return get_user_model().objects.all() def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise Exception('Not logged in!') return user my settings.file that i extra added GRAPHENE = { 'SCHEMA': 'hackernews.schema.schema' } '''python(path=“…/graphql-python/hackernews/hackernews/settings.py”) GRAPHENE = { ‘SCHEMA’: ‘mysite.myschema.schema’, ‘MIDDLEWARE’: [ ‘graphql_jwt.middleware.JSONWebTokenMiddleware’, ], } ''' AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] my main app -> import graphene import links.schema import users.schema import graphql_jwt class Query(users.schema.Query, links.schema.Query, graphene.ObjectType): pass class Mutation(users.schema.Mutation, links.schema.Mutation, graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() schema = graphene.Schema(query=Query, mutation=Mutation) -
Clean request.data in django rest
Quick question: I know that Django has some baked-in security at different system levels, but I'm not sure if accessing the the request.data property directly is save: book = Book.objects.get(uuid=request.data.uuid) (obviously, this is a simplified example) Do I have to clean the data? Are there some packages that do this for me or can I use some of Django's native functions for this? Thanks! -
How to use Social-Auth-Django-App with Facebook's https://m.me/
I tried using hyperlink and supplied it with my actual Facebook Username and it's working. But the problem is my actual Facebook Username is different from the Username provided by Social-Auth-App-Django. So I tried User ID instead but it's not working either. By the way what I'm trying to do is an online shopping website and when a user clicks the hyperlink, he/she will be redirected to the seller's Facebook Messenger account to start a conversation. This is the first line of code that I tried which is working. <a href="http://m.me/myFacebookUsername">Send Message to Seller</a> And this is the code I used using Social-Auth-App's provided data: <a href="http://m.me/SocialAuth_Username">Send Message to Seller</a> And I also tried this: <a href="http://m.me/SocialAuth_UID">Send Message to Seller</a> Any idea how I can use Facebook's m.me/ using the provided data by Social-Auth-App-Django? Or if you can suggest me other ways other than m.me/ I will greatly appreciate it. Thank you very much! -
ValueError: Dependency on app with no migrations: account
I am trying to deploy my code in heroku. While deploying i complete all the steps but i get error while migrate i try these command heroku run python manage.py makemigrations account While running above command i get account/migrations/0001_initial.py - Create model User but while trying to migrate I try heroku run python manage.py migrate account i get error raise ValueError("Dependency on app with no migrations: %s" % key[0]) ValueError: Dependency on app with no migrations: account i also try heroku run python manage.py makemigrations heroku run python manage.py migrate At this time also i get same error the project is running successfully in localhost with out any error I am new to heroku please anyone can help with full instruction