Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import a CSV to my Django Models
I need help in order to upload a CSV to my models. I saw that there are some other questions, but they are old, or written in 2.7 and doesn't make no sense. These are my models. class Ofac_Sdn(models.Model): number = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=200, null=True) b_i = models.CharField(max_length=250, null=True) programe= models.CharField(max_length=250, null=True) last_name= models.CharField(max_length=250, null=True) more_info = models.CharField(max_length=250, null=True) vessel_call_sign = models.CharField(max_length=250, null=True) vessel_type= models.CharField(max_length=250, null=True) vessel_dwt = models.IntegerField(blank=True, null=True) tonnage = models.IntegerField(blank=True, null=True) vessel_flag = models.CharField(max_length=250, null=True) vessel_owner= models.CharField(max_length=250, null=True) dob_aka= models.CharField(max_length=250, null=True) This is the model of a row from my CSV: 36,AEROCARIBBEAN AIRLINES,-0- ,CUBA,-0- ,-0- ,-0- ,-0- ,-0- ,-0- ,-0- ,-0- I have tried until now this example, but i receive an error saying: ModuleNotFoundError: No module named 'settings' If someone could help, I would owe you a lot as i am stuck here! Thank you! import csv, sys, os project_dir = "/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/" sys.path.append(project_dir) os.environ['DJANGO_SETTINGS_MODULE']='settings' import django django.setup() from ofac_sdn.models import Ofac_Sdn data = csv.reader(open('/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/sdn.csv')) #,delimiter="|") #data = csv.reader(open('/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/sdn2.csv'), dialect='excel-tab') for row in data: if row[0] !="Number": post = Ofac_Sdn() post.number = row[0] post.name = row[1] post.b_i=row[2] post.programe=row[3] post.more_info=row[4] post.vessel_call_sign=row[5] post.vessel_type=row[6] post.vessel_dwt=row[7] post.tonnage=row[8] post.vessel_flag=row[9] post.vessel_owner=row[10] post.dob_aka=row[11] post.save() -
Accessing django database from python script
I'm trying to access django app db from within python script. So far what i did is: import os import django from django.db import models os.environ.setdefault("DJANGO_SETTINGS_MODULE", "m_site.settings") django.setup() from django.apps import apps ap=apps.get_model('py','Post') q=ap.objects.all() for a in q: print(a.title) There is application in django called 'py' where i have many posts ( models.py -> class Post(models.Model) ). I would like to habe possibility to access and update this db from python script. So far script above works fine, I can insert, update or query but it looks like it is separated db and not db from django 'py' application. Am I doing something wrong or missing something ? Any help would be very appreciated. Regards -
Non-deterministic results when testing django haystack with elasticsearch
I am functional testing results returned by django-haystack with elasticsearch. I'm having different results when running a test. Sometimes the test pass, sometimes it doesn't. I can't figure out why this happens. My test class first creates entries in the test database, and then call the manage.py rebuild_index, using StaticLiveServerTestCase setUp method. In the end I call manage.py clear_index. I won't go to reproduce here all django code for search indexes, _text.txt's because the django-haystack/elasticsearch code is working. I'm wondering if it's a problem of synchronization between the database entries created and the call to rebuild_index. Basically, in my tests I do this class SearchTest(FunctionalTest): def setUp(self): super(SearchTest, self).setUp() # this make the entries in database self.rebuild_index() def tearDown(self): super(SearchTest, self).tearDown() call_command('clear_index', interactive=False) So, what could be happening? -
Django Rest Framework object with relationship
How do I find an object with relationship and how to save an object in relationship with Django Rest Framework? I looked in the documentation and found something similar to this class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'profile') class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('nome_empresa', 'cnpj') -
Amazon S3: Creating a route alias for a Django app
I have a Django App running on Heroku and I'm using Amazon S3 to store and serve static assets. I'm also using it to store media files. When sending a link to a file to a user it generates it like this: https://s3-eu-west-1.amazonaws.com:443/my-bucket-name/path/to/file.pdf I would prefer it if it looks like the file is stored on my domain, so making it accessible from www.mysite.com/path/to/file.pdf Is this possible? I'm thinking if I use something like files.mysite.com/path/to/file.pdf it may be possible? Alternatively I will have to set up a redirect. -
Django Rest Framework permission on a Foreign key item
I have two models that have a relationship like so: class ManuscriptItem(models.Model): """Represents a single manuscript's content""" author = models.ForeignKey('accounts_api.UserProfile', on_delete=models.CASCADE) title = models.CharField(max_length=255) content = models.CharField(max_length=99999999) def __str__(self): """Django uses when it needs to convert the object to a string""" return str(self.id) class ManuscriptLibrary(models.Model): """Represents a single manuscript's library""" manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE) bookmarks = models.CharField(max_length=99999999) history = models.CharField(max_length=99999999) def __str__(self): """Django uses when it needs to convert the object to a string""" return str(self.manuscript) I want to only let a ManuscriptItem Author be able to assign a single ManuscriptLibrary to that ManuscriptItem. The following are some of what I have attempted without any success: class PostOwnManuscriptLibrary(permissions.BasePermission): """Allow users to update their own manuscripts libraries.""" def has_object_permission(self, request, view, obj): return obj.manuscript.author.id == request.user.id Result: Everyone can write to any ManuscriptItem that they are not an author of. class PostOwnManuscriptLibrary(permissions.BasePermission): def has_permission(self, request, view): manuscript = ManuscriptLibrary.objects.filter(manuscript__author=request.user.id).exists() return manuscript Results: No one has any permissions, not even authors of their own manuscript. The relevant API endpoint views are like so: class ManuscriptViewSet(viewsets.ModelViewSet): """Handles creating, reading and updating items.""" authentication_classes = (TokenAuthentication,) serializer_class = serializers.ManuscriptItemSerializer permission_classes = (permissions.PostOwnManuscript, IsAuthenticated,) def perform_create(self, serializer): """Sets the user profile to the logged in … -
Jquery not working on button click
I am sending an ajax request to my server using Jquery. But my code doesn't sense the button click. My code seems to be fine. I don't know where I am going wrong. I am using Django template engine. I included the jquery script in my script block. In order check whether my button click is sensed I used an alert in button click event handler. But I did not get alert message. My code: {% extends 'base.html' %} {% block script %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> {% endblock script %} {% block content %} <div class="row" style="padding-left: 2%;padding-top:1%;"> <div class="col-md-9"> <h2>BookMyHotel</h2> </div> {% if name %} <div class="col-md-3"> <a href="{% url 'admin' %}" > {{ name }}</a> | <a href="{% url 'office_logout' %}" class="btn btn-primary" >Log out</a><br/><br/> </div> {% endif %} </div> <div class="container" style="margin-left: 4%"> <form class="form-group" name="form1" id="form1" method="post" style="padding-top: 1%" action = "{% url 'update_employee' %}"> {% csrf_token %} <h3>Update employee</h3> {% if message %} <b id="message" style="color: red">{{ message }}</b> {% endif %} <br/> <div class="form-group row"> <label class="control-label col-sm-2">Hotel id</label> <label id="hotel_id" class="control-label">bmh-{{ hotel_id }}</label> </div> <div class="form-group row"> <label class="control-label col-sm-2">Hotel name</label> <label id="hotel_name" class="control-label">{{ hotel_name }}</label> </div> <div class="form-group row"> <label class="control-label col-sm-2">Employee ID</label> … -
Celerybeat does not start in detach mode
I have django 1.11.4 app and use celery 4.1.0 for background periodic tasks. Celery was daemonized according to documentation and was working fine until... I don't know what happened, basically. It suddenly got broken. When I execute /etc/init.d/celerybeat start it writes following exception to /var/log/celery/beat.log and halts: [2017-09-04 18:33:38,485: INFO/MainProcess] beat: Starting... [2017-09-04 18:33:38,485: INFO/MainProcess] Writing entries... [2017-09-04 18:33:38,486: CRITICAL/MainProcess] beat raised exception <class 'django.db.utils.InterfaceError'>: InterfaceError ("(0, '')",) Traceback (most recent call last): File "/home/hikesadmin/.local/lib/python3.4/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'scheduler' Here is the full log: https://pastebin.com/92iraMCL I've remove all my tasks and retained simple celery.py tasks file: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') import django import pymysql pymysql.install_as_MySQLdb() django.setup() from celery import Celery app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task def gogo(): print("GOGO") print(123123123) But celerybeat still does not work. It prints "123123123" and after that halts with same exception. I've researched deeper and figured out that the problem is in the "--detach" modifier. When I launch it without it, it works: /usr/local/bin/celery beat --app=hike_engine -S django -f /var/log/celery/beat.g -l INFO --workdir=/home/hikesadmin/engine --pidfile=/var/run/celery/beat.pid When I add "--detach", celery goes broken. Please help me to trace and fix the problem. … -
Login with Email code error
How are you ? I do not know why I cannot manage to get my login working.. this is my views.py code : def candidate_login(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email,password=password) if user: if user.is_active & user.check_password(password): login(request,user) return HttpResponseRedirect(reverse('index')) else: HttpResponse("Account not active, please contact Admin") else: print("Someone tried to login and failed") return HttpResponse("Invalid login detailed supplied!") else: return render(request,'candidate_login.html',{}) When I try to login I get the error message : "Invalid login detailed supplied! Could you please help me to make it work ? Thk you very much Raphael -
Form field drop down list based on logged in user
How can I change the options available in a ModelForm dropdown list based on the logged in user? Example below uses a hard coded value (2). How can I pass in the logged in User's user_id? Thank you. models.py class Route(models.Model): owner = models.ForeignKey(User) ... class Driver(models.Model): owner = models.ForeignKey(User) .... views.py class DriverCreate(CreateView): model = Driver form_class = DriverCreateForm success_url = reverse_lazy('driver_list') template_name = 'driver_create_form.html' form.py class DriverCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['usual_route'].queryset = Route.objects.filter(user = 2) -
django 1.11.4 : django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I'm learning how to web programing with django framework and i got this error message when i try to create an instance of my 'Artist' from my app models. i use python 3.6 version and django 1.11.4 version can you please help me thanks. File "<stdin>", line 1, in <module> File ".\app\models.py", line 9, in <module> class Artist(models.Model): File "C:\Users\kadjo\documents\visual studio 2015\Projects\DatabaseFun\DatabaseFun\env\lib\site-packages\django\db\models\base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\kadjo\documents\visual studio 2015\Projects\DatabaseFun\DatabaseFun\env\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "C:\Users\kadjo\documents\visual studio 2015\Projects\DatabaseFun\DatabaseFun\env\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Django: method not allowed (POST)
I have models for classrooms and students, and I'm using a form to select a classroom to show a list of students. However, when I submit the form on block_list.html and try to go to the view for the student list in random_list.html, I get a method not allowed (POST). block_list.html: TESTt <form action="{% url 'classroom:random' %}" method="post"> {% csrf_token %} <select name="class_block"> {% for room in class_list %} <option value={{ room.id }}>{{ room.get_course_block_display }}</option> {% endfor %} </select> <input type="submit" value="submit" /> </form> random_list.html: {% for s in object_list %} <ul> <li>{{ s.nickname }}</li> </ul> {% endfor %} urls.py: app_name = "classroom" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^submitted', views.submitted, name='submitted'), url(r'^classup/$', create_classroom_view, name='classroom'), url(r'^block/$', views.block, name='block'), url(r'^random/$', list_random_view, name='random'), # url(r'^(?P<pk>[0-9]+)/$', detail_classroom_view, name='random'), ] views.py: class RandomListView(ListView): model = Student template_name = 'classroom/random_list.html' def get_context_data(self, **kwargs): context = super(RandomListView, self).get_context_data(**kwargs) students = Student.objects.all() # students = Student.objects.filter(classroom__course_block = '24') print (students) context['students'] = students return context list_random_view = RandomListView.as_view() def block(request): class_list = Classroom.objects.all() template = loader.get_template('classroom/block_list.html') context ={ 'class_list' : class_list, } return HttpResponse(template.render(context, request)) models.py: class Classroom(models.Model): COURSE_NAME = ( ('MA8', 'Math 8'), ('SC10', 'Science 10'), ('PH11', 'Physics 11'), ('PH12', 'Physics 12'), ) BLOCK_NUMBER = ( … -
Django dynamic url
I trying to open content inside poster using dynamic url, but i am facing problem my code is for simple web page containing some movie posters and when i click on a poster new template in new page should open which will show information of this poster. but whenever i click on a poster same template(index.html) opens in new page instead of page.html eg 127.0.0.1:8000/home is web page with all posters and i clicked on poster1 with id=1 then in new page 127.0.0.1/home/1 will open but it is still index.html with all posters not page.html in which content of poster1 id=1 is stored. Here is my code homepage/models.py from django.db import models class Poster(models.Model): poster_name = models.CharField(max_length=20) poster_img = models.FileField(upload_to="poster_image/") def __str__(self): return self.poster_name class Poster_page(models.Model): poster = models.ForeignKey(Poster, default= 1) poster_name = models.CharField(max_length=20) poster_img = models.FileField() poster_details = models.TextField() homepage/views.py from django.shortcuts import render_to_response from .models import Poster, Poster_page def poster(request): pos = Poster.objects.all() return render_to_response('index.html', {'pos':pos}) def poster_page(request, id=1): poster_pg = Poster_page.objects.all() return render_to_response('page.html', {'poster_pg':poster_pg}) homepage.url from django.conf.urls import url from.views import poster, poster_page urlpatterns = [ url(r'^',poster), url(r'^home/(?P<id>/d+)/$', poster_page), ] poster.url from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import … -
Django python 3 or 2?
I'm following the tutorial on Django provided here: https://docs.djangoproject.com/en/1.11/intro/tutorial01/ . All of the python calls in the command line in the tutorial look like this: python <something> <maybe something else> Does this mean that this particular tutorial of Django rests on Python2? -
NoReverseMatch at /stocks/5/
Here is my urls.py: urlpatterns=[ url(r'^login/$', views.loginview, name='login'), url(r'logout/$', views.logoutview, name='logout'), url(r'signup/$', views.signup, name='signup'), url(r'^stocks/(?P<pk>[0-9])/$', views.successful_login, name='successful_login'), url(r'^buystocks/(?P<pk>[0-9])/(?P<sn>[A-Z])/buy/$', views.buy, name='buy') ] Here is my a snippet from the template: <form method="post" action="{% url 'buy' pk=user.id sn=stock.stock_name %}" > And this is the error I am getting: NoReverseMatch at /stocks/5/ Reverse for 'buy' with keyword arguments '{u'pk': 5, u'sn': u'HDFC'}' not found. 1 pattern(s) tried: ['buystocks/(?P<pk>[0-9])/(?P<sn>[A-Z])/buy/$'] -
start send and receive messages in Django websockets
a have a Django chat application using web sockets and channels,the wecbokect connection is establish as you can see here: [mansard@web569 src]$ python3.5 manage.py runserver 22783 Performing system checks... Django version 1.11, using settings 'chatbot.settings' 2017-09-04 16:53:05,478 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-04 16:53:05,479 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-04 16:53:05,479 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-04 16:53:05,480 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-09-04 16:53:05,480 - INFO - server - Using busy-loop synchronous mode on channel layer 2017-09-04 16:53:05,480 - INFO - server - Listening on endpoint tcp:port=22783:interface=127.0.0.1 [2017/09/04 16:54:09] WebSocket HANDSHAKING /webscok/ [127.0.0.1:42846] [2017/09/04 16:54:09] WebSocket CONNECT /webscok/ [127.0.0.1:42846] But , when i want to start chatting nothing is happening where the message should be received to the other user and the Error Console doesn’t show any error!? I think it should be the IP address because http://127.0.0.1:22783/ and having the channel layer on in memory. chat.js: $(window).load(function() { $messages.mCustomScrollbar(); var ws_path = "/Pchat/webscok/"; var socket = new WebSocket("ws://" + window.location.host + ws_path); socket.onmessage = function(e) { … -
Is there a better way to get and display data from a related object aside from creating a dictionary?
I have two models with one having a foreign key to the other as such: Models: class WhoAmI(models.Model): name = models.CharField(max_length=200) company = models.CharField(max_length=200) def __str__(self): return self.name class SolarClient(models.Model): name = models.CharField(max_length=200) client_owner = models.ForeignKey(WhoAmI, on_delete=models.CASCADE, related_name='solarclients') addr = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) email = models.EmailField() I am trying to simply display an html table showing each client a salesperson has, with the salesperson listed first with a table of clients below their name. The only way I could figure out how to do this was to create a dictionary using the code shown below. class Homeowners(DetailView): def get(self, request, **kwargs): salespersons = WhoAmI.objects.all() homeowners = SolarClient.objects.all().order_by("client_owner") #the name 'objects' is the Manager rangers = {} for e in salespersons: k = salespersons.get(id = e.id) v = k.solarclients.all() rangers[k] = v return render(request, 'homeowners.html', {'homeowners': homeowners, 'salespersons': salespersons, 'rangers': rangers }) I then iterate over the dictionary using: {% for key, values in rangers.items %} ... display salesperson {% if values %} {% for v in values %} .... display clients {% endfor %} {% else %} ... display "No Clients" {% endif %} {% endfor %} Is there a more efficient way to do this? … -
How change django restframework JSONRenderer charset
I am using django restframework to show my old data but inside my json are "Felipe Niño Arango" this because my data is in other charset how i can change the JSONRenderer charset -
javascript/jquery: creating a list of all option elements's text in a select tag
I'm working on the Django web development platform, so I use some of the django template language in creating my menu. My task is simple, but it's been a while since I've worked with js and I'm not sure what I'm doing wrong right now I just need to create a list of strings for each option element's text or the string for its value attribute. But right now, nothing seems to be getting iterated over... The select tag <div id="keywordCollection"> <select id="#allKeywords"> {% for keyword in keywords %} <option value="{{ keyword }}">{{ keyword }}</option> {% endfor %} </select> Javascript (note that this is inline script in the html file for this web page and it appears immediately after the above.) <script> var collection = [] $("#allkeywords option").each( function() { //This never begins running. console.log("ADDING"); collection.push($(this).value); }); $(function(){ var collection = []; var keywords = $("#allKeywords option"); for(var i=0; i<keywords.length; i++) { // This doesn't ever begin running, keywords.length == 0. kw = keyword[i]; console.log(kw); } $("#allKeywords option").each( function() { //this doesn't ever begin running. collection.push($(this).value); }); .... //irrelevant code that I cut out. }); </script> So none of my loops ever begin. At this point you might be wondering … -
How to run .py file on Django?
Need Help!!! I am trying to include file which imports numpy and uses transpose() or .T. When i run it stops at transpose. When weights updated, trying to incoperate with django on website running and calling neural_network function: Link to py file https://github.com/stmorgan/pythonNNexample/blob/master/PythonNNExampleFromSirajology.py i did make a function for the loop and included everything under it and passing and an array for input and output.like this: def neural_network(a=np.array, y=np.array): np.random.seed(1) def nonlin(x, deriv=False) if(deriv==True): return (x*(1-x)) return 1/(1+np.exp(-x)) syn0 = 2*np.random.random((3,4)) - 1 # 3x4 matrix of weights ((2 inputs + 1 bias) x 4 nodes in the hidden layer) syn1 = 2*np.random.random((4,1)) - 1 for j in range(60000): # Calculate forward through the network. l0 = X l1 = nonlin(np.dot(l0, syn0)) l2 = nonlin(np.dot(l1, syn1)) # Back propagation of errors using the chain rule. l2_error = y - l2 if(j % 10000) == 0: # Only print the error every 10000 steps, to save time and limit the amount of output. print("Error: " + str(np.mean(np.abs(l2_error)))) l2_delta = l2_error*nonlin(l2, deriv=True) l1_error = l2_delta.dot(syn1.T) l1_delta = l1_error * nonlin(l1,deriv=True) #update weights (no learning rate term) syn1 += l1.T.dot(l2_delta) syn0 += l0.T.dot(l1_delta) print("Output after training") print(l2) Need Help!!! -
Is there any way to make a Django app with REAL TIME STREAMING PROTOCOL
please don't report my question I couldn't find answer to this anywhere that's why I had to come here I'm creating a social networking app at a big scale and I wanna implement Live streaming like Instagram does. (With django) any recommendations what to do -
Load comments dynamically in django using jquery ajax
I want to load all the comments of a particular article when a user clicks on the corresponding comments link. I want to do this with Jquery Ajax without refreshing the page but not able to achieve my motive. I have shared my idea over here. If this is not the relevant method than please suggest me another approach. //articles/all_articles.html <div class="infinite-container"> <button onclick="topFunction()" id="myBtn" title="Go to top">Top</button> {% for article in all_articles %} <div class="infinite-item"> <ul id="posts_ul"> {% include 'articles/indivisual_article.html' with article=article %} </ul> </div> {% endfor %} </div> //articles/indivisual_articles.html <a href="#" style="text-decoration: none;" class="comment" id="allcomments" value="{{article.id}}"> <span class="glyphicon glyphicon-comment"></span> {% trans 'Comment' %} (<span class="comment-count">{{article.comments }}</span>) </a><br> <ol class="clearfix"> {% comment %} Place holder to load feed comments {% endcomment %} </ol> <scripts type='text/javascript'> $('#allcomments').on("click",function(){ var myvar= $(this).attr("value"); var $el1= $(this); var $p1= $el1.parent(); var $list= $p1.find(".clearfix"); $.ajax( url: '/articles/comment/', type: 'POST', data:{post_id: myvar}, dataType:'json', success: function(response) { queryset= .parseJSON(response); for(i=0; i<(queryset.count); i++){ value=response[i].comment $list.html(<li>"{{value}}"= + value</li>).load() }); }); </scripts> //views.py @login_required def comment(request): if request.is_ajax(): article_id= request.POST.get('post_id') article = Article.objects.get(id=article_id) comment=ArticleComment.objects.filter(post=article) response=serializers.serialize('json', list(comment), fields=('comment')) return HttpResponse(response, mimetype='application/json') //models.py class Article(models.Model): title=models.CharField(max_length=250) post=models.TextField(max_length=4000) create_user=models.ForeignKey(User) class ArticleComment(models.Model): post = models.ForeignKey(Article) comment=models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User) //urls.py urlpatterns= … -
Django and Ajax issue with validate data
My forms at Django project send with POST method( using AJAX) some data like name, surname, and message. At my views.py I try validate it to store at my DB. views.py def create(request): if request.method == 'POST': name = request.POST['name'] surname = request.POST['surname'] message = request.POST['message'] if len(name) == 1 and len(surname) == 1 and len(message) == 1: Create.objects.create( name=name, surname=surname, message=message, ) return redirect('board:table') else: return redirect('index:index') else: return redirect('index:index') Issue: redirect not working. Why? 1# Example input: name = a , surname = a , message = a Output: All right -> stored at DB 2# Example input: name = aaa , surname = aaa , message = aaa Output: Wrong data and dont stored at DB -> but return redirect not working. Thanks in advance! -
How to receive Django post_save signal on AJAX query?
I use AJAX request to create an order, also I have a post_save signal that should be executed after the order will save. Whether is it possible to receive this post_save signal on an AJAX request?.. because I don't get aything, the signal handler is ignored =| -
Change grouping of an specific exception in sentry (django)
I use raven with my django web application and i want to prevent an exception from excessive grouping as described in documentations here while preserving default behavior for other exceptions. More concretely I have a code snippet like this somewhere in my app: raise Exception('Nothing done for catalog #' + str(catalog_id)) in sentry i see exceptions for different catalogs grouped together because it rolls them up based on stack-traces. As i understood from docs i should use something like: client.captureException(fingerprint=['{{ default }}', str(catalog_id)]) but i don't know where in my code it should be used.