Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is JavaScript replace not working in Django?
I have some code that takes an HTML template and replaces all {{tags}} with their appropriate values. The code works everywhere else in its raw form (without Django). Here's a jsFiddle for proof. However, it does not work in PyCharm when I put it inside my Django project. HTML <h1>Infinite Scroll - Loading JSON</h1> <p>Loading photos from the <a href="https://unsplash.com/developers?utm_source=infinite-scroll-demos&utm_medium=referral&utm_campaign=api-credit">Unsplash API</a></p> <div class="container"></div> <div class="page-load-status"> <div class="loader-ellips infinite-scroll-request"> <span class="loader-ellips__dot"></span> <span class="loader-ellips__dot"></span> <span class="loader-ellips__dot"></span> <span class="loader-ellips__dot"></span> </div> <p class="infinite-scroll-last">End of content</p> <p class="infinite-scroll-error">No more pages to load</p> </div> <!-- .photo-item template HTML --> <script type="text/html" id="photo-item-template"> <div class="photo-item"> <img class="photo-item__image" src="{{urls.regular}}" alt="Photo by {{user.name}}" /> <p class="photo-item__caption"> <a href="{{user.links.html}}?utm_source=infinite-scroll-demos&utm_medium=referral&utm_campaign=api-credit">{{user.name}}</a> </p> </div> </script> <script src="https://unpkg.com/infinite-scroll@3/dist/infinite-scroll.pkgd.min.js"></script> JavaScript // Get an API key for your demos at https://unsplash.com/developers var unsplashID = '9ad80b14098bcead9c7de952435e937cc3723ae61084ba8e729adb642daf0251'; var $container = $( '.container').infiniteScroll({ path: function() { console.log(this.pageIndex); return 'https://api.unsplash.com/photos?client_id=' + unsplashID + '&page=' + this.pageIndex; }, // load response as flat text responseType: 'text', status: '.scroll-status', history: false, }); $container.on( 'load.infiniteScroll', function( event, response ) { // parse response into JSON data var data = JSON.parse( response ); // compile data into HTML var itemsHTML = data.map( getItemHTML ).join(''); // convert HTML string into elements var $items = $( … -
how to add python code in href attribute in html tag
I am new to python, I have a code that iterates the list in HTML using python {% for e in news %} <h5 class="title"> {{ e.title }}</h5> <a href="{% e.url %}"> url </a> {% endfor %} getting template syntax error in href tag. Please let me know if you know the solution. -
uwsgi ini file does not create a sock file
I am trying to configure nginx to work with my django project. I create my ini file called myfoo.ini right above the folder that contains settings.py. This is the content of that file [uwsgi] module = main.wsgi:application master = true pidfile = django.uwsgi.pid enable-threads = true http = 127.0.0.1:8000 processes = 5 socket = /home/ec2-user/MyVenv/MyWeb/foo.sock harakiri = 50 max-requests = 5000 vacuum = true home = venv daemonize = django.uwsgi.log ; If VIRTAL_ENV is set then use its value to specify the virtualenv directory if-env = VIRTUAL_ENV virtualenv = %(_) endif = Any suggestions on why the sock file is not being created ? This file is next to my other django apps ? I was expecting that once I do this uwsgi --ini my_foo.ini It should create a .sock file next to it. However that is not happening any idea if I am doing something wrong ? Also is it ok to place my_foo.ini next to other apps ? -
Django user registration and login using Djnago-Phone-Login
I installed django-phone-login using pip install django-phone-login I followed the instructions given for configuring setting.py file. When i ran server after configuring settings, i saw error as given below. ERRORS: : (admin.E108) The value of 'list_display[0]' refers to 'phone_number', which is not a callable, an attribute of 'PhoneTokenAdmin', or an attribute or method on 'phone_login.PhoneToken'. I have can there were multiple similar question asked for the same error. Django-phone-login Django Registration with phone To me it's sound like there is no work going on this project. So I am wondering if Django-Phone-Login worth considering for new project to implement registration and login process If it's good to consider and production ready app then how to sort out this error in my project. Your advise is highly appreciated on this. -
creating a file when a user signup
I need a file to be created at the time when a user sign up below is my signup view.py in django: class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' what should i do , so that a file will be created at the time when user signup -
Can one table has more than one primary key in Django?
I have following table structure. When I try to migrate, I got following error. django.db.utils.OperationalError: table "certificate_light" has more than one primary key However, I found other stack overflow page saying that one table can have more than one primary key in RDBMS. Can anyone know how I can implement table having more than one primary key in Django? models.py class Certificate(models.Model): name=models.CharField(max_length=20) class Zone(models.Model): zone=models.CharField(max_length=20) conditioned=models.BooleanField(default=True) class Light(models.Model): certificate=models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate') zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone') lpd=models.IntegerField() sensor=models.BooleanField(default=True) -
managing django websites with many pages
I am creating my first web application and I wanted this website to have so many pages in the future. But the problem is that I need to manage those pages easily. something like wordpress and I have no idea how to manage a website with like thousands of pages Any tips? -
Uploading large raster geodjango
I created a geodjango model using RasterField(). I have been trying to upload the raster using postgis. I load the raster like so raster = GDALRaster('rasters/data/my_image.tif', write=True) r = Rast(name="Hello", image=raster) r.save() Everything works fine until I try to save the object and get django.db.utils.OperationalError: cannot allocate memory for output buffer. I am not sure how to solve this. The raster is a single image that is around one gb. When I look at my usage during this process I notice that alomst all of my 32gb of ram is being used for some reason. Can this be chunked? Or is there an alternative to saving this. -
Empty form with MultiChoiceField raising NoReverseMatch error in django
model class MyModel(models.Model): user_account = models.OneToOneField(User, on_delete=models.CASCADE) remark = models.CharField(max_length=120) data_1 = models.BooleanField(default=False) data_2 = models.BooleanField(default=False) data_3 = models.BooleanField(default=False) data_4 = models.BooleanField(default=False) form class MyModelForm(forms.ModelForm): CHOICES= (("data_1", "data_1"), ("data_2", "data_2"), ("data_3", "data_3"), ("data_4", "data_4"),) my_choice = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple()) class Meta: model = MyModel fields = ["remark"] views class MyView(UpdateView): model = MyModel form_class = MyModelForm template_name = "mytemplate.html" def form_valid(self, form): selected_choices = self.request.POST.getlist("my_choice") for item in selected_choices: setattr(form.instance, choice, False) form.instance.remarks = form.cleaned_data["remark"] form.instance.save() return super(MyView, self).form_valid(form) def get_success_url(self): return reverse("app:detail-update-url") form works perfectly fine when i submit the form with data.But it raises Noreversematch with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried when i try to submit the form without checking any of the checkbox.The remark field have required =True so it works fine.what i want is, i need to display the error when non of the checkbox checked any help will be appreciated.. :) -
just Django with Angular6 with out using Django rest framework
I know Angular 4,5,6 can be used for calling an API(DRF API). But my doubt is can we use angular 4,5,6 with Django itself with out DRF. If possible, is that a better idea of using Angular 4,5,6 with django. -
PUT request in Django
I need some help with parsing form data for PUT request in Django. Tried using QueryDict, that isn't really working out for me. How to do the same using middle-ware? -
How to save Html code in database through Django
I want to save html code in database through django. In models.py i have this field description = models.TextField() But when i save data in description field through Django Admin. It display data like this <h1>This is example</h1> rather then converting it in html. Here's the Out Put -
how to display django-simple-history in template from a views.py or other?
Hello I need your help to finish my internship this late November, I do not know how to display a history in a django template! nor even how to come into the django views.py. thank you views.py : class Fournisseur(models.Model): photo = models.FileField(verbose_name="Photo") nom_f = models.CharField(max_length=40, verbose_name="Fournisseur") adresse = models.CharField(max_length=50, verbose_name="Adresse") email = models.EmailField(verbose_name="Courriel") contact = models.PositiveIntegerField(verbose_name="Contact") date_f = models.DateTimeField(auto_now_add=True, verbose_name="Date de création") history = HistoricalRecords() def __str__(self): return self.nom_f -
How to proxy a web request and forward it accurately
I'm trying to proxy the HTTP connections to a website, so that I can always access it from the same IP address of my server, from any device in the world. I am trying to do it without any installations or browser configurations like proxies. So I want to go to mydomain.com/asd and it to load targetwebsite.com/asd perfectly normal, like a VPN that's browser based. It will always be used for the same target domain, although the page does load contents from other domains. I don't really know if there's an easy nginx/httpd config I could do to do this, so I just tried to do it in Django. def index(request): url = "https://targetwebsite.com" + request.META['PATH_INFO'] if request.method == 'GET': r = requests.get(url) elif request.method == 'POST': r = requests.post(url) return HttpResponse(r.text) This works, sometimes. There are some weird Javascript errors, the odd 404. Is there anything that this code is missing? One idea: shared/static session cookie between all requests, so login can be made -
Trouble adding values to ManyToMany field Django 1.9
Before this is flagged, I have vigorously researched this problem and none of the solutions I have found have worked for me. Here is my model class Person(): birth_date = models.DateField(null=False) jobs = models.ManyToManyField('Job', blank=True) Here is what I'm doing to try to add to the ManyToMany field person = Person(birth_date="1996-11-11") person.save() Everything works fine with the initial save. Then I try to add to the jobs field doing the following job = get_object_or_404(Job, pk=1) person.jobs.add(job) I've also tried the following as a test: person.jobs.add(1) No such luck with either. The error is: TypeError: int() argument must be a string or a number, not 'instancemethod' even when I tried to give it a pk directly as an integer. Any help on why this may be happening would be greatly appreciated! -
Difficult implementing ping/latency functionality on unpreviliged host machine with Python
I made a webapp (python/django) which pings different servers and returns ping values. here's the Link. It has a pingserver(ip,sev) function that uses the os/system fping(can be used with /bin/ping) to get output and strips to get the value. (don't mind indentation, came out this way while pasting) def pingserver(ip,sev): ping_response = subprocess.Popen(["/usr/bin/fping","-c1","-t400",ip], stdout=subprocess.PIPE).stdout.read() latency = str(ping_response) ping_value=latency.split('ms')[0].split(',')[-1] if len(ping_value) <= 3: return(sev,'unknown') else: return(sev,ping_value) it works fine in my localserver but the code doesn't work in the hosted machine because '/bin/fping' doesn't exit. I cannot do following: install fping or ping (i dont have root permissions on server) can't use pyping (needs root for raw socket creation ) can't use ping/fping executables ( needs root permission ) can't use http.connnection.request or similar ( i need exact ping value ; not imformation about server up or down ) So my question is how can i get ping/latency under these circumstances so that my code functions. (any suggestions related rewite of code or usuage of library are appreciated) -
IntegrityError / NOT NULL constraint failed
Where is the variable called by 'approve_comment'? I try 'python manage.py makemigrations'. But command-line : 'No changes detected'. How can I this problem? Help me please... enter image description here from django.db import models from django.urls import reverse from tagging.fields import TagField from django.utils import timezone # python2 unicode from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Post(models.Model): title = models.CharField('TITLE', max_length=50) slug = models.SlugField('SLUG', unique=True, allow_unicode=True, help_text='one word for title alias.') description = models.CharField('DESCRIPTION', max_length=100, blank=True, help_text='simple description text.') content = models.TextField('CONTENT') create_date = models.DateTimeField('Create Date', auto_now_add=True) modify_date = models.DateTimeField('Modify Date', auto_now=True) tag = TagField() class Meta: verbose_name = 'post' verbose_name_plural = 'posts' db_table = 'my_post' ordering = ('-modify_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=(self.slug, )) def get_previous_post(self): return self.get_previous_by_modify_date() def get_next_post(self): return self.get_next_by_modify_date() -
Problems connecting Django project to Oracle Database
I've been trying to connect a django 1.11 project to a oracle 11g database, I know that django 2 is not compatible with that version of the database anymore. I'm working in PyCharm and I get this error: enter image description here my configuration in settings.py looks like this: 'ENGINE': 'django.db.backends.oracle', 'NAME': 'XE', 'USER': 'user', 'PASSWORD': 'pass', 'HOST' : '000.000.000.000', 'PORT' : '1521' obviously that are not the real data. I'm working from Mac OS, Do I need to have Oracle instant client? I would really appreciate if you could help me -
Django 2.0.7 with fastcgi gives 404 in browser but works on command line
I'm trying to set up a small django project on a bluehost shared server and am having trouble on what I think should be the last step - getting it running with fastcgi. I installed python 3.7.0 and django 2.0.7 using miniconda and was able to create a project/app but i can't get it to display in a browser (FWIW, I have successfully done this with another bluehost site on a similar plan, though that site is under the "shared plus" plan while this one is just the basic, but I don't know if that's the issue) In my ~/public_html/myproject/.htaccess file I have: AddHandler fastcgi-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /home/username/public_html/myproject/myproject.fcgi/$1 [QSA,L] And in myproject.fcgi I have: #!/home/username/miniconda3/bin/python # -*- coding: utf-8 -*- import sys, os project_name = "myproject" sys.stdout=open('/home/username/public_html/myproject/test.out','w') print(project_name) # Add a custom Python path. sys.path.insert(0, "/home/username/miniconda3/bin/python") sys.path.insert(0, "/home/username/public_html/myproject") sys.path.insert(0, os.getcwd() + "/" + project_name) os.environ['DJANGO_SETTINGS_MODULE'] = project_name + '.settings' from django_fastcgi.servers.fastcgi import runfastcgi from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() runfastcgi(wsgi_application, method="prefork", daemonize="false", minspare=1, maxspare=1, maxchildren=1) This configuration worked for me on the other site, but here I am only able to run ./myproject.fcgi successfully on the command line, but I get a 404 … -
How to increase Django model max_length value in database after tables have already been migrated
I need more characters available for the title and subtitle fields of a blog I made. I would like to increase the max_length from 100 to 150. Here is the table: class Post(models.Model): title = models.CharField(max_length=100) subtitle = models.CharField(max_length=100) slug = models.SlugField(max_length=99) date_added = models.DateTimeField(default=timezone.now) author = models.CharField(max_length=60) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) Through another Q&A I took the advice to change the max_length in the model (in my case from 100 to 150) and type this in the command prompt: python manage.py makemigrations python manage.py migrate I then committed the changes and it allowed me to type more characters in but when I submitted the post it came up with a database error saying the fields can only take 100 characters. How can I get the database to recognize the change in max_characters? -
Django Superuser no longer working after implementing social login
I have recently implemented Social Login to my Django site (which is working), but have encountered an issue where if I create a superuser using the terminal that superuser login does not work. Middleware Section of Settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django_babel.middleware.LocaleMiddleware', 'graphql_jwt.middleware.JSONWebTokenMiddleware', 'saleor.core.middleware.discounts', 'saleor.core.middleware.google_analytics', 'saleor.core.middleware.country', 'saleor.core.middleware.currency', 'saleor.core.middleware.site', 'saleor.core.middleware.taxes', 'social_django.middleware.SocialAuthExceptionMiddleware', 'impersonate.middleware.ImpersonateMiddleware'] Authentication part of Settings.py AUTHENTICATION_BACKENDS = [ 'saleor.account.backends.facebook.CustomFacebookOAuth2', 'saleor.account.backends.google.CustomGoogleOAuth2', 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend'] Any help is really appreciated -
Mark_safe is not working not escaping a href link in an error message
I am trying to send a error message to an ajax call to Django but it is still escaping. The output is 'Please receive ...'. What's missing here? views.py if request.is_ajax(): error_messages = { 'registered': _('Already registered.'), 'inactive': _('Please receive <a href="/activation/">a new activation key here</a>.'), } email = request.POST['email'] try: user = user.objects.get(email=email) if user.is_active: message = error_messages['registered'] else: message = error_messages['inactive'] return HttpResponse(mark_safe(message)) in JQuery $.ajax({ url: url, data: {'email': email}, type: 'POST', }).done(function(msg) { if (msg) { $('.alert').text(msg); }); -
Getting latitude and longitude from postcodes.io with JsonResponse - Django 1.11
I have this method: def postcodes(request): with open('core/stores.json') as f: data = json.load(f) for i in data: postcode = i.get('postcode') resp = requests.get('https://api.postcodes.io/postcodes/{}'.format(postcode)) i.update({'latitude': resp.json().get('latitude'), 'longitude': resp.json().get('longitude')}) data.sort(key=itemgetter('name')) return JsonResponse(data, safe=False) This should compare the file stores.json against postcodes.io api, and return latitude and longitude of each postcode inside the json file. The thing is, that in this case, it's just loading the latitude and longitude of the first postcode in my json file, and not the other ones, also, it just says null on this one: name "St_Albans" postcode "AL1 2RJ" latitude null longitude null 1 name "Hatfield" postcode "AL9 5JP" 2 name "Worthing" postcode "BN14 9GB" 3 name "Rustington" postcode "BN16 3RT" ... and so on This is how the json file looks like: [ { "name": "St_Albans", "postcode": "AL1 2RJ" }, { "name": "Hatfield", "postcode": "AL9 5JP" }, { "name": "Worthing", "postcode": "BN14 9GB" }, ... and so on It just loads latitude and longitude for the first one, but I'm thinking, should this be an issue with postcodes.io itself? -
Bypassing Django's authentication and user model completely
So this is for a homework assignment where I have open choice to use any technology I want. Its a Databases course so the only requirement is that all my SQL should be raw and written by myself. I have been successful in doing that with everything, EXCEPT the user model. What i'd like to achieve is basically use an existing database prepopulated with usernames and plain text passwords for authentication. Since this is homework, security is not a concern at all, the program will never go online. I just want to use my existing database for authentication. My code is littered with LoginRequiredMixins etc so I need for my authentication to return a user object but bypass Django's user model fields and hashed passwords etc. I would also like to use my own field names for login etc. Instead of username and password, I'd like to have email and PIN. I do not need any sign up pages or the ability for anyone to sign up, just what already exists in my table. Any resources you could point me to or help on how one would achieve this? Thanks. -
django Date time input
I need a datetime in the form with day, hours and minutes, but it just is not showing up from django.forms import ModelForm from django import forms class DateTimeInput(forms.DateTimeInput): input_type = 'datetime' class MovRotativoForm(forms.ModelForm): class Meta: model = MovRotativo fields = '__all__' widgets = { 'checkin': DateTimeInput(), 'checkout': DateTimeInput(), }