Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Query's issues
I am doing some Django practice through Coding for entrepreneurs. This is the code: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views import View from .models import KirrURL def kirr_redirect_view(request,shortcode=None,*args,**kwargs): #Method 1: obj = get_object_or_404(KirrURL, shortcode__iexact=shortcode) obj_url = obj.url #Method 2: qs = KirrURL.objects.filter(shortcode__iexact=shortcode) if qs.exists() and qs.count() == 1: obj = qs.first() obj_url = obj.url return HttpResponse("Hello : {sr}".format(sr=obj_url)) What I am doing is I get some words from url and pass it in to the kirr_redirect_view.And use query to get the data and return some words. The website introduce two methods to do it.The second works fine.When I changed to second method.The method suddenly get wrong and I keep getting 404 from the page even if I pass the correct key words. -
How to create fix migrations for an app with existing schema while not touching other apps?
Django 1.9.7, db.sqlite3 as DB I have a Django project with several apps. For app "A", I had migrations, but I deleted them by accident and pushed to the remote git. Also, a lot of new stuff for other apps was pushed to the git during the day. Other apps don't depend on the "A" app models. Everything worked until I decided to add a new field to the model of the "A" app. I got OperationalError: no such column: error. I tried to make initial migrations for the app "A" python manage.py migrate --fake-initial. I got new migrations but I still have the OperationalError: no such column:. How to fix "A" app migrations without affecting other apps migrations? -
Django-all-auth: language translation doesn't work
I'm Korean and using django-all-auth in my Django Project. I checked that there is Korean .po file in django-all-auth. But all expressions are english, not Korean. I just followed Installation part and Configuration part in doc. And here is my settings.py LANGUAGE_CODE = 'ko-kr' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True Did I miss something? -
Django Query to aggregate values from two rows into single result per day
I am trying to create a model manager query which returns a result grouped by day for multiple balance types (DATA and AIRTIME) over a given date range. The Balance history table is updated all the time as the sim uses data, but for reporting we only want to show one balance a day The models are simple: class Sim(TimeStampedModel): number = models.CharField() class SimBalanceHistory(TimeStampedModel): balance_type = models.CharField(choices=BALANCE_TYPES, max_length=10) amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) sim = models.ForeignKey(Sim, related_name='balance_histories') Some sample data from the SimBalanceHistory Table: ID BALANCE_TYPE AMOUNT SIM_ID CREATED MODFIED 1603 AIRTIME 3.71 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1604 DATA 36.75 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1703 AIRTIME 3.71 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1704 DATA 36.74 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1803 AIRTIME 3.71 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1804 DATA 36.73 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1973 AIRTIME 3.71 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 1974 DATA 36.72 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 2059 AIRTIME 3.71 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 2060 DATA 36.72 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 +02:00 2135 AIRTIME 3.71 348 2016-11-17 11:13:42.498180 +02:00 2016-11-17 11:13:43.543159 … -
What is the use of Django Template Language?
What is the use of Django template language in template system. we have built-in template engine which parse html string and render it with context then why we need of django template language ? -
How to use mutiple databases for django unitests?
We, know how to use different databases for django testcases and development server. If not consult this. Now my question is that? What if I have some test cases that can run in sqlite but some other test case(special) which will need postgres sql. I want to specify it for those special test cases which have to be test on postgres. Now the question is why I test all of them in postgres? Testing in postgres is slower than sqlite3, I guess experienced programmers know about this. So is there a way to use different databases in unit tests? Thanks in advance. -
Reverse Filter Django Model with DRF
I have problem filtering in django-models and i am using django-rest-framework to work this serialized data. What i want here is to get all herds record both with animal(s) in which the animal may had a species_type='Cow' or an empty herd(s). This is my models. models.py class Herd(models.Model): name = models.CharField(max_length=25) description = models.TextField(max_length=250, null=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Animal(models.Model): name = models.CharField(max_length=25) species_type = models.CharField(max_length=25) breed = models.CharField(max_length=25) herd = models.ForeignKey(Herd, related_name='animals', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) serializers.py class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = [ 'name', 'species_type', 'breed' ] read_only_fields = ['id', 'created_at', 'updated_at'] class HerdSerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True, read_only=True) class Meta: model = Herd fields = [ 'id', 'name', 'description', 'animals' ] read_only_fields = ['created_at', 'updated_at'] This is my viewset which handle all crud operations. views.py class HerdViewset(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Herd.objects.all() serializer_class = HerdSerializer Now when i browse the HerdViewSet endpoint /api/herd/ i got the results of all herds with animals or empty herd(s). But the animals in some herd does not filter the species_type='Cow' it still returns all animal which belong to … -
Django cannot assign value
i got error of this after start uploading a file with metadata.I want to save data_category into database but this error came out Cannot assign "2": "Layer.data_category" must be a "DataCategory" instance. "2" is the value that i want to store in the database. html <section class="data_category"> <label>{% trans "Select Category of Data" %}</label><br/> <select id="data_category"> {% for category in category %} <option value={{ category.id }}>{{ category.category_name }}</option> {% endfor %} </select> </section> views.py if request.method == 'POST': form = NewLayerUploadForm(request.POST, request.FILES) tempdir = None errormsgs = [] out = {'success': False} if form.is_valid(): data_category=form.cleaned_data["data_category"] print data_category title = form.cleaned_data["layer_title"] # Replace dots in filename - GeoServer REST API upload bug # and avoid any other invalid characters. # Use the title if possible, otherwise default to the filename if title is not None and len(title) > 0: name_base = title else: name_base, __ = os.path.splitext( form.cleaned_data["base_file"].name) name = slugify(name_base.replace(".", "_")) try: # Moved this inside the try/except block because it can raise # exceptions when unicode characters are present. # This should be followed up in upstream Django. tempdir, base_file = form.write_files() saved_layer = file_upload( base_file, name=name, user=request.user, overwrite=False, charset=form.cleaned_data["charset"], data_category=form.cleaned_data["data_category"], abstract=form.cleaned_data["abstract"], title=form.cleaned_data["layer_title"], metadata_uploaded_preserve=form.cleaned_data["metadata_uploaded_preserve"] ) forms.py class NewLayerUploadForm(LayerUploadForm): if … -
django rest framework https authentication - 403 forbidden
I am developing REST api with django rest framework. In my view, I have set permission classes as permission.IsAuthenticated. It is working with HTTP but I get 403 forbidden with HTTPS. I am testing with Chrome Advance Rest Client, using the Basic Authentication. The url I test with is: https://username:password@example.com/product/list HTTP Request Header: GET /jobs/list/ HTTP/1.1 HOST: example.com authorization: Basic Z29kZW5taWxlOnBhc3N3b3JkMTIzIQ== HTTP Response Header: Date: Tue, 22 Nov 2016 08:09:31 GMT Server: Apache/2.4.10 (Debian) Allow: GET, POST, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN Vary: Accept,Cookie Content-Length: 58 Content-Type: application/json On the Advance Rest Client, I got 1 redirect: To: /product/list/ with status 301 Moved Permanently Date: Tue, 22 Nov 2016 08:16:47 GMT Server: Apache/2.4.10 (Debian) Location: /product/list/ Content-Length: 0 Content-Type: text/html; charset=utf-8 view.py class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(...) in my apache config settings, i redirect http to https: <VirtualHost *:80> ServerName example.com ServerAdmin webmaster@localhost ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # This is optional, in case you want to redirect people # from http to https automatically. RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] </VirtualHost> <IfModule mod_ssl.c> <VirtualHost *:443> WSGIDaemonProcess example python-path=/var/www/html/example:/home/admin/project/example/virtualenv/env3.4/lib/python3.4/site-packages python-home=/home/admin/project/example/virtualenv/env3.4 WSGIProcessGroup example WSGIScriptAlias / /var/www/html/example/example/wsgi.py ServerAdmin webmaster@localhost ServerName … -
Django - FilePathField returns wrong paths
I'm trying to allow admin to choose from flags when they creates neww Language object. There is a folder mainapp/static/img/flags/550px/ with *.png images of flags. class Language(models.Model): shortcut = models.CharField(max_length=40, help_text=_('Shortcut of the language'), unique=True) name = models.CharField(max_length=40, help_text=_('Name of the language'), unique=True, verbose_name=_("Language")) flag = models.FilePathField(path='mainapp/static/img/flags/550px'),default='/static/img/icons/check-icon.png') #flag = models.FilePathField(path='{}\mainapp/static/img/flags/550px'.format(settings.BASE_DIR),default='/static/img/icons/check-icon.png') The problem is that Django doesn't resolve those paths in html. There are paths like this: mainapp/static/img/flags/550px\es.png which is a problem because Django starts in /static/, not /mainapp/. On the other hand, when I put static/img/flags/550px, it does not let me choose from the folder. So the main problem is that when admin choose from flags, it saves path with mainapp/static.. at the beginning. I want to save only static/.. Do you know what should I do? -
django crontab job does not work
I have a very simple django project that consists of one application model called Quote. The application simply has a cron job that executes every 1 minute to get a random quote from the DB and use notify-send command to show a notification with that quote. I am using django-crontab to achieve this goal. The cron.py is very simple as show below from random import randint from models import Quote import subprocess, time, os def notify(): latestQuote = Quote.objects.all().order_by("-id")[0] max_id = latestQuote.id quote = Quote.objects.get(pk=randint(1,max_id)) subprocess.Popen(['notify-send',quote.quote]) time.sleep(1) And here is the cron settings in the settings module CRONJOBS = [('*/1 * * * *', 'core.cron.notify')] When executing ./manage crontab add, a cron command is added to my crontab as following */1 * * * * /usr/bin/python /home/anas/storage/motinder/manage.py crontab run 5ade4dc167538a33802640eeb92219ad # django-cronjobs for motinder If I executed the command from the system crontab, the notification is displayed successfully BUT the cron job does not execute automatically. -
Django - Admin to choose from saved/uploaded images
In my project, admin can create a new Language object which consists of this fields: name, shortcut, flag. I have a folder in static folder called img/flags/550px/. There are all possible flags in png formats. I want admin to be able to choose one of those files when they creates a new Language object. For this purpose I've decided to make flag to be FilePathField but apparently, it does not worked that I expected. class Language(models.Model): shortcut = models.CharField(max_length=40, help_text=_('Shortcut of the language'), unique=True) name = models.CharField(max_length=40, help_text=_('Name of the language'), unique=True, verbose_name=_("Language")) flag = models.FilePathField(path='/static/img/flags/550px',default='/static/img/icons/check-icon.png') Admin can't choose anything: Where is the problem? -
What should be the approach to have a django skeleton project and keep the projects based on it in sync?
I know the question can be broad and opinion based. But its something lot of developers might be practicing. The scenario is as such. Lets say I have a skeleton django project which has necessary static(js/css) files in a folder called frontend, then there is a another app which will be common to all the other projects that will be based on this skeleton and so forth. Now, lets say that I have two separate django projects based on this skeleton, so the core is same in both the projects. I am unsure how to update this two projects to keep them in sync with any changes to skeleton project. All the three projects have a repository setup on bitbucket. What I have tried so far is have a python script that can be executed to clone the skeleton project into tmp (we use linux for development) and then copy/add files from those locations into projects that are based on skeleton. I think there might be a better solution to scenarios as such. I would be glad if someone with experience can guide me here. -
Model configuration: dynamically assign questions based on type of Location
I have an app where Locations can be added and a User can leave a review (5 star rating). This is already working. What I'd like to do, is add Questions and Choices to the review. However, I'd like to make sure that only certain types of Questions are asked, depending on the type of Location. So far I'm thinking of expanding the types of Location using a OneToOneField, which is very similar to the official docs example with a Restaurant and a Place having a OneToOneField relationship, and then further specifying that with a ManyToManyField for Category and SubCategory models. However, what I'm struggling with, is how to add a Question to all types of a certain location. What I currently, is that Questions have to be added on a place by place basis. Instead, what I'd like is to add a Question to all Restaurants (OneToOneField to Location) or maybe even to the Category (ManyToManyField to Restaurants). What would be the best way forward? Do I need yet another model to hold the configuration of questions for a type of Location? Also, unrelated note but can I have a class Question with attribute question? Or will this cause … -
How to connect Sqlserver 2008 in Django?
DATABASES = { 'default': { 'NAME': 'CVH_Dev', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'provider': 'SQLOLEDB', 'use_legacy_date_fields': 'True' } } I was tried above code . but it shows error message. Error Messgae: File "C:\Python27\lib\site-packages\django\db\utils.py", line 134, in load_backend raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: 'sqlserver_ado' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: No module named util please tell me how to connect SQL server 2008 to my django project.. now I m using SQL server2008R2 -
Fully replace username with email Django
I want fully remove username in my User model and replace with email. At first i override USERNAME_FIELD. But if i want to use email not username i must to add unique=True in email field. After that change UserManager (create user using email and password). Also replace username occurances with email in UserAdmin and forms, attached to him. My question is it true to override Django classes, or is there better way to use email and don't use username at all. -
Can't enter to Django CMS
I have a project based on django and djano-cms and there is problem with entering to django CMS. I created superuser typing in terminal ./manage.py createsuperuser I gave a username, email and password. When I runserver typing ./manage.py runserver and open admin page, I see django CMS login page. But when I type my username and password and press submit button, it doesn't do anything. Just resets the inputs of account's fields. So how to enter to django CMS? If you guys, know the solution, please answer or leave a comment. Maybe someone faced such kind of problem. Every help is appreciable :) -
What is a difference between template language , backend and template engine?
I am new in Django while reading Django template system I have a little bit confused between Django template language , backend, and engine ? Template Engine : Parse template string and render it with context and generate dynamic Html content . What is the DTL and backend in Django ? Any helpful answer will be appreciated . -
Webpack loader error loading bundle.js for reactjs in Django Application
I have a Django application on production site and am using webpack with ReactJS. I've tried running npm run build but that doesn't do anything. Any ideas on why it's treating it as a string and not rendering bundle.js which is inside my static folder? I am using Nginx as my web server, which serves static files from that static folder inside my main web application folder. -
403 CSRF error on page refresh after login() Django?
So the code is very simple: views.py @csrf_protect def index(request): global userPersonalInformation if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) profile = Profile.objects.get(username=username) return render(request, 'main/profile.html', {"profile":profile}) else: if CheckUser(username, password): user = User.objects.create_user(request.POST['username'], userPersonalInformation['email'], request.POST['password']) user.save() profile = Profile.objects.create(username=username,school=userPersonalInformation['school'],img=userPersonalInformation['img'], birthyear=userPersonalInformation['birthyear'],city=userPersonalInformation['city'],solved=progress['denominator']) profile.save() login(request, user) return render(request, 'main/profile.html', {"profile": profile }) else: context = {"form": Userform(request.POST or None), } return render(request, 'main/login.html', context) else: form = Userform() context = {"form": form, } return render(request, 'main/login.html', context) profile.html {% block title %}Profile | {{ user.first_name }} And this displays Profile | username correctly on the title bar. i.e. User is logged in. Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] main/urls.py from django.conf.urls import url from . import views app_name = 'main' urlpatterns = [ url(r'^$', views.index, name='index'), ] login.html {% extends "main/base.html" %} {% block title %}Sign in{% endblock %} {% block body %} <div class="container"> <form method="post" action="" class="form-signin"> <h2 class="form-signin-heading">Please sign in</h2> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" type="submit">Sign in</button> </form> </div> {% endblock %} form.py from django import forms from django.contrib.auth.models import User class Userform(forms.Form): class Meta: model= … -
Ajax call to fetch new JSON data to update Django template
I've been trying to figure out the problem for the past hours with no luck. I want for my django template to load new json data to the user' screen when the user is near the bottom. Basically I want to make my django app load content as I scroll. This is how I increment the offset to get new data from the api $(window).scroll(function() { if($(window).scrollTop() + $(window).height() == $(document).height()) { alert("Requesting new data"); offset++; $.post('/releases/fetch/', {'offset': offset}, function(data){ console.log("---") console.log(data); console.log("---") }); } }); I do get the new JSON I want, so ajax's post works well and the offset increments. Now with this new JSON I got, I want to render the rest of my template or rather I want to render the JSON I got as dom elements to my page. This is the django view I call for my aja's post def ajax_view(request): if request.is_ajax(): offset = request.POST['offset'] games = services.get_games(offset) return HttpResponse(games) return HttpResponse("Get out!! 404") SO do I call django's render instead the HttpResponse? Oh and this is the django class view that renders the template I'm talking about class HomePage(TemplateView): def get(self, request): # Sends the json to the template games = … -
Environment variable dissapear after desable
I'm using environment variables for secrets in my Django app. But after disable command in virtual environment this variables disappear. For set environment variables i'm using export command. ValueError: Value 'DATABASE_PASSWORD' is required to be set as the environment variable 'DJANGO_DATABASE_PASSWORD' Why this happening and how to avoid this behavior? -
MagicMock not called inside django signals
I have some model class Foo(models.Model): name = models.CharField(...) url = models.URLField(...) foo_pre_save_(sender, instance, *args, **kwargs): r = urlopen(instance.url) # Magic mock is not called html = bs4.BeautifulSoup(r.read(), "html5lib") instance.name = html.find(name="title").text with a test def test_get_site_name(self): with mock.patch('urllib.request.urlopen') as get_mock: get_mock.return_value = mock_response = mock.MagicMock() mock_response.read.return_value = "<title>facebook</title> foo = Foo.objects.create( url = 'www.facebook.com' ) self.assertEqual(foo.name, "facebook") But the pre_save signal is actually going out and hitting the supplied url, and not getting the mock response I believe this has to do with the scope of patch; however, I'm not sure how to fix it. -
Force Django Channels Websocket Authentication
The website I am working on requires login for every page. I am trying to add websockets with Channels for two way communication to the client web browser for notifications. Daphne is running as the interface server and manage.py runworker is running the workers. I have a have a working function in the consumers.py file that runs when the connection has been opened. The problem is that this connection can be opened, and the function runs by any web browser, without being logged in. How can I force login before the connection can be opened? -
Can i build crud in django without database?
How can i build crud in django withoutdatabase and javascript or jQuery? before this case i have a same case but is use jQuery and javascript but my teacher give me same case but use the different languaage i must use django without database & model just use views and template. this is my code use javascript and jquery: <!DOCTYPE html> <html> <head> <title>Tugas jQuery</title> <style> input{ margin: 7px; } select{ margin: 7px; } table { counter-reset: rowNumber-1; } table tr { counter-increment: rowNumber; } table tbody tr .num:before { content: counter(rowNumber); min-width: 1em; margin-right: 0.5em; } </style> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script> <script> function deleteRows(e){ $(e).parent().parent().remove(); $(".number").html(""); } $(document).ready(function(){ var no=$('table tbody tr').index(); var no=no+1; $('#kirim').on('click',function(){ //alert('klik'); var str=$('#jam_terbang').val(); var nm=$('#nama_maskapai').val(); var jt=$('#jam_terbang').val(); var patt = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$"); var res = patt.test(str); var day = 'pagi'; if(res==true){ no++; //Pembagian Waktu if (str <= "10:00") { var day = 'pagi'; } else if (str > "10:00" && str <= "18:00"){ var day = 'siang'; } else { var day = 'malam'; } //Input Table $('#data').append('<tr class="allshow">'+ '<td class="num"></td>'+ '<td class="'+nm+'">'+nm+'</td>'+ '<td class="'+day+'">'+jt+'</td>'+ '<td><a href="#" onclick="deleteRows(this)">Delete</a> <a href="#" class="naik">Up</a> <a href="#" class="turun">Down</a></td>'+ '</tr>'); //Input Select Option var a = $("#mask option[value='"+nm+"']").length; if (a …