Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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(), } -
Create model method using fields from two different models?
I am trying to create a model method that takes data from a field in one model and performs simple arithmetic using data from a field in another model. I am not trying to create a QuerySet in views.py, rather I am trying to create a model method in models.py that I can easily access via a context variable in my html (e.g. obj.model.modelmethod). Below is a very simplified version of my models (before adding the desired model method): class Person(models.Model): ''' This table serves as the ultimate parent. ''' id = models.IntegerField(auto_created=False, primary_key=True) name = models.CharField(max_length=128, null=True, blank=True) def __str__(self): return self.name class SalaryYearOne(models.Model): id = models.OneToOneField( Person, on_delete=models.DO_NOTHING, db_constraint=False, primary_key=True ) salary1 = models.IntegerField(null=True, blank=True) class SalaryYearTwo(models.Model): id = models.OneToOneField( Person, on_delete=models.DO_NOTHING, db_constraint=False, primary_key=True ) salary2 = models.IntegerField(null=True, blank=True) The model method I want to create will be under the SalaryYearOne class. The goal is calculate the salary percent change year-over-year (rounded to two decimal places). For example: class SalaryYearOne(models.Model): ... def salary_percent_change(self): return round((self.salary1 - self.salary2) / self.salary2, 2) The aforementioned is more for illustrative purposes. I understand that there are several issues with it as written. For example, I understand that the SalaryYearOne table does not … -
Django, URL and Views not found
I'm using Django 2.1 and testing views.py and urls.py What I don't understand is why whenever I enter the URL http://127.0.0.1:8000/blog/post_list I get a 404 error message My top urls.py: from django.urls import path from django.contrib import admin from django.conf.urls import include, url from organizer import urls as organizer_urls from blog import urls as blog_urls urlpatterns = [ path('admin/', admin.site.urls), path('', include(organizer_urls)), path('tag/', include(organizer_urls)), path('startup/', include(organizer_urls)), path('blog/', include(blog_urls)) ] my application's urls.py from django.urls import path from blog.views import post_list, post_detail urlpatterns = [ path('', post_list, name='blog_post_list'), path( '<int:year>/<int:month>/<slug:slug>', post_detail, name='blog_post_detail'), ] my application's views.py: from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): return render( request, 'blog/post_list.html', {'post_list':Post.object.all()} ) def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) the error message is: Using the URLconf defined in suorganizer_project.urls, Django tried these URL patterns, in this order: admin/ tag/tag_list [name='organizer_tag_list'] tag// startup/startup_list [name='organizer_startup_list'] startup// [name='organizer_startup_detail'] tag/ startup/ blog/ The empty path didn't match any of these. -
Django 1.11:Apps aren't loaded yet
I'm learning how to do web programming with Django framework and I got this error message when I try to return a template. When I try to load https://www..../index2/ everything is ok. This is my urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^index2/$', views.index2, name='index2'), ] This is my views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, 'main/index.html',) def index2(request): return HttpResponse("Hello, world.") -
django warning urls.W005 URL namespace isn't unique
I am having trouble understanding the following warning. I have a namespace called "v1" and I am using these namespaces to determine versioning in my API (using django rest framework). So, I have paths like these: /v1/accounts/me /v1/listings Here is the URLs configuration (project/urls.py): urlpatterns = [ path('admin/', admin.site.urls), path('v1/accounts/', include('accounts.urls', namespace='v1')), path('v1/listings/', include('listings.urls', namespace='v1')) ] accounts/urls.py app_name = 'accounts' urlpatterns = [ url(r'^token/$', views.obtain_auth_token, name='obtain_token'), url(r'^me/$', my_account, name='my_account'), ] listings/urls.py app_name = 'listings' urlpatterns = [ path('', recent_listings, name='recent_listings') ] Everything works as expected. All urls are dispatched. Versioning works. However, I keep getting the following error: ?: (urls.W005) URL namespace 'v1' isn't unique. You may not be able to reverse all URLs in this namespace I know it is a warning and I might be able to suppress it; however, I want to understand why this is happening. Based on my URLconf and this warning, it seems like there cannot be multiple namespaced paths as "siblings." They need to be children of one namespaced path (e.g "v1"). If my understanding is correct, how am I supposed to create this URL configuration. -
Using postcodes.io API on Django
I'm trying to achieve this: Use postcodes.io to get the latitude and longitude for each postcode and render them next to each store location in the template I have a series of postcodes into a json file: [ { "name": "St_Albans", "postcode": "AL1 2RJ" }, { "name": "Hatfield", "postcode": "AL9 5JP" }, { "name": "Worthing", "postcode": "BN14 9GB" }, { "name": "Rustington", "postcode": "BN16 3RT" }, { "name": "Eastbourne", "postcode": "BN23 6QD" }, ... And so on... I need to check on postcodes.io[0] the latitudes and longitudes of these postcodes, and render these coordinates next to the json result. My question isn't about on how to render them, it's about on how to POST my json postcodes on their website, and get the respective latitudes and longitudes of each one. I'm doing this on pure python, any ideas? 0.- https://postcodes.io/docs -
API url routing - Django/Postman
I am messing around with a backend Django API tutorial (Django 2.1) and I am having trouble pulling 'profile' information via Postman. My assumption is that I am not correctly stating my url in my urls.py. Here is my project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('conduit.apps.authentication.urls'), name='authentication'), path('api/v1/', include('conduit.apps.profiles.urls'), name='profiles') ] Here is my profiles.urls.py: from .views import ProfileRetrieveAPIView urlpatterns = [ path('profiles/<username:username>/', ProfileRetrieveAPIView.as_view()) ] I think my issue has to do with how I am implementing / to the end of my path. My only other relevant experience with this kind of mechanism was on prior projects where I was using something like this for unique blog post url routing (which I have done successfully): ".../<slug:slug>/" Now, here is my relevant class-based view for the above url: class ProfileRetrieveAPIView(RetrieveAPIView): permission_classes = (AllowAny,) renderer_classes = (ProfileJSONRenderer,) serializer_class = ProfileSerializer def retrieve(self, request, username, *args, **kwargs): try: profile = Profile.objects.select_related('user').get( user__username=username ) except Profile.DoesNotExist: raise ProfileDoesNotExist serializer = self.serializer_class(profile) return Response(serializer.data, status=status.HTTP_200_OK) You can see in my retrieve function, I am working with a username attribute. This is what I think I am trying to match up with my url path. I am guessing that I am probably not … -
Empty Set using fitler startswith
Here's my model: class Student(models.Model): name = models.CharField(max_length=100) student_id = models.IntegerField() grade = models.IntegerField() I imported the data from Excel.I want to use Student.object.filter(name___istartswith = _ ) because every Student.name instance as "\xa0" before it. I've tried: .filter(name___contains= _) works (but is not what I need) Replacing "\xa0" with s.name.replace("\xa0",'') did...nothing. The "\xa0" returned! .filter(name___istartswith = u_ ) Every time I run Student.objects.filter(name__istarts with = _) an empty set is returned. I'm sure it's something dumb, but what am I doing wrong? (Running python 3.5) -
Django relationships in models
I have a problem with creating relationship for models. I tried to use ForeignKey to complete structure like this: Tech -> Firm -> Model -> type of fix Tech can have different objects, for example computer, phone, or tablet. At this moment, I got problem. Computer can include firms of phones. How I can fix it? uml-scheme of my structure for this moment: https://i.stack.imgur.com/KvRfw.png