Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Signup page always redirecting to login page even if there are errors during signup
I am working on a signup page for users. It is working fine except the process when there are errors in the form introduced. After hitting the signup button, the page redirects to login with a notification saying username or password mismatch. This is the notification introduced by me into login page if there are any errors. inside views.py def signup(request): if request.method=='POST': form =SignupForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: error=form.errors return render(request,'registration/signup.html',{'error':error}) #return redirect('signup',{'error':error}) else: form = SignupForm() return render(request,'registration/signup.html',{'form':form}) my template for signup.html is: {% extends 'blog/base.html' %} {% block content %} <h2>Sign up</h2> <form method="post" action="{% url 'login' %}"> {% csrf_token %} {% if form.errors %} <h1>Error {{error}}</h1> {{ error }} {% endif %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} path('signup/',views.signup,name='signup') path('accounts/login/',LoginView.as_view(), name='login') form for signup is: class SignupForm(UserCreationForm): first_name=forms.CharField(label="First Name",widget=forms.TextInput(attrs={'placeholder': 'First Name'})) last_name=forms.CharField(label='Last Name') #Removes the help_texts def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['password1'].help_text = None class Meta: model=User fields=('first_name','last_name','username','email','password1','password2') Why does this happen? How can I render the same signup page to user with extra information of showing errors . like **some_error** happened. Please fill out the form again. And why is this page redirecting to login page for … -
How to limit number of choices of a ManyToManyField to a specific number of choices
I am trying to build a multiple choice quizzes Django app. I have a model named Answer, and another model named Question. Here are the contents of Answer: class Answer(models.Model): text = models.CharField(max_length=255) and this is Question: class Question(BaseModel): correct_answer = models.ForeignKey('Answer', on_delete=models.CASCADE, related_name='correct_answers') other_answers = models.ManyToManyField('Answer') I want to limit the number of choices of other_answers in django-admin to 3 answers only. How to do that? Notes: I am ok with re-modeling my models. I will not use django-forms, I am only building an API for a mobile app. -
User matching query does not exist. and DoesNotExist at /messager/
The problem is that the code is written correctly to search for the user using his name, but the error is still visible, if I try to put it in the 'try' block, another error is caused. I tried to find a problem for a long time and looked at a lot of forums, but nothing helped, it’s interesting that this link doesn’t come into contact with the place where the error is caused, otherwise everything goes smoothly. The place where the error occurs. @login_required @lru_cache(maxsize=255) def showProfile(request, name): """Show user profile.""" user = User.objects.get(username=name) The place that is being called. @login_required @lru_cache(maxsize=255) def messager(request): """Show all user messages.""" render(request, 'instagrams/messager.html') I would like it to follow the transition to this template, and not an error, which, moreover, does not exist, because I tested the code in the 'manage.py shell' - there were no errors. -
Can't pass array into Django REST
I have a REST endpoint. When I access this endpoint through the DRF GUI, I can manually enter my data and it works successfully. My model looks like this: class Post(models.Model): title = models.CharField(max_length=100, null=False) content = HTMLField() created_at = models.DateField(auto_now_add=True) authors = models.ManyToManyField(User) My serializer and view looks like this: class CreatePostSerializer(CreateAPIView): serializer_class = PostSerializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'content', 'authors') When I actually try to submit my data through Ajax to the endpoint, like this: $.ajax({ type: 'POST', url: '/api/save-post/', data: { "csrfmiddlewaretoken": getCookie('csrftoken'), "title": "dasf", "desct": "dasf", "content": "fdasf", "authors": [1,2] }, success: function (msg) { console.log(msg); } }); I get an error that says: {"authors":["This list may not be empty."]} with a payload sending: title: dasf desct: dasf content: fdasf authors[]: 1 I've tried changing the contentType to application/json, I've tried almost everything but it seems like nothing is working. How can I make it so my endpoint understands what I'm sending? -
SAWarning: Unknown schema content:
What to do for this kind of warning and SAWarning: Unknown column definition ? How to rectify it? What changes are to be made in reflections.py? -
How to call a function before and after a function is called in django?
I have to check number of calls user has made to an function. I need to know what can be used i.e. Signal calls or logging. -
RuntimeError: Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS for Django OAuth Toolkit
I want to access the models that are used by Django OAUTH Toolkit so I can periodically delete old tokens from the database. I thought I'd just import them: from oauth2_provider.management.commands.cleartokens import Command from oauth2_provider.models import AccessToken Command.handle() However when I try to run this file in the command line I receive the following error: Traceback (most recent call last): File ".\db_cleanup.py", line 5, in <module> from oauth2_provider.models import AccessToken File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\models.py", line 178, in <module> class Application(AbstractApplication): File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\db\models\base.py", line 95, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class oauth2_provider.models.Application doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried adding oauth2_provider.models.Application to my installed apps in my settings file as well but to no avail: `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'oauth2_provider', 'oauth2_provider.models.Application', 'rest_framework', 'rest_framework.authtoken', 'graphene_django', 'corsheaders', ]` I added app_label to the Application class it mentions as well, but that does not work either. -
Built-in UserCreationForm throws "The two password fields didn't match" when passwords match. Django==2.2.2
I'm setting up user registration with built-in User model and UserCreationForm. Problem is that form validation fails when proper credentials are given. And I can't understand why? It looks like form.cleaned_data lacks 'password2' for some reason. I have the same code in other project on django==2.1 and there's no problem. from django.contrib.auth.forms import UserCreationForm from django.http import JsonResponse def register_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] return JsonResponse({'username': username, 'password': password}) else: return JsonResponse({ 'error': 'Form not valid', 'messages': form.error_messages, 'cleaned_data': form.cleaned_data, 'data': form.data, }) Expected: {'username': 'test', 'password': 'qwe'} Actual: () {"error": "Form not valid", "messages": {"password_mismatch": "The two password fields didn't match."}, "cleaned_data": {"username": "test", "password1": "qwe"}, "data": {"csrfmiddlewaretoken": "long string:)", "username": "test", "password1": "qwe", "password2": "qwe"}} -
Django Rest Framework get method
I have some problems with Django rest framework. I don't know basics but it's a small piece of code that I need to do. So I have api.py that looks like: from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .thisisfile import Thisisfile class ScraperAPI(generics.RetrieveAPIView): permission_classes = [ permissions.AllowAny, ] def get(self, request): return Response({ "name": Thisisfile(), "result": True, }) What I need to do here is, to get value (name for example) that I'm defining in the get request. So this name must be passed from this API file to Thisisfile(). And to get a response like. { "user": { "name": "here is the name" }, "result": true } This is how Thisisfile looks like from rest_framework.response import Response from rest_framework import serializers import json class Thisisfile(serializers.ModelSerializer): def getsomething(name): return Response({ "name": name, }) getsomething() So to finalize the question. How to grab this name in Thisisfile and return it as a json? I know this is a stupid code for someone who knows Python but I'm not really good at it. -
Some questions about rbca in django
I have a url like: http://127.0.0.1:8000/course/17, a course associated with a teacher user, but when I change the course id like: http://127.0.0.1:8000/course/22, the user also can see this course, but they don't have association. How could I solve this bug? -
How to use value returned by javascript in onsubmit of HTML form, in Django?
This is my HTML form. There is a Javascript code define in the head tag. Assuming that the Javascript code is valid. The Javascript function returns some modified form of password. <l1> <b>Add:</b> <form action="{% url 'Student:append' %}" onsubmit="return DoPlayfair(add_password.value,ABC.value,Key1.value,'E',DupLet.value)" method="POST"> {% csrf_token %} <input type="text" name="ABC" size="42" value="ABCDEFGHIKLMNOPQRSTUVWXYZ" readonly hidden> <input type="text" name="DupLet" size="2" value="J"readonly hidden> <input type="text" name="Key1" size="33"rreadonly hidden> <label for="add_n">Name:</label> <input type="text" name="add_name" id="add_n" value=""> <label for="add_p">Password:</label> <input type="PASSWORD" name="add_password" id="add_p" value=""> <br> <input type="submit" value="add"> </form> </l1> This is my Django code. def add(request): get_name = request.POST["add_name"] get_password = request.POST["add_password"] print(type(get_name),type(get_password)) s = Student(student_name=get_name,student_password=get_password) context = { "astudent":s } s.save() return render(request,"sms_2/add.html",context) I want to use that javascript changed password in this Django view. How to access it? -
style of Django template is ignored when set as ReactJS dangerouslySetInnerHTML value
My ultimate target is to come up with Print functionality. For some reason, HTML just HAS TO BE generated on the backend. So I have the following code: <div ref={el => (this.componentRef = el)} dangerouslySetInnerHTML={{__html: this.state.htmlToPrint}}> </div> For sake of simplicity, let's assume that the htmlToPrint is just <div style='background: red'></div> Now, the problem is this inline css is ignored. And the strangest think is that when run locally, everything is fine. But after being deployed, the red effect is gone away. I have read that dangerouslySetInnerHTML can have issues with style, but why do I experience the issue only on the remote server? Does it have to do something with nginx ? -
List not showing in html
Im trying to create a table in html but the list is not even working This is my site.html {% extends "blog/base.html" %} {% block content %} <h1>tab in my website</h1> <p>site info</p> {% if result_dict %} <ul> {% for i in result_dict %} <li> {{ forloop.counter }} - {{ i }}</li> {% endfor %} </ul> {% else %} <p>This is not working</p> {% endif %} {% endblock content %} This what what i have in my views.py def prtg(request, *args, **kwargs): response = requests.get("https://prtg.c3ntro.com/api/table.json?content=status=down&username=someuser&passhash=somehash&count=200000000") data = response.json() d = data result_list = [d for d in data['status%3Ddown'] if d['status'] == 'Down'] return render(request, 'blog/prtg.html', {'title':'PRTG'}, {'result_list': result_list}) When I open the page is not loading any information and well it's supposed to show at least the sensors that I'm filtering but nothing shows us, instead I get the message of the else statement "This is not working" What am I doing wrong? -
Django - Register custom values for sharing url
I want to add a share function. I want to register in a model what suffix it should have and later the builder should build a url from this (and of course redirect the user). Example: example.com/article/the-best-article should be converted into this: example.com/sU74?a (That's just an random id) Another example: example.com/poll/what-is-your-thought should be converted into this: example.com/sU74?p (The ids are the same but they are different models!) I want to register the suffix this way: class Poll(Model): # some fields @share.register def suffix(self): return "p" def share_builder(self): # return shared builder # this should return the short url I don't know if this is possible or not. Thanks for your help -
django-hijack fails with UserPassesTestMixin starting in Django 2.1.0
Apparently, starting with Django 2.1.0, django-hijack (version 2.1.10) seems to bug out when used with UserPassesTestMixin. It works fine when the test passes; when the test fails, I get a 403 Forbidden error rather than a redirect to login_url. Is this a bug? If so, how can I monkey patch the package to work with Django 2.1.0+? class MyView(UserPassesTestMixin, View): test_func = lambda self: False login_url = '/myurl/' def get(self, request): return HttpResponse('Hello world') [25/Jun/2019 13:03:29] "GET /hijack/username/someuser/ HTTP/1.1" 302 0 Forbidden (Permission denied): /myview/ Traceback (most recent call last): File "C:\Envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Envs\myenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Envs\myenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\program files\python36\Lib\contextlib.py", line 52, in inner return func(*args, **kwds) File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Envs\myenv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\mixins.py", line 108, in dispatch return self.handle_no_permission() File "C:\Envs\myenv\lib\site-packages\django\contrib\auth\mixins.py", line 43, in handle_no_permission raise PermissionDenied(self.get_permission_denied_message()) django.core.exceptions.PermissionDenied [25/Jun/2019 13:03:29] "GET /buy/ HTTP/1.1" 403 22 -
multiple objects to templates with render doesn't work
I have a problem I want to send more than one object to the same page on tamplate but happens with me Problem NoReverseMatch at / and Try reversing the order of the last 2 urls and stay problem path('', views.index, name='home'), path('', views.category_view, name='home'), boards=Board.objects.all() categorys=Category.objects.all() context = { 'boards':boards , 'categorys':categorys, } return render(request,'home.html',context=context) urlpatterns = [ path('', views.index, name='home'), path('track/<int:track_id>', views.record_view, name='track1'), path('boards/<int:id>', views.boards_topic, name='boards_topic'), ] -
How to add a serializer field in DRF for GET only not POST?
I am working on an existing DRF codebase and want to add a last_build field to return on a GET request only. I do NOT want this to affect anything to do with POST requests. I have created a method that returns the field I am looking for and have successfully tested that it returns the data I want, however I have not yet tested if this will affect existing POST requests. class JobSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True, max_length=150) product = ProductSerializer(many=False, required=True) platform = PlatformSerializer(many=False, required=True) stages = StageSerializer(many=True, required=False) last_build = serializers.SerializerMethodField() def get_last_build(self, name): latest_build = JobExecution.manager.filter(job__name=name.name) return latest_build.last().build_id class Meta: model = Job fields = ("name", "product", "platform", "stages", "last_build") validators = [ UniqueTogetherValidator( queryset=Job.manager.all(), fields=("name", "platform", "product") ) ] def create(self, validated_data): # Create objects from data try: product_data = validated_data.pop("product", None) if product_data: ps = ProductSerializer() validated_data["product"] = ps.create(product_data) else: logger.exception("product is not valid") platform_data = validated_data.pop("platform", None) if platform_data: ps = PlatformSerializer() validated_data["platform"] = ps.create(platform_data) else: logger.exception("platform is not valid") stage_data = validated_data.pop("stages", []) stages = [] the_job = Job.manager.get_or_create(**validated_data)[0] if stage_data: for stage_data in stage_data: ss = StageSerializer() stage_data["job"] = the_job the_stage = ss.create(stage_data) return the_job except Exception as e: logger.exception(e) raise e … -
How to update the page in Django by pressing a pushbutton
I made an application using django and raspberry, and I wanted it when I push the pushbutton, django requests the page through the url. Can someone help me ? -
Using a dropdown box to display a picture in Django
I am building a Django website and I want to have a page where there is a dropdown box (which is made from a variable in one of my models) and the selection from that dropdown box alters the display down below. For example: I have a model that contains the variables Name & Value I want to have in a dropdown box all the values for Name, and for the corresponding Value to be displayed when a Name is selected. Using views.py I can send the values of Name to create the dropdown box. But I don't know how to display the corresponding value when the user selects a Name. This seems like it probably has a very simple answer, but I am struggling to find an example for this on SO or Django tutorials. (Likely because I don't know the correct terminology to use). Could someone offer some direction please? -
my main.css is not rendering,I am using multiple entry points webpack.config
my main.css is not rendering,I am using multiple entry point webpack.config.js file % load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta name='apple-mobile-web-app-capable' content='yes' /> <meta itemprop='name' content='TableGrabber Dashboard'> {% render_bundle "main" "css" %} {% render_bundle "vendors~main" "css" %} <title> {{ title }} </title> I expect my both app.js file will render and the routes written in them can be run by putting the URL in the browser -
Pviz Html file shows correct graphic when locally opened but on server no graphic appears
I am creating a website and want to show a image based on the protein sequence that a user inputs. I am using the genentech Pviz GitHub to help me create the graphic and have copied an example from their website. It work completely fine and shows the correct image and graphic when I open it within PyCharm but when I open it as a template in views.py it does not. <html> <head> <title>pViz.js different track heights</title> <link rel="stylesheet" type="text/css" href="deps/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="deps/pviz-core.css"> <script src="deps/pviz-bundle.min.js"></script> <!-- just a few lines of javscript to decorate the page --> <script src="examples-utils.js"></script> <style type="text/css" media="screen" class='example'> g.feature rect.coverage_bar.psm_coverage { fill: blue; fill-opacity: 0.4; } g.feature rect.coverage_bar.psm_no_coverage { fill: red; fill-opacity: 0.4; } </style> </head> <body class="container"> <div class="row"> <h2>pViz with different track heights example</h2> </div> <div id="main" class="row"></div> <div class="row"> <h3>Comments</h3> </div> <script class="example"> var pviz = this.pviz; var seq = 'MELAALCRWGLLLALLPPGAASTQVCTGTDMKLRLPASPETHLDMLRHLYQGCQVVQGNLELTYLPTNAS'; var seqEntry = new pviz.SeqEntry({ sequence : seq }); /** * attach a track height ratio to the category (1 is the default) */ pviz.FeatureDisplayer.trackHeightPerCategoryType.psms = 0.2; pviz.FeatureDisplayer.trackHeightPerCategoryType.psms_coverage = 3; pviz.FeatureDisplayer.setStrikeoutCategory('oups'); new pviz.SeqEntryAnnotInteractiveView({ model : seqEntry, el : '#main' }).render(); pviz.FeatureDisplayer.setCustomHandler(['psm_coverage', 'psm_no_coverage'], { appender : function(viewport, svgGroup, features, type) … -
Create multiple shipments and packages in FedEx using a single API call
I have a requirement to create multiple shipments in FedEx with multiple packages. Here is my scenario In a single button click, I want create 10 shipments and each shipment have 5 packages each. As per the example I found, I have to call a FedEx API each time for each shipment and package. That means, In my case, I have to make 50(5 * 10) API calls one by one and this makes the system really slow. Do we have any alternate method to make a single API call to create multiple shipments and create shipments with multiple packages? Thanks in advance -
Select link menu with go button
This is a dropdown selection box where user can choose page and then click the submit button to go to that page Im using Django 2.2, don't know how to make the button go to the selected link gradovi.html {% block content %} <div class="row"> <form> <div class="input-field"> <select> <option value="" disabled selected>Izaberite grad</option> {% for grad in gradovi %} <option value="{{grad.grad_slug}}">{{grad.grad_ime}}</option> {% endfor %} </select> <label>Materialize Select</label> </div> <button class="btn waves-effect waves-light" type="submit" name="select"> <i class="material-icons right">send</i> </button> </form> </div> {% endblock %} -
Library that can track API usage for Django Rest Framework
So I created a basic api for a basic website, and now I want to be able to track which people are using it and what are they using it for. Any recommendations? (I've tried DRF-Tracking, but it's not logging anything. Help with that would also solve my problem) -
Django translations - underscore as alias of gettext for list items - UnboundLocalError
I'm struggling trying to understand why the _ used as an alias for gettext is not working for translating items of a list. I am using Python 3 and importing gettext this way: from django.utils.translation import gettext as _ The snippet of code failing is this: def register(request): request_data = {k: v for k, v in request.data.items()} if "username" not in request_data: raise ValidationError({"username": [_("The username field must be included and cannot be empty.")]}) When sending a request to this view I get the following error: UnboundLocalError at /v1/register/ local variable '_' referenced before assignment On the other hand, a snippet of code in the same file that is not failing is the following: def collaborator_workspace_list_email_recovery(request): username = request.data.get("username") if not username: raise ValidationError(_("Username must be provided in the request body!")) How can I use _ for translating items of a list (as for the example above)?