Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Angular PUT request: Multiple parameter
My model is as follows: class User_evaluation(models.Model): username = models.ForeignKey(User) year = models.CharField(max_length=4) subject_code = models.ForeignKey(Subject) name = models.CharField(max_length=50) weight = models.PositiveIntegerField() mark = models.PositiveIntegerField() is_taken = models.BooleanField() My API route file is as follows: router = DefaultRouter() router.register(prefix='user_evaluations', viewset=User_EvaluationsViewSet, base_name="user_evaluations") urlpatterns = router.urls I am trying update my django model above through the given route using DRF from angular JS using the following piece of code: marksApp.factory("UserEvaluations", ["$resource",function($resource) { return $resource( "api/v1/user_evaluations/", {}, { "update": {method: "PUT", headers:{ "Content-Type":"application/json" }} }, { stripTrailingSlashes:false } ); }]); The problem is that I am getting a 405 error with the following details: Request URL:http://localhost:8000/api/v1/user_evaluations/ Request Method:PUT Status Code:405 Method Not Allowed Remote Still learning DRF and would like to know if this is the best way to update an existing record. Point of Interest: The record that I need to update in this table needs to be identified by the following fields combined: username, year, subject_code, name. The fields to be updated are the mark and is_taken fields. -
Thumbnails are of different size - Django
Here the code for the index view of my Django app using the bootstrap thumbnails. But the thumbnails producing are of different size. How can I make them to the same size? {% extends 'eapp/base.html' %} {% block content %} {% for lt in lists %} <div class="row"> <div class="col-xs-6 col-md-3"> <div class="thumbnail"> {% if lt.image%} <img src="{{ lt.image.url }}" class="img-responsive"> {% endif %} <!img src="..." alt="..."> <div class="caption"> <h3><a href="{% url 'eapp:detail' lt.id %}">{{ lt.title}}</a><small> {{ lt.timestamp|timesince }} ago</small></h3> <p>{{ lt.content|linebreaks|truncatechars:120 }}</p> <p><a href="{% url 'eapp:detail' lt.id %}" class="btn btn-primary" role="button">View</a></p> </div> </div> </div> {% endfor %} {% endblock %} Thankyou. -
Django localisation - thousand separator
In settings.py I have : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True And in the django template I'm trying to do next : {% load l10n %} ..... ..... <div>{{ price|floatformat:0|localize }}</div> But the number that I see is still without separator : 9080. I tried to enable thousand_separator as follows : USE_THOUSAND_SEPARATOR = True THOUSAND_SEPARATOR = '.' But then is the separator (not dot, but comma) added to all id's that my site uses. Thus if I send an id=9800 to my view I get 9,800 and I get an error. I have read that I can use {{ value|unlocalize }} or {{ value|safe }}, but I do not want to do that for all my vars. Is there any better way to do that? Can I use thousand_separator only in one template for only one var? Thus, something like : {% load l10n %} ..... ..... <div>{{ price|floatformat:0|localize }}</div> -
Why do i get reverse match error in get_absolute_url method?- Django
views.py class ProfileView(DetailView): model = User template_name ="profile/profile_view.html" class ProfileEdit(UpdateView): model = User form_class = ProfileForm template_name="profile/profile_new.html" models.py #.... models def get_absolute_url(self): return reverse('user:user_profile', kwargs={ "slug": self.slug }) urls.py url(r'^(?P<slug>[\w.@+-]+)/edit/$', ProfileEdit.as_view(), name='profile_edit'), url(r'^(?P<slug>[\w.@+-]+)/$', ProfileView.as_view(), name='user_profile'), Reverse for 'user_profile' with arguments '()' and keyword arguments '{'slug': 'rahul'}' not found. 0 pattern(s) tried: [] I dont understand i get the correct slug value but what is the right way to pass it to the url patterns? -
Django Tables Link Column link to page with query
I have a Django table (Django Tables 2) with Link Column containing link to another page with another table with search form. So after click I get from: localhost:8000/stats/office/ to: localhost:8000/stats/office/workers/ However, I would like to filter data by search form in the table in the second page, so it would render only clicked office (e.g. "1" as in this query): localhost:8000/stats/office/workers/?action=submit&office=1&owner=&date_month=0&date_year=2016&submit=search my code looks like: #table.py office = tables.LinkColumn('stats:office-workers', verbose_name=_(u'Pobočka'), accessor='office') #urls.py url(r'^stats/office/$', login_required(permission_required('view_office', raise_exception=True)(OfficeSummarizeList.as_view())), name='office'), url(r'^stats/office/workers/$', login_required(permission_required('view_worker', raise_exception=True)(WorkerSummarizeList.as_view())), name='broker'), I tried many things but I was not able to pass the parameter 'office' to the view, thank you very much for your help. -
update() in classserializer not taking input from postman
I have two Models Country and Address, accordingly i have created two serializer CountrySerializer and AddressSerializer class CountrySerializer(serializers.ModelSerializer): country = serializers.ReadOnlyField(source='country.name') class Meta: model = Country fields = '__all__' class AddressSerializer(serializers.ModelSerializer): country = CountrySerializer(many=True) class Meta: model = Address fields = '__all__' Now i want to update AddressSerializer, when i use PUT method in Postman with field country it doesnt take an input instead updates existing country and not new input, can anyone help me in this ? thanks in advance -
Python and Django - standalone executable to run without dependency
I am developing a Python web-application with Django and don't want to force my customers to install Django and modules. PyInstaller is the tool that I am using to convert Python scripts into linux executables which works fine as a desktop application. But I do not have any idea how to package my web application that uses Django without any dependencies (Python and Django installation) So, is there a way to redistribute Django without any Python dependencies and if possible convert them to standalone executable? -
Read uploaded file with csv.reader
Task: read uploaded file to check structure. My test upload file has 5 lines with header and about 20-30 columns. Encoding is ISO-8859-1 Sounds simple but it drives me slowly into insanity. The only working solution at the moment is detour about Models: file = request.FILES.getlist('job_file', None)[0] newdoc = models.Jobs(job_file=file) newdoc.save() with codecs.open(newdoc.job_file.name, "r", encoding='iso-8859-1') as fp: file_content = list(csv.reader(fp, delimiter=';', quotechar='"')) Dirty, crazy and far from acceptable Non working solutions: 1: file_content = list(csv.reader(file, delimiter=';', quotechar='"')) print(file_content) >>>_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) 2: file_content = list(csv.reader(file.open('r'), delimiter=';', quotechar='"')) print(file_content) >>> TypeError: argument 1 must be an iterator 3: file_content = list(csv.reader(file.read(), delimiter=';', quotechar='"')) print(file_content) >>>_csv.Error: iterator should return strings, not int (did you open the file in text mode?) Some hints: print(file.read()) >>>b';"";""\r\n' <-- WRONG see file content at the top print(file.readlines()) >>>[] Please save me! -
Comparign __exact and get()
What is the need of __exact query lookup if we can simply fetch data using get(). I mean what are the extra benefits of __exact in querysets ?? -
Accept Post request to nodejs from django
I am making a post request from django to nodejs v = {} v['id'] = 'test' y=requests.post('http://localhost:3000',params=v) How can i parse this data in nodejs i am currently doing like this but it shows undefined. app.post('/', function (req, res) { console.log(req.body.id) ======> this shows Cannot read property 'id' of undefined res.send('hello') }) so why the error is coming -
form validation with django CBV FormView
Can someone explain me how can I validate my form, it's rather simple stuff and some how I can I just don't get it, need to validate my select field so I can return and display data, can someone explain how to do this from django.views.generic.edit import FormView from django.utils import timezone from .models import Rate from statistics.forms import StatisticsForm from statistics.services import StatisticsCalculation class StatisticsView(FormView): template_name = "statistics/invoice_statistics.html" form_class = StatisticsForm def get_initial(self): initial = super(StatisticsView, self).get_initial() initial["month_choice"] = timezone.now().month initial["invoice_year"] = timezone.now().year return initial def get_context_data(self, **kwargs): context = super(StatisticsView, self).get_context_data(**kwargs) default_currency = Rate.EUR currency_usd = Rate.USD currency_gbp = Rate.GBP context["can_view"] = self.request.user.is_superuser context["currency"] = default_currency context["currency_usd"] = currency_usd context["currency_gbr"] = currency_gbp context["statistic"] = StatisticsCalculation.\ statistic_calculation(supplier_default_currency) context["statistic_usd"] = StatisticsCalculation. \ calculation(supplier_default_currency_usd) context["statistic_gbp"] = StatisticsCalculation. \ statistic_calculation(supplier_default_currency_gbp) return context -
moviepy cannot run in a django project on apache
I'm using moviepy in a model to create thumbnail for uploading video. It works fine with django 'runserver' command, but when the project is deployed on apache, things get wrong. None of the url binded to views function give any response and there is nothing in apache error log. But if I delete the line from moviepy.editor import *, other urls can be visited. What is the problem? Is there something I need to do with apache or ffmpeg? I'm using Ubuntu 16.04 and Django 1.10, Apache 2.4.18, ffmpeg 3.2.4 Thanks. -
Django Migration not detected when models.py inside an folder in app
Folder structure that I kept for my project is: project: commons settings.py manage.py app models models.py __init__.py on running ./manage.py makemigrations no changes are getting detected. I have added the app in installed_apps of settings.py as 'app'. Can this be achieved in django ? Advance thanks for your time. -
How to make sure data over UNX Sockets gets sent in order using Twisted Python
With my current setup, I'm running a server with Django and I'm trying to automate backing up to the cloud whenever a POST/PUT action is made. To circumvent the delay (Ping to server hovers around 100ms and an action can reach upwards of 10 items posted at once), I decided to create a separate entity with a requests client and simply have this handle all backing up functions. To do this, I have that entity listen via UNX using twisted and I send it a string through it whenever I hit an endpoint. The problem however is that if too many end points get called at once or get called in rapid succession, the data sent over the socket no longer comes in order. Is there any way to prevent this? Code below: UNX Server: class BaseUNXServerProtocol(LineOnlyReceiver): rest_client = RestClient() def connectionMade(self): print("UNIX Client connected!") def lineReceived(self, line): print("Line Received!") def dataReceived(self, data): string = data.decode("utf-8") jstring = json.loads(data) if jstring['command'] == "upload_object": self.rest_client.upload(jstring['model_name'], jstring['model_id']) Unix Client: class BaseUnixClient(object): path = BRANCH_UNX_PATH connected = False def __init__(self): self.init_vars() self.connect() def connect(self): if os.path.exists(self.path): self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.client.connect(self.path) self.connected = True else: print("Could not connect to path: {}".format(self.path)) def call_to_upload(self, … -
Stopping the Inheritance of nav-bar for a particular template
I working on a Django project and there is a navbar for the site. So when one user gets logged in I want to change the navbar. So how can I stop the navbar getting inherited from the base template? {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>Blog</title> <title>Eapp</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Eapp</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'eapp:registration' %}">Register</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'eapp:login' %}">Login</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> {% block content %} {% endblock content%} </div> </body> </html> This is my base.html looks like and , please give me an idea about how the new template look like? Thank You -
Django : 'Form' object has no attribute 'clean_data'
I made password reset form which takes 3 passwords, old password, new password, and confirm for new password. So far I succeeded to make it displayed in the html but couldn't proceed further. whenever I click submit button it displays error message. I've been search about this errors in stack overflow and changed it but still keep displaying error. This is the error message. AttributeError at /blog/password_change/blue/ 'PasswordChangeForm' object has no attribute 'clean_data' View.py @login_required def password_change(request, username): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.POST) if form.is_valid(): oldpassword = form.cleaned_data.get('oldpassword') password = form.cleaned_data.get('password') password2 = form.cleaned_data.get('password2') if oldpassword == password2: update_session_auth_hash(request, form.username) form.save() return HttpResponseRedirect('/blog/password_change_done/') else: return render(request, 'blog/detail.html', {'error_message': 'password mismatch'}) #return redirect(reverse('blog:home')) #return redirect(reverse('blog:profile', args=[form.user.get_username()])) else: print("C") form = PasswordChangeForm(user=request.user) return redirect(reverse('blog:profile', args=[form.user.get_username()])) for oldpassword = form.cleaned_data.get('oldpassword'), I also tried oldpassword = form.Cleaned_data['oldpassword'] too but it made same error message. forms.py class PasswordChangeForm(forms.Form): oldpassword = forms.CharField(widget=PasswordInput()) password1 = forms.CharField(widget=PasswordInput()) password2 = forms.CharField(widget=PasswordInput()) def __init__(self, user, data, **kwargs): self.user = user super(PasswordChangeForm, self).__init__(data, **kwargs) def clean_oldpassword(self): if self.clean_data.get('oldpassword') and not self.user.check_password(self.clean_data['oldpassword']): raise ValidationError('Please type your current password.') return self.clean_data['oldpassword'] def clean_password2(self): if self.clean_data.get('password1') and self.clean_data.get('password2') and self.clean_data['password1'] != self.clean_data['password2']: raise ValidationError('The new passwords are not the same') return … -
How to splits datetime in django views.py?
I am sending sms to user after successful transaction,in that sms i am adding date.During sending sms taking that date from database, as that is datetime field it gives me date up to nano seconds while i want only date of transaction, how can i split it? -
Display Django Inline Objects In Wagtail CMS ModelAdmin List Display
I have a Product and a MenuPrices model. The MenuPrices model is an inline panel to the Product model. In Wagtail ModelAdmin, I'd like to add the MenuPrice objects as part of the inline display. Below is my code and a screenshot. Thank you. MenuPrices MENU = ( ('lunch', 'Lunch'), ('dinner', 'Dinner'), ('special', 'Special'), ) MENU_CHOICES = ( ('starters', 'Starters'), ('salads', 'Salads'), ('pastas', 'Pastas'), ('desserts', 'Desserts'), ('neopolitan_pizzas', 'Neopolitan Pizzas'), ('classic_american', 'Classic American'), ('create_your_own_pizza', 'Create Your Own Pizza'), ('lunch_combos', 'Lunch Combos'), ('sandwiches', 'Sandwiches'), ) class MenuPrices(models.Model): menu_section = models.CharField(default=None, max_length=100, choices=MENU_CHOICES, unique=True, verbose_name='Menu Section') menu = models.CharField(default=None, max_length=100, choices=MENU, unique=True, verbose_name='Menu Section') menu_price = models.DecimalField( blank=True, null=True, max_digits=5, decimal_places=2, verbose_name='Menu Price', help_text='Numbers only with 2 digital decimal. I.e. 25.00' ) panels = [ MultiFieldPanel( [ FieldPanel('menu'), FieldPanel('menu_section'), FieldPanel('menu_price'), ], heading="Menu & Prices", classname="collapsible" ), ] Product class ProductMenuPrices(Orderable, MenuPrices): page = ParentalKey('Product', related_name='prices') @register_snippet class Product(ClusterableModel): product_title = models.CharField(max_length=255, verbose_name='Product Title') product_description = StreamField([ ('heading', blocks.CharBlock(classname='full title')), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], blank=True) panels = [ MultiFieldPanel( [ FieldPanel('product_title'), InlinePanel('prices', label="Menu & Price Assignment"), ], heading="Product Detail", classname="collapsible" ), StreamFieldPanel('product_description'), ] def __str__(self): return self.product_title wagtail_hooks.py class ProductModelAdmin(ModelAdmin): model = Product menu_label = 'Products' menu_icon = 'snippe' menu_order = 300 add_to_settings_menu … -
CSRF token AJAX based post in a Django Project
I recently learnt JS and tried the following JS code for AJAX POST but I am getting a 403 error. Did some further research and found that I needed to pass a CSRF token. I have gone through a lot of tutorials online but the only solutions I was able to find were of JQuery and I have no idea how that syntax works. I need to know how to pass a CSRF token via Javascript AJAX based post for a django project. My code is; var upvoteBtn = document.querySelector('#upvote'); var downvoteBtn = document.querySelector('#downvote'); upvoteBtn.addEventListener('click', jL); downvoteBtn.addEventListener('click', cL); function jL(event) { document.getElementById("first").innerHTML = "yes! upvoted"; document.getElementById("upvote").style.visibility='hidden'; var http = new XMLHttpRequest (); var url = 'http://myurlhere';//edited var data = 'title=Post%20Title&body=Body'; var method = 'POST'; http.open(method, url, true); http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') http.onreadystatechange = function() { if (http.readyState === XMLHttpRequest.DONE && http.status === 200){ document.getElementById("first").innerHTML = "yes! upvoted"; console.log("i have upvoted", http.responseText); } else if (http.readyState === XMLHttpRequest.DONE && http.status !== 200){ console.log("error!", http.responseText); } }; http.send(data); } function cL(event){ event.target.innerHTML = "downvoted! "; } -
Accessing django shell from heroku scheduler for django orm
I'd like to create a scheduled task for my django application on heroku that accesses the django orm so i can easily remove some records nightly. I've seen that i can get the scheduler to run one-off scripts like task.sh which runs something like !#/env/bin/python print('hello') but i'd like access to the orm. Which is usually only available if you're using python manage.py shell. I'm considering just running a script with sqlalchemy, but I'd feel more comfortable using the django-orm because that seems more compact and makes more sense with what I'm doing. -
Django Ldap Settings
I am using Django Ldap authentication . By default we would give the Ldap settings in settings.py so that the LdapBackend file would access the settings.py file for the Ldap credentials . But in my case , i need the LdapBackend.py file to look into a separate json file for the Ldap settings . How to do it Thanks -
timestamp wth timezone vs django
My Oracle DB has a table with a column of type TIMESTAMP WITH TIMEZONE. The Django model converts it to datetime but loses the original TZ info and assumes UTC. DB: 01-JAN-17 12.10.01.809000 AM -05:00 Django:2017-01-01 00:10:01.809000+00:00 USE_TZ = True The problem is that the table contains timestamps from different timezones. So if I change the standard timezone with activate() it won't help. Is there a way for Django to explicitly read the timezone from the database without assuming it? PS.: I'm aware that it would be better/easiest if my database would only contain UTC values but this is what I got. -
Django: add additional data in queryset
I've two models: Movie Attributes: name, plot, rating, release_date, photo Director Attributes: name, bio, photo Movie and Director models has a many-to-many relationship. Now in my movies/views.py file: def movies_index(request): movies = Movie.objects.all() for movie in movies: # insert directors in every movie object context_data = { 'movies': movies } return render(request, 'movies/index.html', context_data) I want to insert directors data in to every movie object. So that the result may be like: [ { name: "12 Angry Man", plot: "bla", release_date: "1-2132", directors: [ { name: "Quentine", bio: "Lodfs" }, { name: "Tarantino", bio: "Lodsdfs" } ] } ] How can I achieve this? Or, is there any different approach do do this? N.B. I'm using Django 1.9, Python 2.7 -
Override Template django-allaut
I'm almost throwing in the towel with overriding the template. There not way it works for me. Always it's looking the template in the default directory: /Library/Python/2.7/site-packages/allauth/templates/account I have try almost all that I found: http://stackoverflow.com/a/18811664/3348531 http://stackoverflow.com/a/40065009/3348531 my dir structure: myproject myproject myapp templates accounts login.html ... But I also try: myproject myproject myapp templates myapp accounts login.html ... Nothing work --urls.py urlpatterns = [ url(r'^accounts/', include('allauth.urls')), ... --settings.py INSTALLED_APPS = [ 'formimmapp.apps.FormimmappConfig', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'formtools', 'crispy_forms', ] TEMPLATE_DIRS = (os.path.join(PROJECT_DIR, 'templates'),) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [os.path.join(BASE_DIR,'templates')], 'DIRS': [os.path.join(PROJECT_DIR, 'templates')], # 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Django Version 1.10.1 -
How to display data as array format using python
def index(request): conn = MySQLdb.connect(host="localhost", user="user", passwd="pwd", db="highchart_with_django") cursor = conn.cursor() cursor.execute("SELECT categories,tokyo,london,new_york,berlin FROM basic_line_chart") row = cursor.fetchone() while row is not None: print row row = cursor.fetchone() return render(request, "linechart.html") It's giving output like below: ('Sep', Decimal('7.00'), Decimal('3.90'), Decimal('-0.20'), Decimal('-0.90')) ('Oct', Decimal('6.90'), Decimal('4.20'), Decimal('0.80'), Decimal('0.60')) expecting output: ["Sep", "7.00", "3.90", "-0.20", "-0.90"],["Oct", "6.90", "4.20", "0.80", "0.60"] How can i achieve this. please help me with this.