Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get related objects in Django and how to use Prefetch with related models
models.py class Press(models.Model): created = models.DateTimeField(editable=False) title = models.CharField(max_length=500, blank=True) slug = models.SlugField(max_length=600, blank=True, unique=True) def __str__(self): return self.title class Scan(models.Model): press = models.ForeignKey(Press, related_name='scans', on_delete=models.CASCADE) created = models.DateTimeField(editable=False) title = models.CharField(max_length=300, blank=True) main_scan = models.ImageField(upload_to='press/scans', blank=True) def __str__(self): return self.title views.py class PressListView(ListView): model = Press context_object_name = "press" template_name = "press.html" def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['press'] = Press.objects.prefetch_related(Prefetch('scans', queryset=Scan.objects.select_related('press'))) return context What I would like to achieve on the front-end of the site is to list all Press and as the cover image for each would like to use 1st main_scan image from the Scan model. I know I can add models.ImageField to Press model, but I do not want to - in the admin I am using admin.TabularInline from Scan model that is attached to Press model. I know there is documentation on prefetch but probably I am using it wrong and as well doing it wrong on the front-end in the template. Question is how to make it very optimized, that the performance is best, hitting the Database just once. Previously I was doing it this way and it worked, but this is causing … -
Django REST Framework TokenAuthentication Problem
Estoy intentando implementar la autenticación de token, el cuál busco generar al momento de dar de alta un usuario. El usuario se genera correctamente pero no se genera el token. Otro problema, al margen de la no generación del token, es que al crear el usuario el password en la base de datos se guarda como texto plano. El código es el siguiente: Python 3.7 Django 2.2.3 DRF 3.10.1 PostgreSQL En settings.py ''' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Instaladas: 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } ''' En serializer.py ''' from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password':{'write_only':True}} def create(self, validated_data): user = User( email = validated_data['email'], username = validated_data['username'] ) user.set_password(validated_data['password']) user.save() Token.objects.create(user=user) return user ''' En apiviews.py ''' from rest_framework import generics from .serializers import UserSerializer class UserCreate(generics.CreateAPIView): authentication_classes = () permission_classes = () serializer_class = UserSerializer ''' En urls.py ''' from api.apiviews import UserCreate urlpatterns = [ path('v3/usuarios/', UserCreate.as_view(), name='usuario_crear') ] ''' Ingreso con la siquiente url: localhosts/api/v3/usuarios/ Creo un usuario y no me genera ningún error. El … -
Different fieldsets in Django Admin site depending on user group
In my django admin site I want to hide some fields to users within a group (Controllers group) What would be the best approach? Can we do something like this? This is my code, but it doesn't work: admin.py: class PriceFile(admin.ModelAdmin): if User.groups.filter(name='Controllers').exists(): fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description']})] else: fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description', 'total_sum', 'margin_percent', 'final_price']})] -
Django - Group by return only value Sum
In Django how to perform the following SQL: select sum(valor_aprovado) as vla from convenios group by ano order by ano Desired result: sum_value | -------------| 472837446.59| 163438615.51| 448397994.27| 959203234.57| 739555948.32| I'm using the following syntax, but I just want it to return the VLA field and not the ANO Convenios.objects.values_list('ano').order_by('ano').annotate(vla=Sum('valor_aprovado') Result: [(2002, Decimal('36246385105.92')), (2003, Decimal('163442260.52')), (2004, Decimal('447464292.52')), (2005, Decimal('948880015.70')), (2006, Decimal('737373593.32')), (2007, Decimal('1449818896.88')), (2008, Decimal('1812889287.82')), (2009, Decimal('2306375485.81')), (2010, Decimal('8730479758.56')), (2011, Decimal('1662088139.88')), (2012, Decimal('1886396504.43')), (2013, Decimal('535507602.69')), (2014, Decimal('4279003118.70')), (2015, Decimal('1883240765.95')), (2016, Decimal('1245291830.72')), (2017, Decimal('2161176688.18')), (2018, Decimal('1346548803.43'))] Can you help me? Thanks -
Count how many fields a model has
I am wondering if there is a way to know how many fields a model contains. Example: class Post(models.Model): title = models.TextField() body = models.TextField() sub_title = models.TextField() summary = models.TextField() I can count it but I would like to know if there is an in-built method that allows me to do so. Ideally the quesry/code would be: Post.number_of_fieds-->output--> 4 Does such a thing exist? -
I Want to create a API for a User to join Specific Group in my app
I'm trying to create a RESTApi for a user to join a specific group in my app. I have the following models: User, Groups then a ManytoMany connection of User to Groups under the field members I've tried using different view and serializers, I either Get queryset isnt iterable or null value in column "max_no_members" violates not-null constraint DETAIL: Failing row contains (11, , d85743a7-ccd9-4175-984b-86c10c75aec6, null, null, , null, 2019-07-25 18:11:34.9933+00, t, null, Monthly). views.py class GroupJoinAPIView(CreateAPIView): queryset = Groups.objects.annotate(arr=ArrayAgg('members')).values_list('id', 'arr') serializer_class = JoinGroupSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): print(sys.stderr, self.queryset) if self.request.user.id in self.queryset.all(): return 'User already in the group' else: list(self.queryset.all()).append(self.request.user.id) serializer.save() serializers.py class JoinGroupSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only = True) class Meta: model = Groups fields = ['members','users'] urls.py path('<int:pk>/join', GroupJoinAPIView.as_view(), name='members'), models.py(Groups) class Groups(models.Model): name = models.CharField(max_length = 50, unique = True) group_id = models.UUIDField(default = uuid.uuid4, editable = False) max_no_members = models.PositiveIntegerField() savings_amount = models.PositiveIntegerField() savings_type = models.CharField(max_length = 10, default = 'Monthly') description = models.TextField(blank=True) begin_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True) searchable = models.BooleanField(default = True) members = models.ManyToManyField(User, related_name='group_members') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete =models.CASCADE,related_name='group_admin' ) def __str__(self): return self.name I would like to be able to add an authenticated user to a … -
ApiConnectionError with Stripe Python SDK
I am developing a web app using Django and stripe payment gateway for payments. I used Ubuntu machine while integrating stripe payment(using stripe python SDK) and everything worked fine. I am running the same code again on Mac OS X system and it throws the following error: I found out different answers on StackOverFlow (found similar questions) for this but that didn't solve my issue. I tried the following things to resolve the issue: I tried connecting with a different key pair by generating it from the stripe dashboard I tried updating the OpenSSL through brew Turned off the firewall None of the above worked for me. Can someone help solve this who has faced a similar issue and resolved it? -
How to associate invited users with the inviter's Company/group?
I am using Django, django-allauth and django-invitations. I am able to successfully invite users to the platform, but I would like to associate them with the inviter's Company. I've read over the bee-keeper/django-invitations and it doesn't seem to have the information on how to do this. models.py class Company(models.Model): name = models.CharField(max_length=100, default=None) class CustomUser(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) objects = CustomUserManager() views.py @login_required def company_users(request): # Get users that are in the company's user database as well as users that have been invited company_users = CustomUser.objects.filter(company=request.user.company.id) Invitations = get_invitation_model() # I'm afraid this is going to get all invited users, not just those that belong to the company invited_users = Invitations.objects.filter() if request.method == 'POST': print(request.POST) invitees = request.POST['invitees'] invitees = re.split(',', invitees) for invitee in invitees: Invitation = get_invitation_model() try: invite = Invitation.create(invitee, inviter=request.user) invite.send_invitation(request) except IntegrityError as e: print(type(e)) print(dir(e)) return render(request, "company_users.html", { 'message': e.args, 'company_users' : company_users, 'invited_users' : invited_users, }) return render(request, 'company_users.html', { 'company_users' : company_users, 'invited_users' : invited_users, }) In the code above, users are successfully invited to the platform, but the user is not associated with the Company of the inviter. I'm also afraid that the list of invited … -
Django Code Acting Different To Code Ran Locally
When I try and run the code ' '.join([(f'<a href="{word}">{word}</a>' if ('http://' in word or 'https://' in word) else word) for word in chat.split(' ')]) in Django it throws a SyntaxError (SyntaxError at /chat invalid syntax (views.py, line 25)) however, when I run it locally there is no SyntaxError. The Python version on the webserver is 3.5, and the version I used was 3.6, but that shouldn't matter. If it does, however, what code should I use in place of what was provided? -
How to process the URL in django
I have created a form where the user can select different dropdown. On the basis of user selection, it will create a URL on selecting the submit button and that URL is displayed in the page with the URL link. When a user clicks into it, it directs to related web pages. But What I want is instead of a user clicking on URL, the related URL page should directly open when the user selects the select button. Do we use ajax here to process the form? I am not sure how to do it. Any help is appreciated. -
Can't display the contents of postgres table in Django Admin panel
I have a postgres instance on AWS and I am using it as the database in django. To push the data in the postgres into my django models.py I did - python manage.py inspectdb > models.py The models.py has this - class TasteCluster(models.Model): id_cluster = models.IntegerField(blank=True, null=True) table_cluster_name = models.CharField(max_length=250, blank=True, null=True) cluster_description = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return self.id_cluster Now when I check the tables in the admin panel in django I can see the table taste cluster like this - Select taste cluster to change ADD TASTE CLUSTER Action: Go 0 of 8 selected TASTE CLUSTER 632 644 643 639 619 614 665 621 8 taste clusters When I click on any of the id_cluster I get this error - TypeError at /admin/dbconnect/tastecluster/8/change/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/admin/dbconnect/tastecluster/8/change/ Django Version: 2.2.3 Exception Type: TypeError Exception Value: __str__ returned non-string (type int) Exception Location: /usr/local/lib/python3.7/site-packages/django/template/defaultfilters.py in _dec, line 42 Python Executable: /usr/local/opt/python/bin/python3.7 Python Version: 3.7.3 Python Path: ['/Users/rahman/Desktop/django_exercise/03project/post', '/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/rahman/Library/Python/3.7/lib/python/site-packages', '/usr/local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages/geos', '/usr/local/Cellar/numpy/1.16.3_1/libexec/nose/lib/python3.7/site-packages', '/usr/local/Cellar/protobuf/3.7.1/libexec/lib/python3.7/site-packages'] Server time: Thu, 25 Jul 2019 16:19:03 +0000 How can I get/view all the columns and rows of the table ? I am a newb at … -
I need to step out of django directory to see other url patterns
I am trying to make a simple wait-screen with js that redirects you to a django page. the wait-screen will be used alot in the script so I have it in a app called core. the app then has the necessary part linked in the root urls.py. but when I call the wait screen it will pull up but then look for the redirected url in only the core folder. I tried to include the root urls.py in my core/urls.py but that resulted in a circular url problem. here is the main urls.py from django.contrib import admin from django.urls import path, include from core.views import HomePage, wait_screen urlpatterns = [ path('', HomePage.as_view(), name="index"), ... path('Well/', include('Well.urls')), path('wait_screen/', wait_screen, name="wait_screen"), path('admin/', admin.site.urls), ] here is the core/urls.py from django.urls import path from . import views urlpatterns = [ path('wait_screen/', views.wait_screen, name="waitscreen"), ] here is the wait_screen written in js, linked with a view <script> $(function() { // Stop Watch Functions function get_elapsed_time_string(total_seconds) { function pretty_time_string(num) { return ( num < 10 ? "0" : "" ) + num; } ... } var elapsed_seconds = 0; // Set stopwatch setInterval(function() { elapsed_seconds = elapsed_seconds + 1; ... // Redirect var redirect_to = … -
Django view for quiz
I am a newbie to Django, I want to make quiz app but I am stuck in the problem. I have created 3 models(Quiz, Question, Choice). I want to write a function which returns questions which have the same quiz title. I tried this views.py def detail(request): sets = Quiz.objects.all() question = Question.objects.filter(sets.title) return render(request,'App/appdetail.html',{'question':question}) models.py class Quiz(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=100) def __str__(self): return self.title class Question(models.Model): set = models.ForeignKey(Quiz,on_delete=models.CASCADE) question_txt = models.CharField(max_length=100) def __str__(self): return self.question_txt class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_txt = models.CharField(max_length=20) boolean = models.BooleanField(default=False) def __str__(self): return self.choice_txt error message -
how to automatically populate part of Django modal form before popup using ajax code
I have created a work schedule page with a month view, where every day of the month will be pupated by the required tasks to be done on that day. I have also created a modal popup form that appears when the user click any of the dates of the schedule table. The form includes state_time, end_time, task_name, etc. When the user fill the form, a will be created in the relevant day of the month as soon as the user submitted the form. the press button is located in the scheduler table according to the start_time value in the form. The div id of every day cell of the scheduler is the same as its date. What I would like to do is as soon as the user click on any date in the scheduler table the popup form appears automatically populated with this date , which is the same as the clicked div id. view.py def task_create_slim(request): data = dict() # print("hii55") if request.method == 'POST': form = TaskFormSlim(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True New_task_data = form.cleaned_data # getting the data from the form jsut after saving New_task_date = New_task_data['start_time'] last_task_per_day=Task.objects.filter(start_time=New_task_date).last() # last_task_per_day = [Task.objects.all().latest('start_time')] # I … -
I've ran into really weird error some templates in production doesn't load
I deployed a django app on AWS EC2 every page is working but the login page and detail view page returning a 'template not found error while both of the views working on my machine.how can i fix this ? i already see it has to do something with my virtual machine. to keep in mind here's my folder structure : /Eyelizer /app1 /app2 /Eyelizer /eyelizerenv /etc I use this folder structure as it has something to do with the nginx and gunicorn configuration. -
TypeError: Object of type Cart is not JSON serializable
I just started using session in Django framework. I have create an object cart from Cart model. And when i wan to set cart inside request.session with session['cart'] = cart, I get this error message: TypeError: Object of type Cart is not JSON serializable This is my Cart model class Cart(object): def __init__(self): self.items = [] def addItem(self, itemCart): try: # get index of itemCart if exist index = self.items.index(itemCart) # itemCart exist then set its quantity self.items[index].setQuantity( self.items[index].quantity + itemCart.quantity) except ValueError: # the item does not exits then add to items list self.items.append(itemCart) This is my view when i update the session cart = Cart() session['cart'] = cart And When i run the code i get this error: File "C:\Users\Patrick-PC\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type Cart is not JSON serializable. Please help -
Is Django and Python a good solution for developing a motorsport engineering tool(Dynamics lap simulation, Timing Management, Calculations,...)
I'm thinking on developing a new Car Dynamics Simulation Tool in Django and Python, having databases with the simulations results and car models. The idea is plot in the web application all the results and display the results in a friendly way for the user. I am very confortable working with Python and I would like to know if you think it is a good idea to develop this tool in django(Python), as long as my idea is running the app through internet, with a certain user and password, and having the possibility of store all the results and models in the server. My only concern is that I dont know if Django is a valid solution for that or I should find other kind of solution. I hope you can help me! Thank you in advance -
Does not display data after filling in the template
I make comments on the site and cannot understand why, after the user has filled out comment forms, they are not displayed, I try to display them through a template P.S I need to display the text and the nickname that the user would enter views.py def CommentGet(request): if request.method == 'POST': comment = Comments(request.POST) name = request.POST['name'] text = request.POST['text'] if comment.is_valid(): comment.save() return HttpResponseRedirect(request.path_info) comments = CommentModel.objects.all() else: comment = Comments(request.POST) comments = CommentModel.objects.all() return render(request, 'news/post.html', {'comment': comment,'comments':comments}) post.html <form method="post" action="{% url 'comment' %}"> {% csrf_token %} <input type="text" name="name" value="{{ name }}"> <input type="text" name="text" value="{{ text }}"> <input type="submit"> </form> {% for comm in comments %} <h1> {{ comm.name }} </h1> <h1> {{ comm.text }} </h1> {% endfor %} models.py class CommentModel(models.Model): name = models.CharField(max_length=100) text = models.TextField(default='') dates = models.DateTimeField(auto_now=True) class Meta: ordering = ['-dates'] def __str__(self): return self.name -
'TemplateDoesNotExist': template loader appears to be searching non-existent routes
I'm receiving a TemplateDoesNotExist error when I click on a particular link, and I've noticed from the 'template-loader postmortem' that Django is searching incorrect and non-existent paths. I've recently moved half of the contents of a Django app called 'reviews' into another called 'accelerators'. My templates directory for each app follows the pattern: '"app name"/templates(folder)/"app name"/html templates'. Having moved the template into the accelerators app (and having updated my settings and urls), Django should be looking for the template via 'accelerators/templates/accelerators/accelerator_form.html', but according to the error message it's instead searching: 'accelerators/templates/reviews/accelerator_form.html'. I suspect this has something to do with the fact that I've just moved this template, alongside a number of other files, from the reviews app, but I can't figure out why this is happening. I've included my updated urls etc. below for reference. Base directory urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('', include('accounts.urls')), path('reviews/', include('reviews.urls')), path('accelerators/', include('accelerators.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) accelerators/urls.py from django.urls import path from .views import ( AcceleratorListView, accelerator_detail, accelerator_reviews, AcceleratorCreateView, AcceleratorUpdateView, AcceleratorDeleteView, ) from . import views urlpatterns = [ path('', AcceleratorListView.as_view(), name='accelerators'), path('<int:pk>/', views.accelerator_detail, name='accelerator_detail'), path('new/', AcceleratorCreateView.as_view(), name='accelerator_create'), path('<int:pk>/update/', AcceleratorUpdateView.as_view(), name='accelerator_update'), path('<int:pk>/delete/', AcceleratorDeleteView.as_view(), name='accelerator_delete'), path('<int:pk>/reviews/', views.accelerator_reviews, name='accelerator_reviews'), … -
Getting 1062, Duplicate entry for key unique constraint key, but there are no rows in database with the data for which unique constraint is added
We are getting 1062, “Duplicate entry" for Key "unique constraint key name" on saving Django Model, whereas there are no existing rows in database with the unique constrained data, for eg: we have added unique together for email and phone number fields, but when we try to save data we are getting duplicate entry. This is not happening all the time but in some cases, also this happens a lot when database cpu utilization is high , we are using Amazon AWS -
Django on Google App Engine: Cron Job Returning 400
I am trying to create a cron job on Google App Engine for my Django application deployed in the flexible environment. The cron job is deployed and view-able on the GCP dashboard but when it runs it shows "Failed". In the logs I can see that it is returning an HTTP 400 error, which is likely the the problem. I am able to go to the URL that the cron job requests by putting into my browser. Checking the logs, that shows an HTTP status 200. The error only occurs when I press the "Run Now" button on the Cron Jobs GCP dashboard, or when it runs automatically at the interval specified in cron.yaml. This is my first attempt at setting up a cron job on Google App Engine so forgive me if this is not correct. I'm treating this like any other view function in Django. The url is specified in urls.py, which routs to the view function. The view function runs my process and returns an HttpResponse. For troubleshooting purposes, I've removed any process from the view function and just return the HttpResponse (see code below); obviously, the intention is to put a process in the function once … -
How to convert SQL import to Django import?
I'm trying to import data from a database using Django. This was previously done using SQL, but now I'm trying to use Django instead of SQL. I'm not familiar with SQL really and am having trouble converting the SQL import to a Django one. So far, I've converted con = psycopg2.connect("dbname='mydatabase' user='mydatabase_reader' host='xxx.xxx.xx.xx' password='test'") to users = EventTransactions.objects.using('mydatabase').filter('profitcenter_id'=profitcenter_id, 'actualdatetime'=date).values('') but that's as far as I've gotten. Right now, I'm working on using the for loop to grab information for each day. def handle(self, *args, **options): r = redis.Redis(host=REDIS_HOST, db=REDIS_DB) memberships = MEM_MAP_INV.keys() start_date = datetime.datetime.strptime(options['start_date'],'%Y-%m-%d').date() end_date = datetime.datetime.strptime(options['end_date'],'%Y-%m-%d').date() profitcenter_id = options['profitcenter_id'] # number of days passed elapsed_days = (end_date - start_date).days dates = [start_date + datetime.timedelta(days=i) for i in range(elapsed_days)] con = psycopg2.connect("dbname='mydatabase' user='mydatabase_reader' host='xxx.xxx.xx.xx' password='test'") cur = con.cursor() for date in dates: counts = {} for m in memberships: membership = tuple(MEM_MAP_INV[m]) sql = cur.mogrify("""SELECT count(*) from eventtransactions WHERE profitcenter_id = %s AND date(actualdatetime) = %s""", (profitcenter_id, date)) # have to split into two cases due to how postgres queries for NULL values if m == 'n/a': sql = cur.mogrify(sql + """ AND membertype IS NULL""") else: sql = cur.mogrify(sql + """ AND membertype IN %s""",(membership,)) cur.execute(sql) count = … -
Is there anyways to store the data from the forms into variables without saving it to the database?
I'm trying to save the data inside a form into variables without saving it to the database but I don't know how. I'm not even sure if it's possible. -
Pass id parameter into imported class in Django
In Django I have a function based view responsible of printing the details (actually only the name) of all the registered users on a pdf file. def test_pdf(request, id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="My Users.pdf"' buffer = io.BytesIO() report = MyPrint(buffer, 'Letter', id) pdf = report.print_users() response.write(pdf) return response This function works because I imported in the views.py file a class I built in another file, responsible of drawing the pdf, MyPrint: from reportlab.lib.pagesizes import letter, A4 from reportlab.platypus import SimpleDocTemplate, Paragraph from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_CENTER from django.contrib.auth.models import User class MyPrint: def __init__(self, buffer, pagesize): self.buffer = buffer if pagesize == 'A4': self.pagesize = A4 elif pagesize == 'Letter': self.pagesize = letter self.width, self.height = self.pagesize def print_users(self): buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=72, pagesize=self.pagesize) # Our container for 'Flowable' objects elements = [] # A large collection of style sheets pre-made for us styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. users = User.objects.all() elements.append(Paragraph('My User Names', … -
validate and handle error to pass meaningful status back to client
I am using graphene-django instead of rest api(rest framework). I am working on user registration. In the rest framework, validation was done in serializers part but when using graphene how do i validate and handle error for passing meaningful status to client? Here is the registration code class Register(graphene.Mutation): class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) user = graphene.Field(UserQuery) success = graphene.Boolean() errors = graphene.List(graphene.String) @staticmethod def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: user = User.objects.create(email=email) user.set_password(password) user.is_active = False user.full_clean() user.save() return Register(success=True, user=user) except ValidationError as e: import pdb pdb.set_trace() return Register(success=False, errors=[e]) return Register(success=False, errors=['password', 'password is not matching']) one example can be validation for if user with email already exists