Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
need a work-around to achieve multiple return values of "Case" in django
I have model like this: class Record(models): borrower = ForeignKey(User) lender = ForeignKey(User) borrower_state = IntegerField(choices=in_following_comment) # [1 for awaiting,2 agreed,3 refused] lender_state = IntegerField(choices=in_comment_above) i am given 3 flags, on which my query will be base: namely, "awaiting for me" namely, "done" namely, "reject by others" which means, "awaiting for me" indicates :this user's state is awaiting and the counterpart is not refused. "done" indicates both parties are of "done" state "reject by others" indicates: this user either is of "awaiting for me" or of "done", the counterpart is of state "reject" my code is like this, i know each case return a single value in database await = Agreement.STATE_AWAIT done = Agreement.STATE_DONE neg = Agreement.STATE_NEGATIVE mapping = { 'awaiting_me': [(await, await), (await, done)], # state intervals of self and counterpart 'awaiting_others': [(done, done), (await, await)], 'finished': [(done, done), (done, done)], 'refused': [(await, neg), (neg, neg)], } user = self.request.user if value in mapping: new_qs = qs.filter( Q(receiver_state__gte=Case( When(receiver=user, then=mapping[value][0][0]), default=mapping[value][0][1] )), Q(receiver_state__lte=Case( When(receiver=user, then=mapping[value][0][1]), default=mapping[value][1][1] )), Q(owner_state__gte=Case( When(owner=user, then=mapping[value][0][0]), default=mapping[value][0][1] )), Q(owner_state__lte=Case( When(owner=user, then=mapping[value][0][1]), default=mapping[value][1][1] )), ) return new_qs else: return qs -
How to make Django 'listen' for file uploads to FTP server
I have a Django application that manages orders from a Shopify-based webshop. Whenever someone orders something that needs shipping, my app will create a file and place it on the carriers ftp-server. When the order has been shipped, the carrier will upload a new file to the ftp-server with the relevant information about the shipment. How can I make Django automatically 'listen' for these file uploads? I have looked a bit at Django Channels, but it doesn't say anything about ftp interaction. Can this be done and how? -
Clarity regarding flow for integrating ADFS authentication in a Django backend
I'm working on an app which has a Django backend and React frontend. I need to authenticate a user from Active Directory using ADFS. What I already have with me is federationmetadata.xml and Federation URL. Question 1: Is there a detailed explanation on how can I set up my application to read the metadata that is shared already? What essential details should the application know for integrating ADFS authentication? Question 2: to implement what is explained in the 1st link, I'm using django-auth-adfs package. What is CA Bundle in the same context? Also, I'm assuming this package will not help me in validation of credentials. Is it correct? Question 3: If the above assumption is correct, I would need to validate the token and in that case I would be using some package like python3-saml. In such context, how does my app connect to django-auth-adfs and python3-saml and what do each of them have to offer? I'm having trouble joining the dots here. Any help would be useful!! I've gone through multiple sources for the same (some listed): Best way to Integrate ADFS 2.0 authentication in a Django application https://github.com/onelogin/python3-saml -
Django : How to give parameters to {% url %} tag in javascript function which will be used in FOR loop?
I try to make a button with a javascript "location.href" property in Django ListView templates. {% for item in object_list %} <div class="clear_float"> <h2><a href = "{% url 'photo:album_detail' item.id %}">{{ item.title }}</a></h2> &emsp;<b><i>{{ item.description }}</i></b> <p style="display:inline" class="editbutton"> <b><button onclick="photoAdd()">Add Photo</button></b> {% if item.author == request.user %} <b><button onclick="albumEdit()">Edit</button></b> <b><button onclick="albumDelete()">Delete</button></b> {% endif %} </p> </div> {% endfor %} And albumEdit() and albumDelete() is coded like below. function albumEdit(){ location.href="{% url 'photo:album_edit object.id %}"; } function albumDelete(){ location.href="{% url 'photo:album_delete object.id %}"; } {% url 'photo:album_edit object.id %} returns "photo/object.id/edit/" The problem is, I guess, the ListView returns object_list so the javascript function is used in FOR loop with item object. I tried replacing object.id with item.id but it didn't work. So I also tried another way to give a argument to javascript function like below. <b><button onclick="albumEdit({% url 'photo:album_update' item.id %})">Edit</button></b> and javascript function albumEdit(arg){ var address = arg; location.href=encodeURI(address); } Cuz I don't know much about javascript, it also didn't work. I will be grateful for any advice and help. Thank you :D -
Authentication failed: `email` is not a recognized scope - social signup django
I am implementing django social signup according to this documentation I have successfully implemented linkedin , github and stackoverflow social signups.I need extra data from the profile informations.For that purpose i used scope SOCIAL_AUTH_STACKOVERFLOW_SCOPE = ['email'] But following error occured Authentication failed: `email` is not a recognized scope Anyone one tell me what are the scope fields we can as social signup with github , linkedin and stackoverflow? -
How can I count across several relationships in django
For a small project I have a registry of matches and results. Every match is between teams (could be a single player team), and has a winner. So I have Match and Team models, joined by a MatchTeam model. This looks like so (simplified) class Team(models.Model): ... class Match(models.Model): teams = ManyToManyField(Team, through='MatchTeam') ... class MatchTeam(models.Model): match = models.ForeignKey(Match, related_name='matchteams',) team = models.ForeignKey(Team) winner = models.NullBooleanField() ... Now I want to do some stats on the matches, starting with looking up who is the person that beats you the most. I'm not completely sure how to do this, at least, not efficiently. In SQL (just approximating here), I would mean something like this: SELECT their_matchteam.id, COUNT(*) as cnt FROM matchteam AS your_mt JOIN matchteam AS their_mt ON your_mt.match_id = their_mt.match_id WHERE your.matchteam.id IN <<:your teams>> your_matchteam.winner = false GROUP BY their_matchteam.team_id ORDER BY cnt DESC (this also needs a "their_mt is not your_mt" clause btw, but the concept is clear, right?) While I have not tested this as SQL, it's just to give an insight to what I'm looking for: I want to find this result via a Django aggregation. According to the manual I can annotate results with an … -
Adding an django-action that tests data on Logistic Regression Model and inserts output into model
I built a Multinomial Logistic Regression model using Pyspark. It classifies customers into three classes Silver, Gold and Platinum. The features are 'Age', 'Account_Type', 'Salary', 'Balance', 'Employer_Stability', 'Customer_Loyalty', 'Residential_Status' and 'Service_Level'* `from pyspark.ml.classification import LogisticRegression from pyspark.ml.evaluation import MulticlassClassificationEvaluator # initial Logistic Regression model lr = LogisticRegression(labelCol="label", featuresCol="features", maxIter=10) # Training model with Training Data lrModel = lr.fit(trainingData) # Make predictions. predict = lrModel.transform(testData) # Select example rows to display. predict.select("prediction", "label", "features").show(10) # Select (prediction, true label) and compute test error evaluator = MulticlassClassificationEvaluator( labelCol="label", predictionCol="prediction", metricName="accuracy") accuracy = evaluator.evaluate(predict) print("Test Error = %g " % (1.0 - accuracy)) print("The Accuracy = %g Percent" % (accuracy * 100))` In django, I have created models that display these features. Now, I would like to add an action that gets the features from the django-model and tests them in my classification model then assign either Silver, Gold, Platinum to the Service_Level field in my django-datatable. How do I connect pyspark to django and perform the above operation? PS: I am also using jupyter notebooks -
Multiple forms in one page update concrete block?
As you can see from the picture I have several forms in one page. Each of this form has there own block with list of comments. I am tring with AJAX/JQuery update block of comments after succesfull adding new comment by form. Lets say if user add comment by 3-d form AJAX need update 3-d comments block which is under 3-d form. Here below you can see my JS code. The problem is when I use the same id for all forms (task-comment-form) and the same id for all comments block (task-comments) works well only first form. When I submit second or third form it update first comment block. I think JS checks the document from top to bottom and finds the first match. When I use the same class for all forms and comment blocks it works wrong too. For example when I submit second form all 3 comment block updates. So how to associate a particular form with a specific comment block? JS: $(document).ready(function() { $('.submit').on("click", function() { event.preventDefault(); console.log(event.preventDefault()); var form = $(this).closest('form'); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#task-comments").html(data.html_task_comment); } else { $("#task-comment-form").html(data.html_task_comment_form); } } }); … -
NoReverseMatch at /series/ Reverse for '{'serial_slug': '', 'season_slug': 'Season_1', 'series_slug': 'Episode_1'}' i can get 'serial_slug'
I can not get "serial_slug", I think it's problematic in other models, I have 3 basic ones, in the "season" model I can not get all the URLs that I need, the URL goes of this type from the beginning "series / serial_name / This is the url for serial, followed by the url for the season, serials / serial_name / season_name / and in the "season" model I can not get the serial_services, since I do not have access through "ForeignKey" if I make access through "ForeignKey" to the " Then it will not be able to start as the series should be on the bottom, if it is rearranged in places with the model season, then the model "serial" will not be able to belong to the model "season" and also with the "Series" model, if I rearrange the models in places, then work There will not be, since they stand, the most optimal option, and you can not access the model " Series "through the model" Season "for obtaining URL series for the model" season " this is my url.py urlpatterns = [ url(r'^$', homeview, name='homeview'), # /series/ url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # … -
new style getargs format but argument is not a tuple error in python/django
I managed to get a list of information from a file to a list by: open_file = open(fileinfo, 'r') contents = open_file.readlines() for i in range(len(contents)): info_list.extend(contents[i].split()) I then assigned, y = info_list which worked when I call upon individual list values y[0] y[1] etc. However, when I try to draw a rectangle using PIL , 'dr.rectangle((y[i], y[i + 1], y[i + 2], y[i + 3]))' I get the error 'new style getargs format but argument is not a tuple' in my Django web page. am I missing out anything? -
django: sort rows based on number of column matching
I have a model:- class Userprofile(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL) education=models.models.CharField(max_length=20,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) occupation=models.CharField(max_length=20,blank=True,null=True) .... for a user profile (let's say: ('masters','India','student') I want to filter all the user profiles ordered by the number of fields it matches with the given user profile i.e first all 3 fields matching profiles then any 2 fields matching profiles and so on.Can anyone suggest a way to do this efficiently? -
Block tags in include django
The following template should be used for embedding of the share features: {% load static %} {% block head %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static 'css/shariff.css' %}" /> {% endblock %} <section id="share"> {% with url=request.build_absolute_uri %} <p><label>Share:<input type="text" value="{{ url }}" readonly /></label></p> <p><label>Embed:<input type="text" value="<iframe src=&quot;{{ url }}&quot;></iframe>" readonly /></label></p> {% endwith %} </section> {% block scripts %} {{ block.super }} <script src="{% static 'js/shariff.js' %}"></script> {% endblock %} It is included in the content block like this: {% include 'polls/share.html' with request=request question=question only %} But when I added the head and script block overrides, the template is not rendered anymore. How can this be fixed? -
uwsgi 1.0.4 logging File handle not release
i have an application for High requests count for django(1.3.1)+uwsgi(1.0.4), when i configure uwsgi with xml format: ”<log-maxsize>51200000</log-maxsize>“, log file will cut to small size automaticuwsgi.log.1485843562 uwsgi.log.1487389022 uwsgi.log.1488980345 uwsgi.log.1490664169,but all file's handle not released anyway, so disk was used as 100% cannot save another file anymore. -
how to get session data in django?
how to get session data in Django [category array] cat=[] for c in Categories.objects.all(): cat.append({"categoryName":c.categoryName,"cateId":c.id}) request.session['category'] =cat pprint(request.session['category']) output [{'cateId': 1L, 'categoryName': u'Single Grain'}, {'cateId': 2L, 'categoryName': u'Ready Mix'}] show in submanu { % for cc request.session['category'] %} <li role="presentation"> <a role="menuitem" tabindex="-1" href="/category/{{cc.cateId}}/">{{cc.categoryName}} </a></li> { % endfor % } -
how to create a time slot like zocdoc or practo or lybrate?
I want to create an appointment scheduler like zocdoc, practo or lybrate in python django. How do I display the frontend where users can book a specific time slot on a specific day? -
(django-queryset) get/remove first/last x entries efficiencly
Let's say I have a huge queryset - and my archive works with pages, for example, pages of a hundred entries. In my ListView I get passed on which page (1 to n) I am and how many entries per page. (Normally 100, but the user can change that.) I thought this should be done like this: for x in range(page-1): my_huge_qs.remove_first_entries(entries_per_page) #^ pseudo code. How can this be done? my_huge_qs.remove_any_entry_behind(entries_per_page) Can this made be better than with manual IDs? -
django webpack loader setting to load css
It works when I set up like below. I am using django-webpack-loader index.html {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Jayground</title> {% render_bundle 'main' 'css' %} </head> <body> <div id="react-app"></div> {% render_bundle 'main' 'js' %} </body> </html> Header.js import styles from './header.css'; export default class Header extends React.Component { render(){ <div className="header"> hello </div> } } webpack.config.js (I made styles.css separately and then load css file in html separately so that className="header" works.) config.plugins = config.plugins.concat([ new ExtractTextPlugin('styles.css'), ]); config.module.rules.push( { test: /\.css$/, use: ExtractTextPlugin.extract({ use: 'css-loader' }) } ) According to what I understood, code below should work too. If I don't separate css file by using ExtractTextWebpackPlugin, bundle js file have css information in it like this. exports.push([module.i, ".header {\r\n background-color: blue;\r\n}\r\n\r\n.extra {\r\n\tfont-size: 50;\r\n}", ""]); css should be loaded properly. Header.js import styles from './header.css'; export default class Header extends React.Component { render(){ <div className={styles.header}> hello </div> } } webpack.config.js config.module.rules.push( { test: /\.css$/, use: ['style-loader', 'css-loader'] } ) Do I miss something to work properly? -
how to save user inputs withou backeneds
I am just learning Django and web development in general and I was wondering if what I want to do is possible. I would like to write a Django quiz that saves the answers a user inputs without needing a backend. Is this possible?If it is not possible what is the simplest and easiest way I can do this. My template: {% extends "base.html" %} {% block title %}Exam Questions{% endblock %} {% block content %} {% if all_questions %} <form action="{% url 'save_answer' %}" method="post"> {% csrf_token %} {% for question in all_questions %} <h3>{{question.text }}</h3> <input type="hidden" name="exam_id" value="{{ question.exam.id }}"> <input type="hidden" name="question_id" value="{{ question.id }}"> <input type="hidden" value="{{question.answer_set.all}}" name="answers"> {% for answer in question.answer_set.all %} <p><input type="radio" name="answer" value="{{ answer.id }}">{{ answer.text }}</p> {% endfor %} {% endfor %} <input type="submit" value="Send"> </form> {% else %} <h2>No questions available</h2> {% endif %} {% endblock %} Now I would like to know how to save user answers without backends -
how to clear objects between wsgi runs?
I feel kinda lack of knowledge of threading theory... In my django project i create custom logging.handler and append it to some logger. All works fine but when django process next request and application create this logger again it already has appended handlers. I've solve this problem by check handlers list in logger creation procedure. But I still don't get how it happening. And have similar problem with an application which has xml-parser inside. This parser doesn't "clear memory" (?) between wsgi runs and keep some results from past. Only apache restart helps... Is there are a way to force django (python?) remove these kind of objects from thread(?)? How it actually works? -
UNIQUE constraint failed: music_playlist.owner_id
Users can register and login to my website. Users those who are currently logged in to my website could create their own playlist. But when the create button is submitted, it returned me this error: UNIQUE constraint failed: music_playlist.owner_id Here is my models.py : class Playlist(models.Model): name = models.CharField(max_length=200, null=False, blank=False,default='') owner = models.ForeignKey(User, unique=True,null=True) def __str__(self): return self.name @property def playlist_id(self): return self.id This is my views.py(where the error occurs): @login_required def create_playlist(request): form = PlaylistForm(request.POST or None) if form.is_valid(): data = form.cleaned_data playlist = form.save(commit=False) playlist.owner = request.user playlist.save() #playlist_name = form.cleaned_data['name'] context={ 'playlist':playlist, 'form':form, } return render(request, 'create_playlist.html', context) context = { "form": form, } return render(request, 'create_playlist.html', {'form': form,}) When the user goes to create_playlist.html, they could type the name of the playlist and click create button. I want the owner field of the playlist to be equal to the currently logged in user. You help is very much appreciated. -
the object has no attribute 'get_answers_list'
i am getting error in quiz app in views.py and forms.py. inheritance is done for quiz app and multichoice app. this my code link -
How to convert NoneType value from aggregate to float in Python?
I have a Django models.py file with a class defined as follows: class Cotizacion(models.Model): # Fields nombre = models.CharField(max_length=100) slug = extension_fields.AutoSlugField(populate_from='nombre', blank=True) fecha_vence = models.DateField(default=now) _subtotal = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, db_column='subtotal', default=0) _total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, db_column='total', default=0) _utilidad = models.DecimalField(max_digits=8, decimal_places=6, null=True, blank=True, db_column='utilidad', default=0) # utilidad = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) # total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) creado = models.DateTimeField(auto_now_add=True, editable=False) actualizado = models.DateTimeField(auto_now=True, editable=False) # Relationship Fields itinerario = models.ForeignKey(Itinerario, on_delete=CASCADE, verbose_name='itinerario') nivel_de_precio = models.ForeignKey(NivelDePrecio, verbose_name='nivel de precio', on_delete=models.PROTECT, null=True) class Meta: ordering = ('-id',) verbose_name = _('Cotización') verbose_name_plural = _('Cotizaciones') def __str__(self): return self.nombre def __unicode__(self): return u'%s' % self.nombre @property def subtotal(self): agregado = self.lineas.aggregate(subtotal=Sum('monto')) return agregado['subtotal'] @subtotal.setter def subtotal(self, value): self._subtotal = value @property def total(self): agregado = self.lineas.aggregate(total=Sum('total')) return format(math.ceil(agregado['total'] / redondeoLps) * redondeoLps, '.2f') # return math.ceil(agregado['total'] / redondeoLps) * redondeoLps @total.setter def total(self, value): self._total = value @property def utilidad(self): agregado1 = self.lineas.aggregate(costo=Sum('monto')) agregado2 = self.lineas.aggregate(precio=Sum('total')) precio = agregado2['precio'] precioRnd = math.ceil(precio / redondeoLps) * redondeoLps if agregado2['precio'] == 0: return 0 else: ganancia = round((precioRnd - agregado1['costo']) / precioRnd, 4) return ganancia @utilidad.setter def utilidad(self, value): self._utilidad = value def get_absolute_url(self): return reverse('transporte_cotizacion_detail', args=(self.slug,)) def … -
Why would redirecting from javascript back into a django request generate a clickjacking exception?
I'm trying to redirect from a javascript page back to django. my javascript uses window.location.replace(): d3.select("#cmd").on("click", function(){ // http://stackoverflow.com/a/506004/1079688 // similar behavior as an HTTP redirect window.location.replace("/djggApp/ggEditDoc"); this matches a pattern in urls.py: url(r'^ggEditDoc$', views.ggEditDoc, name='ggEditDoc'), then calling this method in views.py: def ggEditDoc(request): return (request, 'ggEdit_doc.html', Context({})) ggEdit_doc.html sits in the template directory along other similar pages. but this throws an exception: 'tuple' object has no attribute 'get' Exception Location: /Data/virtualenv/django/lib/python2.7/site-packages/django/middleware/clickjacking.py in process_response, line 32 looking there, it seems to have to do with the X-Frame-Options in the HTTP header. is there some way X-Frame-Options are/not being passed along correctly by this redirect, or ...? -
ImportError: cannot import name 'classproperty'
What is the solution of this error........ from django.utils.decorators import classproperty ImportError: cannot import name 'classproperty' Why this error shows. How can I solve this problem ? -
Django-Dashing Custom Widget HTML Location
I'm using the Django-Dashing framework (https://github.com/talpor/django-dashing), and I can't figure out where to place my HTML file for the custom widget that I am using. I have the following code in my dashboard.html file, which is being loaded properly. {% extends 'dashing/base.html' %} {% load staticfiles %} {% block stylesheets %} <link rel="stylesheet" href="{% static '../../static/widgets/timetables/timetables.css' %}"> <!--<link rel="stylesheet" href="{% static '../../../../static/css/analytics/widgets/timetables.css' %}">--> {% endblock %} {% block scripts %} <script type="text/javascript" src="{% static '../../static/widgets/timetables/timetables.js' %}"></script> <!--<script type="text/javascript" src="{% static '../../../../static/js/analytics/widgets/timetables.js' %}"></script>--> {% endblock %} {% block config_file %} <script type="text/javascript" src="{% static '../../static/dashing-config.js' %}"></script> <!--<script type="text/javascript" src="{% static '../../../../static/js/analytics/dashing-config.js' %}"></script>--> {% endblock %} I also believe I properly defined my TimetablesWidget class properly in widgets.py, and its corresponding JavaScript class name Timetables properly, as all of the data is being correctly fetched when the widget renders. I did a console.log statement to make sure that the data was being fetched properly, and it indeed is. However, it is not rendering correctly in the div on the screen, which makes me think that my timetables.html file is not actually being loaded. Based on where I defined my other paths, could someone let me know where I am supposed to put …