Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add Facebook style notifications to django blog?
I made a django blog where different users can post their stuff now I want to make a mechanism allowing the user to be notified if someone liked his/her post or commented etc. What is the best way to go about doing that?(any documentation would be appreciated) -
Django redirect not working when I submit my form
My redirect for my login page is not working correctly when I submit a form. def login_page(request): form = LoginForm(request.POST or None) context = { 'form': form, } print(request.user.is_authenticated) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) if user is not None: print(request.user.is_authenticated) login(request, user) # Redirect to a success page. return redirect("login") else: # Return an 'invalid login' error message. print("Error") return render(request, "content/login.html", context) I am expecting it to redirect to same page and print an output that lets me know the authentication worked. But this is what actually happens.. https://i.imgur.com/pFJ5QJH.png Any idea as to what is going on? -
Mypy - Django custom user form gives 'name is not defined'
Mypy is not happy with the following custom user form (sub class). forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('email', 'username',) Mypy throws the following error: Mypy found 1 error: Name 'UserCreationForm.Meta' is not defined What can I do to prevent this error? I am new to Mypy and I can't find the solution in the documentation. Thanks in advance for your help! (PyCharm, Python 3.7, Django 2.2) -
Why audio scroll controler doesn't work? django | ckeditor | html5audio
See my problem: https://drive.google.com/file/d/1fdbiceEX90q_Q9VVmPXnT94jDT05I7I9/view I use ckeditor 4 / django 2. Plugin: html5audio -
Viewing the result videos of the Machine Learning model on the browser which I can also download, that are stored in different media-storage folder
I have a machine learning model which is capable of doing some video analytics and then finally stores the output videos in a separate folder. I want to run the model every time I upload a new video which goes into a media-storage folder in the project. After the analysis is completed I want to run that result video in the browser and also give a download video option which fetches the video from the media-storage-2 folder where the model will store the result videos. I don't know how to do it. Kindly note that I am developing a Django website and I want the result videos to be displayed and downloaded from there itself. -
Problem with django-RESTframework-Tutorial
I'm trying to get familiar with django-RESTframeworks, therefore I started the official tutorial, to create a Test-API. https://www.django-rest-framework.org/tutorial/quickstart/#quickstart When finally starting the API on my Windows via [CMD] "pyhon manage.py runserver", I get an error code on the command line, which you will see below. I also want to add, that unfortunately, there is some ambiguity in the descriptions in the tutorial, at least from the viewpoint of a beginner, i.e. it's not always certain whether the corresponding code in the tutorial needs to be added in a module or replace all or part of the code in the modules. Therefore, I tried implementing the directions of the tutorial in various ways, always with the same end result. I'm running the code in a virtual env, where i've installed Django 1.11., so there shouldn't be an issue with different Django versions. C:\Users\Rolimar\projects\djREST_tut>workon djresttut (djresttut) C:\Users\Rolimar\projects\djREST_tut>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x0000000004CBF978> Traceback (most recent call last): File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\registry.py", line 81, in … -
How to add selected checkbox options to a models table
I am using django for my web app. I have checkbox options of currency that if selected are to be saved into a models table so that a value can be calculated on submit and used for viewing history. The first part I'm stuck on, is getting the selected checkbox of options from 'curNamelist' into an array called 'curName' to be saved into the models table called 'Currency'. Are my variable defined correctly? The second part is to calculate the currencies values. How can I use these selected currency options to calculate the respective amounts/values using a python script which returns to html template and saves into the curValue column of the 'Currency'table onclick of submit *The currency table is defined in models.py *The curnamelist is from another models.py table just listing the various currencies * In views.py the relevant tables are sent in context to the html template *The html template has the checkbox options and the submit button which calls js. This code is done in Javascript document.getElementById('results').addEventListener('click', function(){ html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>'; return new Promise(function (resolve, reject) { var checkElements = document.getElementsByClassName('ch'); Currency = []; for(var i =0; i< curNamelist.length; i++){ if (checkElements[i].checked) { for (i in curNamelist) … -
How to add background image in django-cms?
I'm trying to set editable background image of header on my site built using Django CMS. Tried instructions from Using django-cms, how can I allow the user to specify a background image , but still got "background-image: url('')" in my resulting HTML code. Here is code that I add to try to add backgroung image: context_processors.py in root of project: from cms.models.pluginmodel import CMSPlugin def cover_image(request): page = request.current_page if page: cover_image_plugin = CMSPlugin.objects.filter( placeholder__page=page, placeholder__slot='cover_image', plugin_type='FilerImagePlugin', ).first() if cover_image_plugin: return {'cover': cover_image_plugin.filerimage.image} #return {'cover': cover_image_plugin.get_plugin_instance()[0]} return {} End of settings.py: TEMPLATES[0]['OPTIONS']['context_processors'].append('context_processors.cover_image') base.html: ... {% placeholder "cover_image" %} <header class="masthead" style="background-image: url('{{ cover.url|urlencode }}')"> ... Could anybody help me to fix it and to make background image work? -
Exclude Object while .values_list if multiple value
In my model I have a value 'type_name': class FooModel(models.Model): type_name = models.CharField(max_length=30) In my Views.py I want to generate a QuerySet with these type_name-inputs from the DB, but it shouldn't have multiple time of the same value in it. I tried: FooModel.objects.all().values_list('type_name', flat=True) and get <QuerySet ['X', 'X', 'X', 'Y']> But what I need is: <QuerySet ['X', 'Y']> -
How to return specific info in tuple from Django Queryset
I have a simple model with a tuple that is returning info as such below: class Store(models.Model): STORE_BRAND = ( ('nike', 'Nike'), ('adidas', 'Adidas'), ('puma', 'Puma'), ) online_store = models.CharField(unique=True, max_length=255, choices=STORE_BRAND) def __str__(self): return self.online_store I'm trying to return the store name so I can use it in a conditional statement in a context processor. store_brand = Store.objects.get(online_store='nike') Works fine, returns <Store: nike> Now i'm trying to use it in a conditional statement and it keeps returning false: >>> store_brand == 'nike' False What am I doing wrong? -
Es posible combinar la consulta en el filter 'filter?name__icontains=pr&enabled=true'
Estoy haciendo una filtro para StockType que me deje filtra por nombre y que sean activos o inactivos pero no consigo ese resultado Lo probé pero no logro obtener el dato que sea solo activo o inactivo, pero me funciona bien para el campo name Algún Consejo para este tipo de filtrado? me seria de mucha ayuda! class StockTypetFilter(django_filters.FilterSet): class Meta: model = StockType fields = { #isnull, icontains, iexact 'name': ['icontains'], 'enabled': ['exact'] } class FilterView(generics.ListAPIView): queryset = StockType.objects.order_by('-id').all() serializer_class = StockTypeSerializers filter_class = StockTypetFilter pagination_class = StandardResultsSetPagination permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser] #En la url tengo de esta manera re_path(r'^stock-types/filter?$', FilterView.as_view(), name='stocks-types-filter'), Al probar la api desde el postman api/stock-types/filter?name__icontains=pr&enabled__icontains=true { "count": 2, "next": null, "previous": null, "results": [ { "id": 3, "created_by": "meli", "updated_by": "meli", "create_date": "2019-04-14T15:35:44.246486", "update_date": "2019-04-14T17:26:55.018930", "enabled": true, "name": "PRUEBA TEST" }, { "id": 2, "created_by": "meli", "updated_by": "meli", "create_date": "2019-04-14T15:15:18.956902", "update_date": "2019-04-14T16:05:04.047478", "enabled": false, "name": "COMPRAS" } ] } -
Persisting django channels groups when deploying to production using multiple server instances
I am deploying my django application that uses web sockets (django channels 2) to production. Using load balancer and two application instances with nginx/gunicorn has been working fine so far but I am wondering about the scalability of the websockets part. How can I build scalable web sockets architecture that will share the django channels groups among different server instances? I am using websockets for the live chat functionality so I have to make sure that users added to a specific group will be able to send/receive message from all other users in the same chat room no matter to which server instance the load balancer will point them. My first thought was to simply use a separate remote server just for redis but I am aware that the vertical scalability will eventually come to an end. What happens when I will need to scale redis servers horizontally? I've been already using the gunicorn + daphne setup but only with low/dev-testing traffic. I have not tried scaling django channels horizontally yet. -
How to pass two different arguments in a single function in django?
Python newbie here, I am trying to create a web-app where shippers can post their truck-loads on sale and accept bids from transporters, and the transporters can post their bids on loads. I have a list view function in my views.py, where a shipper can see all the bids posted by different suppliers, and then he can 'assign' one supplier for that post-load. For that I created this function which takes 2 arguments : the quiz.id (which is the unique primary key of the post-load) and the supplier's ID. urls.py path('confirm/<int:pk>/', teachers.ConfirmRFQ, name='ConfirmRFQ'), views.py @login_required def ConfirmRFQ (request, pk,bi): quiz = Quiz.objects.get(pk=pk) bid = Bid.objects.get(pk=bi) quiz.status = 'Assigned' bid.confirmed = 'Assigned' quiz.save() bid.save() return redirect('teachers:quiz_change_list') The function call in template: <a href="{% url 'teachers:ConfirmRFQ' quiz.pk %}" class="btn btn-primary">Assign</a> Is there something wrong here ? Can I not pass two arguments as such ? Because I keep getting the NoReverseMatch at /teachers/quiz/13/results/ Reverse for 'ConfirmRFQ' with arguments '(13, 33)' not found. 1 pattern(s) tried: ['teachers/confirm/(?P[0-9]+)/$'] error. Not sure if model is necassary here, but here it is: models.py class Quiz(models.Model): bid_status_choices = (('Active', 'Active'), ('Assigned', 'Assigned'), ('Dispatched', 'Dispatched'), ('Delayed', 'Delayed'), ('Delivered', 'Delivered')) mtypes =(('Fragile','Fragile'),('Non-Fragile','Non-Fragile')) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') name = … -
Providing "resource" argument to CloudLoggingHandler class does't work
Providing "resource" argument to CloudLoggingHandler class does't work, that is, it cannot logging to stackdriver. If I comment "resource" out, it works fine. I also try a simple python script that doesn't run in Django, it works fine too. This actually my Django LOGGING handlers settings: 'handlers': { 'stderr': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'name': "name", 'resource': Resource( type="container", labels={ ... }, ), 'client': google.cloud.logging.Client() }, }, No resource, No problem: 'handlers': { 'stderr': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'name': "name", 'client': google.cloud.logging.Client() }, }, A simple script works too: import logging import google.cloud.logging # Don't conflict with standard logging from google.cloud.logging.handlers import CloudLoggingHandler, setup_logging from google.cloud.logging.resource import Resource client = google.cloud.logging.Client() logging.getLogger().setLevel(logging.INFO) # defaults to WARN res = Resource( type="container", labels={ ... }, ) handler = CloudLoggingHandler(client, name='name', resource=res) setup_logging(handler) logging.error('logging!') I use google-cloud-logging version is 1.10.0. Can someone give some suggestions about debug stackdriver logging? -
Sending model updates from db to clients with WSGI
What is the most lightweight way to notify clients of changes to a model table they are viewing? I've used Django Rest Framework to set up an API that serves a templated table of items to clients, and allows them to change buyers on the fly. Currently, I use a recurring jQuery AJAX request with a setTimeout for 2 seconds. This sends a ton of requests and data even when there are no changes, and the webpage size keeps growing. I've had to disable caching as some users might have IE11. I started looking for a way to push the updates to the clients and started exploring Django Channels and Server-Sent-Events. Django Channels Built the demo chat app Very fast Websockets are supported by all my target browsers Seems like overkill for what I'm trying to achieve. Lots of configuration Requires Redis or some other datastore I don't really need the two way communication My app is hosted on Pythonanywhere, which doesn't allow ASGI and doesn't seem to have any plans to do so (1, 2). Server Sent Events Very little information on how to configure this for Django No native support in IE11 or Edge, but there are polyfills … -
How to store checkbox values in databse using django
With this code i want to store multiple courses to the student table.But this code is not working.Neither it throws any error neither saves any data.The main problem is while clicking submit button the submit button does not perform any action at all.It does not load the submit button.How can i solve this?? models.py class Course(models.Model): title = models.CharField(max_length=250) basic_price = models.CharField(max_length=100) advanced_price = models.CharField(max_length=100) basic_duration = models.CharField(max_length=50) advanced_duration = models.CharField(max_length=50) def __str__(self): return self.title class Student(models.Model): name = models.CharField(max_length=100) course = models.ManyToManyField(Course) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateField() def __str__(self): return self.name views.py def addstudent(request): courses = Course.objects.all() if request.method == 'POST': form = AddStudentForm(request.POST,request.FILES) if form.is_valid(): student = form.save() student.save() # student.course.set(courses) messages.success(request, 'student saved.') return redirect('students:add_student') else: return HttpResponse(form.errors) else: form = AddStudentForm() return render(request,'students/add_student.html',{'form':form,'courses':courses}) forms.py class AddStudentForm(forms.ModelForm): course = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Student fields = ['name','course','email','address','phone','image','joined_date'] add_student.html <form action="{% url 'students:add_student' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <h5>Full Name <span class="text-danger">*</span></h5> <div class="controls"> <input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div> </div> <div class="form-group"> <h5>Courses <span class="text-danger">*</span></h5> <div class="controls"> {% for course in courses %} <input name ="course" type="checkbox" … -
External CSS not working in HTML in Python project
I replaced internal CSS in base.html with an external CSS file. In base.html there is a menu which links to different HTML pages. When I click on any menu item, the page is loading but not CSS. I tried using <link> tag in homealter.html but it doesn't work. base.html <link href="../static/css/base_style.css" rel="stylesheet" type="text/css"> <div class="menu"> <table> <tr> {% with request.resolver_match.url_name as url_name %} <td class="{% if url_name == 'home' %}active{% endif %}"><a href="{% url 'home' %}">Resource Wise Analysis</a></td> <td class="{% if url_name == 'homealter' %}active{% endif %}"><a href="{% url 'homealter' %}">Land Distance Analysis</a></td> <td class="{% if url_name == 'graphsone' %}active{% endif %}"><a href="{% url 'graphsone' %}">Water Type Based Analysis</a></td> <td class="{% if url_name == 'graphstwo' %}active{% endif %}"><a href="{% url 'graphstwo' %}">Land Distance Analysis</a></td> <td><a href="{% url 'logout' %}">Logout</a></td> {% endwith %} </tr> </table> </div> {% block mains %} {% endblock %} </body> homealter.html {% extends 'base.html' %} {% block mains %} {% load staticfiles %} <div class="contnt"> <table> <tr> <th>Land Size</th> <th>Land Distances Count</th> <!--<th>Details</th>--> </tr> {% for index, row in yeye.iterrows %} <tr> <td><p>{{index}}</p></td> <td>{{row.Distance}}</td> <!--<td><a href="{% url 'yearwise' index %}">View Details</a></td>--> {% endfor %} </tr> </table> <img src="{% static 'images/im1.jpg' %}"> </div> {% endblock %} It worked … -
How can I add model in database Mysql in django without problems and with encoding utf-8?
I have project on Django with Mysql. Databases was imported from another project by using command "python manage.py inspectdb" Everything worked correctly with english and russian symbols. I added easy model and migrated it. This model workes correctly only with english symbols, but with russian symbols doesn't work Error: "Exception Type: OperationalError Exception Value: (1366, "Incorrect string value: '\xD0\x94\xD0\xB8\xD0\xBC...' for column 'title' at row 1")" I think that is the problem with encoding. Mysql encoding was latin1 and changed to utf-8, but error was not resolved. mysql> SHOW VARIABLES LIKE 'character_set%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.01 sec) mysql> SHOW VARIABLES LIKE 'collation%'; +----------------------+-----------------+ | Variable_name | Value | +----------------------+-----------------+ | collation_connection | utf8_general_ci | | collation_database | utf8_unicode_ci | | collation_server | utf8_unicode_ci | +----------------------+-----------------+ 3 rows in set (0.00 sec) PLease help me to use russian symbols in this model. Another question: this model was migrated, I can see it in … -
the command "python manage.py startapp (nameofapp)"for creating app doesn't work, can't figure out why
i've created a test(basic) django website and can't modify by creating apps by using commands such as "python manage.py startapp appname" or "admin-py startapp appname". Im learning it through the online youtube lesson, and the author creates the app that way. Once he has typed this command, the appname appears in pycharm, but in my case, it doesn't. "python manage.py startapp appname" or "admin-py startapp appname" "python manage.py startapp appname" or "admin-py startapp appname" as i mentioned the expectation was the appearance of the appname in pycharm, and it didn't -
Django templating language syntax for navbar notifications
I am trying to use the Django templating language in my Django Channels 2.1.2 project to render out any unread chat messages in a Facebook-style notification popup. The list of unread chatmessages (in their respective threads) and the correct number of notifications are not displaying because I am having trouble with the correct syntax. {{ notification|length }} is displaying the instance of the notification model (which is always 1 for the logged-in user). I think it needs to display the notification_chat field (if the boolean field is set to unread), which is the number of unread messages. Please correct me if I'm wrong. This is how the front end looks. When you click the message icon, the notification disappears. I have a Notification model class Notification(models.Model): notification_user = models.ForeignKey(User, on_delete=models.CASCADE) notification_chat = models.ForeignKey(ChatMessage, on_delete=models.CASCADE) notification_read = models.BooleanField(default=False) def __str__(self): return f'{self.id}' navbar.html {% if user.is_authenticated %} <li id="notification_li" class="nav-item"> <a class="nav-link" href="#" id="notificationLink"> <i class="fas fa-envelope"></i>&nbsp; Inbox</a> <span id="notification_id">{{ notification|length }}</span> <div id="notificationContainer"> <div id="notificationTitle">Notifications</div> <div id="notificationsBody" class="notifications"> {{ notification.notification_chat }} </div> <div id="notificationFooter"><a href="{% url 'chat:inbox' %}">See All</a></div> </div> </li> base.html <script> $(document).ready(function() { $("#notificationLink").click(function() { $("#notificationContainer").fadeToggle(300); $("#notification_id").fadeOut("slow"); return false; }); //Document Click hiding the popup $(document).click(function() { $("#notificationContainer").hide(); … -
Gunicorn nginx server works perfectly but after some time shows 502 Bad Gateway
My server is working perfectly when I restart gunicorn but when time passes it shows me 502 bad gateway for some pages ( not all) gunicorn config : import multiprocessing bind = 'unix:/tmp/gunicorn.sock' workers = multiprocessing.cpu_count() * 2 + 1 reload = True daemon = True accesslog = './access.log' errorlog = './error.log' gunicorn error log : [2019-04-20 12:36:44 +0000] [19797] [INFO] Worker exiting (pid: 19797) [2019-04-20 14:36:44 +0200] [21460] [INFO] Booting worker with pid: 21460 [2019-04-20 14:36:44 +0200] [21462] [INFO] Booting worker with pid: 21462 [2019-04-20 14:37:12 +0200] [14828] [CRITICAL] WORKER TIMEOUT (pid:21452) [2019-04-20 12:37:12 +0000] [21452] [INFO] Worker exiting (pid: 21452) [2019-04-20 14:37:12 +0200] [21477] [INFO] Booting worker with pid: 21477 [2019-04-20 14:38:12 +0200] [14828] [CRITICAL] WORKER TIMEOUT (pid:21462) [2019-04-20 12:38:12 +0000] [21462] [INFO] Worker exiting (pid: 21462) [2019-04-20 14:38:12 +0200] [21494] [INFO] Booting worker with pid: 21494 [2019-04-20 14:38:16 +0200] [14828] [CRITICAL] WORKER TIMEOUT (pid:21477) [2019-04-20 12:38:16 +0000] [21477] [INFO] Worker exiting (pid: 21477) [2019-04-20 14:38:17 +0200] [21498] [INFO] Booting worker with pid: 21498 [2019-04-20 14:38:24 +0200] [14828] [CRITICAL] WORKER TIMEOUT (pid:21460) [2019-04-20 12:38:24 +0000] [21460] [INFO] Worker exiting (pid: 21460) [2019-04-20 14:38:24 +0200] [21500] [INFO] Booting worker with pid: 21500 nginx config : upstream your-gunicorn { server … -
How to display detail objects after filtering their primary object in django?
I am working on an app that can create teams, Players,I am now on displaying player objects which are connected by a foreign key teams that displays relevant players to their team.But the problem I am getting is when the player objects are displayed in detail view,all the players get displayed while that specific player objects should be displayed.Please help me to solve the problem. here,s the html {% include 'games_app/base.html' %} {% block body_block %} <div> {% for players in play.teams.all %} <h1>Players :<strong>{{players.player_name}}</strong></h1> <h1>Players-age :<strong>{{players.player_age}}</strong></h1> <h1>Players-form :<strong>{{players.player_form}}</strong></h1> <h1>Players-over :<strong>{{players.over}}</strong></h1> <h1>Players-batting :<strong>{{players.batting}}</strong></h1> <a href="{% url 'games_app:players_update' players.pk %}">Edit Player</a></br> <a href="{% url 'games_app:players_delete' players.pk %}">Delete Player</a> {% endfor %} </div> {% endblock %} Here,s the views.py of detail players def Detail_Players(request,pk): model = models.Team.objects.get(pk=True) template_name = 'games_app/players_detail.html' return render( -
I have a problem with django-allauth linkedin signup
I tried to signup with the django-allauth linkedin module, but when the django-allauth callback call this URL: /accounts/social/signup/ and nothing is happening (it stuck on /accounts/social/signup/). But everything is okay with the Google module of django-allauth. I'm using Django 2.2 and django-allauth 0.39.1. My settings: SOCIALACCOUNT_PROVIDERS = { 'linkedin': { 'SCOPE': [ 'r_basicprofile', 'r_emailaddress' ], 'PROFILE_FIELDS': [ 'id', 'first-name', 'last-name', 'email-address', 'picture-url', 'public-profile-url', 'gender', 'birthday' ], 'HEADERS': { 'x-li-src': 'msdk' } } } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 ACCOUNT_LOGOUT_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/' AUTH_USER_MODEL = 'profile.CustomUSER' Actually, django-allauth should redirect to the home page. -
" local variable 'response' referenced before assignment " error in djnago
## while creating views 'add_car' method i tried to assign value to 'response' variable but it shows errors.If i type ' response =None ' the output i get is None from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json from .models import Car def index(request): response=json.dumps([{}]) return HttpResponse(response,content_type='text/json') def get_car(request,car_name): if request.method == 'GET': try: car=Car.objects.get(name=car_name) response=json.dumps([{'Car':car.name,'Top speed':car.top_speed}]) except: response=json.dumps([{'Error':'No car with that name'}]) return HttpResponse(response,content_type='text/json') @csrf_exempt def add_car(request): #response=None if request.method =='POST': payload=json.loads(request.body) car_name=payload['car_name'] top_speed=payload['top_speed'] car=Car(name=car_name,top_speed=top_speed) try: car.save() response=json.dumps([{'Success':'Car added succesfully'}]) except: response=json.dumps([{'Error':'Car could not ne added'}]) return HttpResponse(response,content_type='text/json') -
Is there any way to avoid creation of new object while refereshing page in django?
i have a function which add question and answers to a model. When i submit it if form is valid, save it redirect it to another view which will display the questions and answers. Problem arrives when i reload that page, a another object will created again and displayed? how that possible? views.py for adding the question and answer if request.method == 'POST': form = FaqForm(request.POST) faq_formset = FaqFormset(request.POST ,prefix='faq_formset') if form.is_valid() and faq_formset.is_valid(): for ch in faq_formset: course = ch.cleaned_data.get('course') ques = ch.cleaned_data.get('ques') ans = ch.cleaned_data.get('ans') Faq( course=course, ques=ques, ans=ans, ).save() return faq(request) for displaying it: def faq(request): faq = Faq.objects.all() lms_faculty = request.session['lms_faculty'] context = { 'dash_title' : 'View FAQ', 'heading' : 'FAQ', 'lms_faculty' : lms_faculty, 'faq' : faq, } return render(request, 'lmsadmin/view_faq.html', context) views.py what i tried initially if request.method == 'POST': form = FaqForm(request.POST) faq_formset = FaqFormset(request.POST ,prefix='faq_formset') if form.is_valid() and faq_formset.is_valid(): for ch in faq_formset: course = ch.cleaned_data.get('course') ques = ch.cleaned_data.get('ques') ans = ch.cleaned_data.get('ans') Faq( course=course, ques=ques, ans=ans, ).save() faq = Faq.objects.all() lms_faculty = request.session['lms_faculty'] context = { 'dash_title' : 'View FAQ', 'heading' : 'FAQ', 'lms_faculty' : lms_faculty, 'faq' : faq, } return render(request, 'lmsadmin/view_faq.html', context) On reload the web page i don't want to …