Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get necessary file for django pythonanywhere app ssl installation from namecheap ssl
I just activated an ssl through namecheap and received the zip file of my certificate in the form of mydomain_com.zip. It contains three files: mydomain_com.ca-bundle mydomain_com.crt mydomain_com.p7b To install ssl on my pythonanywhere django web app I need to create a combined-cert.pem and a private-key.pem. I was able to get the certificate and the certificate bundle from the .ca-bundle and .crt files but I cannot find the private key that is necessary in saving into a .pem extension to install. Any help is much appreciated. Thanks. -
Render button for user to download file in Django Template
I am trying to render a button on Django Template which would let user download a file . I have used the following code for Template HTML {% load static %} <form method="get" action="hi.csv"> <button type="submit">Download Operation 1 Output</button> </form> I have modified url.py to include index/hi.csv otherwise error page was showing . path('index/hi.csv', include('myapp.urls')) I have read the below links to no luck : Allow users to download files directly django Django: let user download a large file https://docs.djangoproject.com/en/2.0/howto/static-files/ I need a quick solution for now . I don't want to use Nginx or Apache as it will take time to learn those technologies . Please advise -
How to run django test when managed=False
I have some models that have managed=False. because of this, my tests fail due to not being able to find tables I've followed this link https://dev.to/patrnk/testing-against-unmanaged-models-in-django and then https://github.com/henriquebastos/django-test-without-migrations to set up a custom test runner. The runner does run, but i still run into the same problem, and I don't know why. My django version is 2.1 How do I test when managed=False? -
Django GoogleCloud JSON show 500
I'm currently working on a DJango project with google cloud for University and faced a problem I don't know how to solve.I tried searching for it but found nothing. I'm beginner with both technologies so sorry for bad code. Summary: On local host it is returning json correctly and is able to use it in js to show table with books. On google cloud after using "gcloud app deploy" it show json correctly in browser but in js in line with "ajax.send();" show error 500. Other Json lists on gcloud work correctly. Here is code for DJango: doesn't work: def favoriteBookList(request): bookListt = Profile.objects.get(user=request.user) #after commenting this line it work bookList = bookListt.favorite.all() testt = [1,2,3] for x in range(bookList.count()): testt.append(bookList[x].bookId.id) data = Book.objects.filter(id__in=testt).values() data = list(data) return JsonResponse(data, safe=False) work fine: def allBooksList(request): data = Book.objects.all().values() data = list(data) return JsonResponse(data, safe=False) Here is code for js: <script> var a = 0; var ajax = new XMLHttpRequest(); var method = "GET"; var url = "page_with_json"; var asynchronous = true; ajax.open(method, url, asynchronous); ajax.send(); ajax.onreadystatechange = function(){ if (this.readyState === 4 && this.status === 200){ var data = JSON.parse(this.responseText); var table = document.getElementById("tableBooks"); table.innerHTML = ""; while(a<data.length){ var bookName = … -
Can't validate field in CBV with django-ckeditor
I have view (CBV) with django-ckeditor on front-end side. Everything is working, but I can't validate text field (is mandatory), when I'm clicking "Post comment" button, I don't receive any message that this field is required. Below is my code. form.py class Comment(forms.ModelForm): text = forms.CharField(widget=CKEditorUploadingWidget(), label='', required=True) class Meta: model = Comment form in template: <form action="" method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button type="submit" class="btn btn-primary">Post comment</button> </form> -
correct DRF filter list view endpoint to return multiple objects by id
I want to be able to request multiple db objects by id in a single DRF request via url parameter with a GET request. I read through this stackoverflow post and DRF's docs on filtering against query parameters and thought I understood how to implement but my solution is a little off. It will return a response, but isn't filtering the queryset (multiple id response is {"detail":"Not found."}) views.py @permission_classes((HasAPIAccess, HasUnrestrictedAPIAccess, )) class EventListView(generics.ListAPIView): serializer_class = EventSerializer queryset = Event.objects.all() def get_queryset(self): ids = self.request.query_params.get('ids', None) if ids is not None: ids = [ int(x) for x in ids.split(',') ] queryset = Event.objects.filter(pk__in=ids) else: queryset = Event.objects.all()[0:10] return queryset urls.py router = DefaultRouter() router.register(r'events', EventViewSet) my_patterns = [ url(r'^events/list/(?P<pk>[0-9]+)/$', EventListView.as_view(), name='events-by-id'), url(r'^', include(router.urls)), ] urlpatterns = [ url(r'^$', RedirectView.as_view(url='/v1/')), url(r'^v1/$', schema_view), url(r'^v1/', include(my_patterns)), ]` the goal is to make a GET request like curl -X GET --header 'Accept: application/json' --header 'Api-Key: {{ key }}' 'http://api.foo.com/v1/events/list/?ids=1,2,3,4,5' but currently that's returning {"detail":"Not found."} response if I make a request to curl -X GET --header 'Accept: application/json' --header 'Api-Key: {{ key }} ' 'http://api.foo.com/v1/events/list/2/' I'm getting back the Event.objects.all() queryset. is my url regex wrong for EventListView? thanks -
How put production with django
How i can put on production django project with de mod_wsgi i read the documentation but dont It is not very clear for me please some one suggest Font official i try this config(/etc/httpd/conf.d/django.conf): Alias /static /root/inventarios/static <Directory /root/inventarios/static> Require all granted </Directory> <Directory /root/inventarios/inventarios> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess inventarios python-path=/root/inventarios:/root/inventarios/venv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /root/inventarios/inventarios/wsgi.py when i restart the httpd i dont get errors..but dont start deploy project. Please maybe some one suggest ..!! -
django: views syntax error that isn't true
no matter what i do it seems like it's wrong even though it's right i guess return Response ( {'success': True, 'deleted': is_deleted, 'count': cart.count, 'item_total': cart_item.item_total, 'cart_price': cart.cart_price, 'cart_count':cart_count}, status = status.HTTP_200_OK) it gives me this error return Response ( {'success': True, 'deleted': is_deleted, 'count': cart.count, 'item_total': cart_item.item_total, 'cart_price': cart.cart_price, 'cart_count':cart_count}, status = status.HTTP_200_OK) ^ SyntaxError: invalid syntax any clues? -
Django JWT token not working -rest_framework
I'm trying to set up a JWT auth with Django and rest_framework. I keep getting Authentification credentials were not provided. I'll try to post the code and the request i'm making(which is provided by postman). If i delete the decorators from the view, it works, it also works if i set up basic auth in postman. settings.py JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), } ''' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } ''' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Play', 'rest_framework', #'rest_framework.authtoken' ] views.py @api_view(['GET']) @permission_classes((IsAuthenticated, )) def try_view(request): return HttpResponse('please work') urls.py url(r'^auth/obtain_token/', obtain_jwt_token), url(r'^auth/refresh_token/', refresh_jwt_token), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), And finally, the request i'm making: import requests url = "http://localhost:8000/try/" headers = { 'Content-Type': "application/x-www-form-urlencoded", 'cache-control': "no-cache", 'Postman-Token': "2583de3d-b996-4948-99cb-d47664ca48ec" } response = requests.request("GET", url, headers=headers) print(response.text) -
Django OAuth Toolkit Toen Generation
Using Django OAuth Toolkit, I have authorization_grant_type set to password and skip_authorization set to true. I am able to generate tokens and refresh tokens using curl without an issue using the following command: curl -X POST -d "grant_type=password&username=username&password=password" http://p6ge67ihXcwECuy7Z7iomyv16VlEk4uX6B886UWl:NZK5WUWsdb1oI1aAXAy3EOLx6zbXBrtVEIUoI7pK9ZLpwkMTvIcq3FMycHklGjJazHj4TguPPvpEL1JNmL6uZz594DjNk99nKu6Uq4Z66mM26AWD63D9WO449exUjYq3@localhost:8000/o/token/ But when I try substituting this command with a POST and invoke that POST from a Django view, I get the following: <Response [401]> Unauthorized: /o/token/ Any clue why this happening? My POST code is as follows: data = { 'grant_type': 'password', 'username': 'username', 'password': 'password' } response = requests.post('http://p6ge67ihXcwECuy7Z7iomyv16VlEk4uX6B886UWl:NZK5WUWsdb1oI1aAXAy3EOLx6zbXBrtVEIUoI7pK9ZLpwkMTvIcq3FMycHklGjJazHj4TguPPvpEL1JNmL6uZz594DjNk99nKu6Uq4Z66mM26AWD63D9WO449exUjYq3@localhost:8000/o/token/', data=data) What am I missing? Any help would be greatly appreciated. Thanks. -
Filtering Class-based view (Listview) in django::: UserCheckout matching query does not exist
please I've been trying to fix out this but I have not been able to solve it out. I am getting this error page whenever I try to load the order url locahost:8000/orders/ DoesNotExist at /orders/ UserCheckout matching query does not exist. Request Method: GET Request URL: http://localhost:8000/orders/ Django Version: 1.8.4 Exception Type: DoesNotExist Exception Value: UserCheckout matching query does not exist. Exception Location: /home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/db/models/query.py in get, line 334 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.0 Python Path: ['/home/rayup/hotels', '/var/www', '.', '', '/var/www', '/home/rayup/.virtualenvs/secondenv/lib/python36.zip', '/home/rayup/.virtualenvs/secondenv/lib/python3.6', '/home/rayup/.virtualenvs/secondenv/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages'] Server time: Tue, 13 Nov 2018 18:39:47 +0000 PLEASE HERE IS THE Traceback::: Environment: Request Method: GET Request URL: http://www.rayconsult.com.ng/orders/ Django Version: 1.8.4 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'shop', 'orders', 'crispy_forms', 'django_filters', 'registration', 'bootstrap3', 'cart', 'contact', 'newsletter', 'newsletter1', 'django.contrib.sites'] Installed 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'] Traceback: File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/rayup/hotels/orders/mixins.py" in dispatch 11. return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs) File "/home/rayup/.virtualenvs/secondenv/lib/python3.6/site-packages/django/views/generic/base.py" in … -
django application with postgresql error value too long for type character varying(1)
I a have a problem with django app and POSTGRESQL database with the slug field error : value too long for type character varying(1) I test some app with sqlite database and all work fine but not work in postgresql database,any idea why ? test 1 : class MyModel(models.Model): name = models.CharField(max_length=254) slug_name = models.SlugField(max_length=254) def save(self, *args, **kwargs): self.slug_name = slugify(self.name) super(MyModel, self).save(*args, **kwargs) test 2 : class MyModel(models.Model): name = models.TextField(max_length=500) slug_name = models.SlugField(max_length=500) def save(self, *args, **kwargs): self.slug_name = slugify(self.name) super(MyModel, self).save(*args, **kwargs) test 3 : class MyModel(models.Model): name = models.TextField() slug_name = models.SlugField() def save(self, *args, **kwargs): self.slug_name = slugify(self.name) super(MyModel, self).save(*args, **kwargs) -
Django URLconf loading
I'am reading Django's official docs, and there is this sentence on reverse_lazy(): It is useful for when you need to use a URL reversal before your project’s URLConf is loaded. Could anybody explain what is meant by "URLConf loading"? Thank you in advance. -
django: removed `app_label` in `django_content_types` table?
In a django project, I have moved some models (that are not managed by django) from an app to the root project (the folder containing manage.py). Changed INSTALLED_APPS, appropriately, everything works, tests run etc. The model classes are not managed by django. However, I found in the database that the django_content_types table still lists the models, with the app_label column having the value of the old app. How/when does django use that table? Is it safe to leave it having the old value? If not, what should I change it to? -
django template access to list item by forloop.counter
I want to loop over my model's query set in the Django template. I can do it simply using Django for loop but I can not do it for steps more than 1,Here is my code {% for map in maps %} {% if forloop.counter|divisibleby:2 %} #Here I can access Maps with index of 1,3,5 and .. #How can I access map with index 2,4,6 here at the same time sth like Map[forloop.counter+1] {% endif %} {% endfor %} In fact I want a way to acces Map[forloop.counter+1] in my template but I have no idea how to do that -
Can't use 'from django.contib.auth.hashers import make_password' in my root folder
django.core.exceptions.ImproperlyConfigured: Requested setting PASSWORD_HASHERS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
PUT/Update Foreign Key & Many To Many relationship with just pk, and NOT the whole object
I've got a User model that has a foreign key and many to many relationship with another model. class User(AbstractUser): ''' Custom User model. Countries is a list of countries associated with the user. Home country is a single country object ''' countries = models.ManyToManyField( Country, blank=True, related_name='user_countries' ) home = models.ForeignKey( Country, on_delete=models.PROTECT, null=True, related_name='home_country', ) and class Country(models.Model): ''' Describes the countries, as well as territories of the world. ''' name = models.CharField(max_length=255, null=True, blank=True) top_level_domain = JSONField(null=True, blank=True) alpha2code = models.CharField(max_length=255, null=True, blank=True) alpha3code = models.CharField(max_length=255, null=True, blank=True) calling_codes = JSONField(null=True, blank=True) capital = models.CharField(max_length=255, null=True, blank=True) alt_spellings = JSONField(null=True, blank=True) region = models.CharField(max_length=255, null=True, blank=True) subregion = models.CharField(max_length=255, null=True, blank=True) population = models.IntegerField(null=True, blank=True) latlng = JSONField(null=True, blank=True) demonym = models.CharField(max_length=255, null=True, blank=True) area = models.FloatField(null=True, blank=True) gini = models.FloatField(null=True, blank=True) timezones = JSONField(null=True, blank=True) borders = JSONField(null=True, blank=True) native_name = models.CharField(max_length=255, null=True, blank=True) numeric_code= models.CharField(max_length=255, null=True, blank=True) currencies = models.ManyToManyField(Currency) languages = models.ManyToManyField(Language) flag = models.CharField(max_length=255, null=True, blank=True) regional_blocs = models.ManyToManyField(RegionalBloc, blank=True) cioc = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name The country model itself has a few many to many relationships, and so it is a nested object. When updating my user model with … -
Django & POST from Ajax
I've been trying to get a POST to my Django views with the final goal to send a 'selected' input (from a clicked #id) and have Django send a response which I can dynamicly show. Using GET I'm able to recieve a response but the POST is giving me problems (I could go for GET but at this time I just want to understand why I'm messing up POST...;)) I have used several guides by now but most are about forms and, to be honest, I have trouble following the documentation (I have little to no background in programming). Could someone point me in the right direction? My HTML ('numberinput' is a placeholder for now): <script> $("#test").on(click(function () { numberinput = 8; $.ajax({ type: 'POST', url: '{% url "rungenerator" %}', data: {'numberinput': numberinput}, dataType: 'json', success: function (inputtype) { alert(inputtype) } }) })) </script> <div> <form method="POST"> {% csrf_token %} <button type="submit" id="test">Buzzzz Ping</button> </form> </div> Views: def rungenerator(request): inputtype = "Please make a selection" if request.method == 'POST': inputtype = request.POST['numberinput',None] return JsonResponse(inputtype) URLS: url(r'^ajax/rungenerator/$', views.rungenerator, name='rungenerator'), -
Use Django Call Command With Greater Than Sign As Argument
Is there a way to pass ">" as an argument when using call_command('dumpdata','>','db.json') When using this command from the terminal as python manage.py dumpdata > db.json everything works as expected, but when trying to use it programatically is when the issue occurs. Namely LookupError: No installed app with label '>'. The specific question is "how do I use the > argument in the call_command function." But more generally, is there some fundamental rule that i am misunderstanding about handling this symbol in the call_command function? -
Django send_mail does not work with mailgun
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 587 EMAIL_HOST_USER = 'donotreply@kamiltrojnar.pl' EMAIL_HOST_PASSWORD = 'passwordsecret' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'donotreply@kamiltrojnar.pl' SITE_ID = 2 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Testing email sending From: donotreply@kamiltrojnar.pl To: kamil.trojnar@gmail.com Date: Tue, 13 Nov 2018 17:20:27 -0000 Message-ID: <154212962720.11272.17395367179025062268@DESKTOP-EG7NCN4.home> AS title def index(request): send_mail("Testing email sending", 'AS title','donotreply@kamiltrojnar.pl',['kamil.trojnar@gmail.com'], fail_silently=False) return render(request, 'userpanel/index.html') I get no errors and email. What may be the issue? -
Custom users not superusers from django
I started with Django Rest Framework official tutorial (https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/) earlier today, and I have a question in the authentication and permissions section, If I want to have custom users table, not the default superuser created by Django, is there any feature in DRF that help me with this requirement ?? and if there isn't, is it a good way to use the python manage.py createsuperuser to create a whole table of users that may contain 100 user ?? Im new to python, django, and DRF so thanks for any help. -
Django models - admin: Any ideas to build following Model structure?
I've been trying to solve following Django model design problem: The main object here is a Task object. Each Task consists of (amongst others) following fields: 1 Intro, consisting of 0 or more InstructionWindiws 1 Outro, consisting of 0 or more InstructionWindows A number (1 or more) of Blocks, each consisting of 0 or more InstructionWindows. An Instruction Window is a text field containing HTML. The widget for an InstructionWindow could be a CKEditor. Now I would like the Admin's Task Change View to incorporate a widget for each of above three Fields, each consisting of a TabularInline where the user could add, edit or remove InstructionWindows for each Field (or Blocks of InstructionWindows). I've been struggling with ArrayFields, ForeignKeys, intermediary objects, etc. but I don't see an elegant way to solve the puzzle. ArrayFields seem usable, but there is no usable Widget it seems. Moreover, for the Blocks instructions, this would imply using an Array of Arrays. Any suggestions pointing me in the right direction would be much appreciated! Joris -
request.POST in Django 2.1
This post is a follow-up of this previous question: Django request.POST empty I had a project up and running with Python 3.5.4 and Django 1.11.13, on Visual Studio 2015. I later updated to Django 2.1.2 because I wanted to import the "path" module, so that I can use this: urlpatterns = [ path ( '', c_views.Indice, name = 'indice' ), path ( '<int:CompiladoID>', c_views.Detalle, name = 'detalle'), path ( 'elementos/<int:CompiladoID>', c_views.Elementos, name = 'elementos'), path ( 'datoselementos/<int:ElementoID>', c_views.DatosElemento, name = 'datoselemento'), ...instead of this: urlpatterns = [ url ( r'^$', c_views.Indice, name = 'indice'), url ( r'^(?P<CompiladoID>\d+)/$', c_views.Detalle, name = 'detalle' ), url ( r'^(?P<CompiladoID>\d+)/elementos$', c_views.Elementos, name = 'elementos' ), url ( r'^(?P<CompiladoID>\d+)/generar$', c_views.Generar, name = 'generar' ), which I find easier to declare and read. After this change I started to experience problems with request.POST. I got a "request" response, but POST was empty, as shown here: Actually, I was not initially aware of this. It's taken me 3 days, and a compare with a backup copy that I've recovered, to realize that Django version was different. That said, I'm puzzled about the fact that a newer version of Django should not be able to do something that older … -
Trying to run python manage.py migrate on a djangoFramework project but receiving errors
Following a tutorial on youtube on how to set up and use the DjangoFramework. Tried running python manage.py migrate but I ran into this error and I'm unable to figure out a solution to it. Using mysqlclient and running on a virtual environment django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") -
Django multiple Admin Model
I Wanna use 2 Admin apps such as : django-admin-sortable django-import-export Is there a way to use both in Admin Form ? I mean my code is using SortableAdmin: class RuleAdminForm(forms.ModelForm): content = forms.CharField(widget=CKEditorWidget()) class Meta: model = Rule fields = '__all__' class RuleAdmin(SortableAdmin): list_display = ('title', 'section', 'subsection',) readonly_fields = ('author', 'date_posted') fields = ('title', 'section', 'subsection', 'content', 'author', 'date_posted') form = RuleAdminForm with .register(Rule, RuleAdmin) If I want to use import-export I need to create this : class RuleResource(resources.ModelResource): class Meta: model = Rule class RuleResourceAdmin(ImportExportModelAdmin): resource_class = RuleResource But I can't register with .register(Rule, RuleResourceAdmin) since Rule is already registered Is there a way to have both options ? Using sortable admin to sort my rules, and the possibility to import CSV etc. Many thanks !