Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Swagger with OAuth2 authentication
I have a REST API created with Django rest framework. To authenticate my API calls I am using OAuth2 tokens. My question is how can I enable standard username/password authentication in docs generated by Django rest swagger. Right now i am gettings 401 : {"detail":"Authentication credentials were not provided."} http://127.0.0.1:8000/docs/?format=openapi settings REST_FRAMEWORK = { # Don't perform any authentication on API calls so we don't have any CSRF problems # :PRODUCTION: Put back authentication for production version when not testing on same server? 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.ext.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'PAGE_SIZE': 1000, # Max number of results returned from a list API call 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), # Use JSONRender so the Web API interface is not shown. This is needed when testing the app on the same server 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'veeu': { 'type': 'oauth2', 'flow': 'password', 'tokenUrl': 'http://localhost:8000/auth/token/', 'scopes': { 'write:all': 'Write all', 'read:all': 'Read all', } } }, } LOGIN_URL = 'http://localhost:8000/admin/' When I click Django login it takes me to admin login page. And after I log in, this message is still the same. If I add header Authorization: Bearer TokenHere it works. However, the point is to enable … -
How heroku run python manage.py migrate?
I deployed a simple Django app in Heroku Steps: - git push heroku master - heroku run python manage.py makemigrations ( or + app_name) it seem to affect: 0002_main.py: - Create model Comment - Remove field status from match - Remove field quantity from slot - Add field avatar to account - Add field slots to match - Alter field verification_code on account - Alter field verification_code on slot - Add field match_object to comment - Add field user to comment - Alter index_together for comment (1 constraint(s)) then I run - heroku run python manage.py migrate but i received: Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. -
Django exception handling cancels non-atomic transaction mode
Best described by example. Consider the following code (Django 1.9) View: @transaction.non_atomic_requests def error_generating_view(request): modelA = ModelA(...) modelA.save() if (some_bad_condition) json_error_msg ('') return HttpResponse(True) View in other module def json_error_msg(error_message): return JsonResponse(json.dumps(error_message, ensure_ascii=False), status = 500, safe = False) Django seems to through an exception to client-side, but the problem here is that modelA instance is saved, although I set up @transaction.non_atomic_requests. It looks like I am doing something wrong with exception handling syntax. Could anyone point to what exactly I should rectify here to make Django through customized exception message to client and simultaneously treat the entire view as terminated incorrectly so that the transaction is rolled back ? -
How to fix KeyError: 'DJANGO_DEBUG' on Django 1.10
I am getting following error while executing migrate command "python manage.py migrate". File "/Users/Jhon/djangowww/project/app/blog/settings.py", line 29, in <module> DEBUG = os.environ['DJANGO_DEBUG'] == 'True' File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'DJANGO_DEBUG' How can recover from this issue? -
Django - create a new object based on another object by prefilling the form and corresponding inline formsets
I want to offer users the possibility to create a new publication based on an existing publication. To do that, I want them to click a link to "basedview" that contains the id of the publication they want the new item to base on. There are two formsets for n:n relations included. that should open a prefilled form with all fields prefield with the data from the publication it's based on. once the user has made changes as needed, it should then save a new publication and new relations for the fieldset - the latter being the difficult part of it. So my question is - how can I load all corresponding formsets from the database and then delete all their pk but still keep the relation to the publication item? Right now it is like this in the get method: self.object = None try: self.object = KombiPublikation.objects.get(pk=self.kwargs['pk']) except ObjectDoesNotExist: raise Http404("Keinen Output unter dieser PubID gefunden.") form = KombiPublikationForm(instance=self.object) pubspr_formset = KombiPublikationSpracheFormset(instance=self.object) pubpers_formset = KombiPublikationPersonFormset(instance=self.object) But that ends up to be just an edit of the existing publication. I somehow have to delete the pk after I populated the formset or find a way to populate the formset differently. … -
How to pass an argument from SnippetChooserPanel to a django-template
in my-django-project, I've successfully implemented a wagtail-driven app that allows to reference the model Map() of my-django-projectas a snippet in wagtail/admin(as described here). My problem now is that when I choose (in the SnippetChooserPanel) the instance of Map() to be integrated in my wagtail template, my choice gets lost and my template renders all the instances found in Map() table. This is because my choice in SnippetChooserPanel is not passed to the wagtail-app template. my wagtail-app/models.py class HomePage(Page): [..] maps = models.ForeignKey( 'maps.Map', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) [..] class Meta: verbose_name = "Homepage" HomePage.content_panels = Page.content_panels + [ [..] SnippetChooserPanel('maps') ] my-django-project.maps.templates.maps/maps.html {% load wagtailimages_tags wagtailadmin_tags %} {% load i18n %} {% for map in maps %} <div class="col-xs-4 item-thumb"> <a href="{{ map.detail_url }}"><img src="{{ map.thumbnail_url }}" /> </a> </div> {% endfor %} my-django-project.maps.templatetags/maps_tags.html from django import template from geonode.maps.models import Map register = template.Library() # Map snippets @register.inclusion_tag('maps/maps.html', takes_context=True) def maps(context): print("QUI \n") return { 'maps': Map.objects.all(), 'request': context['request'], } my wagtail-app.templates/home_page.html {% load maps_tags %} <div class="mine"> [...] {% maps %} </div> I'm new to Wagtail and there is not much documentation on SnippetChooserPanel handling.. Do you have any hints? Thank you in advance for any help … -
Can a model be related to another model using both one-to-many and many-to-many relationships?
Say you want to develop an app where the employees of a company can send each other messages. Here is a simplified version of the models: class Message(models.Model): message_to = models.ForeignKey(Employee, related_name="%(app_label)s_%(class)s_related_message_to") message_from = models.ForeignKey(Employee, related_name="%(app_label)s_%(class)s_related_message_from") message_cc = models.ManyToManyField(Employee, related_name="%(app_label)s_%(class)s_related_rfi_cc") message_date = models.DateTimeField() message_body = models.TextField() message_document = models.CharField(max_length = 30, choices = DOCUMENTS) class Employee(models.Model): first_name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) email = models.EmailField(max_length = 70) employer = models.ForeignKey(Company, related_name = 'employees') Then, in the forms.py: class MessageForm(ModelForm): class Meta: model = Message fields = ['message_from', 'message_to','message_cc', 'message_date', 'message_body'] The tables are created in the database, but it gives me the error: FieldError: Unknown field(s) (message_ccmessage_document) specified for Message Any help is much appreciated -
Django `bulk_create` with related objects
I have a Django system that runs billing for thousands of customers on a regular basis. Here are my models: class Invoice(models.Model): balance = models.DecimalField( max_digits=6, decimal_places=2, ) class Transaction(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, ) invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, related_name='invoices', null=False ) When billing is run, thousands of invoices with tens of transactions each are created using several nested for loops, which triggers an insert for each created record. I could run bulk_create() on the transactions for each individual invoice, but this still results in thousands of calls to bulk_create(). How would one bulk-create thousands of related models so that the relationship is maintained and the database is used in the most efficient way possible? Notes: I'm looking for a native Django solution that would work on all databases (with the possible exception of SQLite). My system runs billing in a celery task to decouple long-running code from active requests, but I am still concerned with how long it takes to complete a billing cycle. -
Validação em django
Gostaria de saber como eu faço pra salvar uma certa quantidade de alunos em vagas. como faço pra permitir que só sejam salvos 5 alunos? Já tentei de várias maneiras, porém ainda não consegui :( Class Turma(models.Model): descricao = models.CharField(max_length=50) vagas = models.PositiveIntegerField() horario = models.CharField(max_length=5,choices=HORARIO_CHOICES,null=False,blank=False,verbose_name='Turno') ano = models.PositiveIntegerField(null=False,blank=False) semestre = models.CharField(max_length=1,choices=SEMESTRE_CHOICES,null=False,blank=False) aluno = models.ManyToManyField(Aluno,verbose_name='Aluno') professor = models.ForeignKey(Professor,verbose_name='Professor') def __str__(self): return str(self.descricao) -
Django doesn't see translations in app folders
So Django Translations. I have this file structure: /backend # Here I store the whole project with frontend stuff, server configs and so on |-env # Virtualenv stuff |-web # Root Django folder |---root # Thus is the module with settings |---common # This and 'common' are app modules |-----locale # I only create this folder, Django creates all the following |---locale # I created it, when I tried to fix this problem. # Django So, I use gettext in my common module, then I do makemessages, and it all goes fine, po-files are created in common/locale folder. First time I got an idea, that I do something wrong, was when django-rosetta package hadn't shown me strings from common module, only from root module. Nevertheless, I translate my strings to a few languages and then do compilemessages, and it also goes as expected, mo-files are created, the content is there. My problem is, that Django's JSONCatalog view doesn't show any of my strings. I've tried two different view setups: from django.views.i18n import JSONCatalog # First one urlpatterns = [ url(r'^i18n/', JSONCatalog.as_view(), name='json_catalog'), ] # Second one urlpatterns = [ url(r'^i18n/', JSONCatalog.as_view(packages='common'), name='json_catalog'), ] First one returns strings from all of … -
How to pass a tag from a tag in django?
I have a custom template filter, that replaces different markdown with html tags, so, for example, [b][/b] is replaced with <b></b> etc. And I need to replace the link to a video surrounded by [video] markdown with an actual video tags. I found an application 'django-embed-video' that handles all possible formats and can embed youtube videos. To use it, I need to include a {% video %} tag in a template. But is there any way to pass that tag as a return value from another tag (my filter). Do you have any ideas how could I do it without copying a logic from embed-video app into my filter? -
django manage.py reported a fatal error: Python/modsupport.c:91 object at 0xb63f0e2c has negative ref count -1246818113
django version: 1.10.3, python version: 2.7.12, [GCC 4.6.3] on linux2, i updated the python from version 2.6 to 2.7.12, there is no problem in the progress of python installation. unfortunately when i run command "python manage.py makemigrations show", there is a fatal error occoured. inf@inf:/opt/lampp/htdocs/dpcm$ python manage.py makemigrations show Fatal Python error: Python/modsupport.c:91 object at 0xb63b1e2c has negative ref count -1247076161 Aborted (core dumped) II tried python commands and run other scripts, this will won't happen. -
Django REST same API for different countries
I have an ecommerce system belongs to each country. My datas in the database is seperated based on country values. But I should have same API deploy as one webserver. and return the products to each country specific. My domain names for each country country1.abc and country2.xyz. When user enters to country specific webpage it should return only that country products. How can I differentiate the api (UI code also same) ? And DB also replicate to each country. because Sometimes I need to scale for only one country data. Whats is the best approach to do it in Django. -
Performing Raw SQL Queries with Django
I'm looking for create some SQL queries with Django but I don't have a display result. This queries are very important because I would like to configure a research bar used by client. For example : A user wants to search all people in my table which are named 'Dupont' and living in New-York In my views.py, I have written something like that : def Test(request) : cursor = connection.cursor() cursor.execute('''SELECT * FROM BirthCertificate_people WHERE `name` = "Dupont" AND `city` = "New-York"''') row = cursor.fetchone() print row template = loader.get_template('test.html') return HttpResponse(template.render(request)) In my template file test.html : <h2 align="center"> SQL Queries display </align> </h2> {% block content %} <!-- What I write there --> {{ }} {% endblock %} I don't know How I can display the SQL queries results in my .html file. I read some tutorials : Django Raw SQL Query but none results for the moment .. Thank you so much ! -
Docker with a django website
I have to dockerise a django app but i don't know if it is possible to link it with gunicorn, nginx, supervisor , anaconda and mongoDB. I need one or many conteners for that ? -
Django-phonenumber-field error in Production
I am using django-phonenumber-field battery for my django app (django 1.9, python 3.5). I have form like follows: class PhoneChangeForm(forms.Form): phonenumber = PhoneNumberField(widget=PhoneNumberPrefixWidget(attrs={'placeholder': _('Phone number')}), label=_("Enter phone")) def clean_phonenumber(self): users = User.objects.filter(profile__phone__iexact=self.cleaned_data['phonenumber']) if users.count() == 0: return self.cleaned_data['phonenumber'] else: raise forms.ValidationError(_("This phone is already in use.")) In my development environment this form works normally. If there is user with given phone number then ValidationError is raised. When I am moving the same code into Production I have following error: Django Version: 1.9.6 Exception Type: ProgrammingError Exception Value: can't adapt type 'PhoneNumber' Creators don't respond to the last comments so I decided to ask here. Can you suggest the best way to debug it? -
Loading image with Django
For some reason I cannot get my images to upload with Django. The models are saving the filename but saving the file in my media folder. This is my Model class Quiz(models.Model): name = models.CharField( verbose_name ='Quiz Title', max_length = 50 ) description = models.TextField( blank = True, null = True, verbose_name = 'Quiz Description' ) pool = models.ForeignKey ( Pool, verbose_name = 'Category of Quiz', ) categories = models.ManyToManyField ( Category, through = 'QuizCategory', related_name = 'category', verbose_name = 'Category', help_text = 'Categories in this Quiz' ) live = models.BooleanField ( verbose_name = 'Quiz is Live?', default = False, ) logo = models.ImageField( upload_to = 'logos', blank = True, ) def __unicode__(self): return u'%s' % (self.name) This is my View def create_quiz(request): if request.method == "POST": try: quiz = Quiz.objects.get(id=int(request.POST.get('id'))) except: quiz = Quiz() quiz.name = request.POST.get('name') quiz.description = request.POST.get('description') quiz.logo = request.POST.get('logo') quiz.pool = Pool.objects.get(name=request.POST.get('pool')) quiz.save() Help most welcome. Thank you -
Displaying nested entities in Django REST Framework
I would like to display nested entities in the Django REST response – not hyperlinked entities or primary keys - the actual entity inside the parent. This would look something like this: { 'id': 5 'name' : 'blah' 'children' : [ {'id' : 77, 'foo' : 'bar'}, {'id' : 78, 'foo' : 'bar'}, ... ] } This is mentioned in the REST documentation as one possible way of representing relationships between entities, but the documentation doesn't indicate how it can be done. -
Change php code with inbuilt php functions into python code (django)
I have to implement a payment gateway it is paystation payment gateway, They have provided their code in php but my project is in django framework, so i need to convert its code into python(django) code, I am new to python previously worked on php. The code that i have to change in python is $amount = ($_POST['amount'] * 100); $paystationId = 'dummy Id'; //Paystation ID - Replace PAYSTATIONID with your Paystation ID. $gatewayId = 'PAYSTATION'; //Gateway ID - Replace GATEWAYID with your GATEWAY ID. $merchantRef = urlencode('from sample code'); //merchant reference is optional, but is a great way to tie a transaction in with a customer (this is displayed in Paystation Administration when looking at transaction details). Max length is 64 char. Make sure you use it! $testMode = 'true'; //change this to 'false' for production transactions. $hmacMode = false; //change this to 'true' to use hmac and also change the next variable $hmac_security_code = 'hmac-security-code'; // change this to the Paystation supplied security code $merchantSession = urlencode(time().'-'.makePaystationSessionID(8,8)); $paystationUrl = "https://www.paystation.co.nz/direct/paystation.dll"; $paystationParameters = "paystation=_empty&pstn_pi=".$paystationId."&pstn_gi=".$gatewayId."&pstn_ms=".$merchantSession."&pstn_mr=".urlencode($merchantRef)."&pstn_am=".$amount."&pstn_nr=t"; if ($testMode == 'true'){ $paystationParameters = $paystationParameters."&pstn_tm=t"; } /* If hmacMode is true generate hmacParameters */ if($hmacMode){ $hmacParameters = generateHMACParams($paystationParameters,$hmac_security_code); } $result = doPostRequest($paystationUrl, $paystationParameters, … -
Direct link to an item in a ListView
Let's say I have a ListView that looks like this: class CarsListView(ListView): model = Car paginate_by = 5 and a model Car: class Car(models.Model): created = models.DateTimeField() brand = models.CharField(max_length=30) class Meta: ordering = ("created",) The CarsListView is working correctly showing me all cars ordered by created. So far, so good. Instead of creating a DetailView for each car, I want to add a view that redirects incoming requests for a specific car to the CarsListView on the correct page. class CarsRedirectView(RedirectView): def get_redirect_url(self, *args, **kwargs): car = Car.objects.get(pk=kwargs["pk"]) # stuck here return "hmm?" All I really need to know here is on which page the car is. One way to do this is to fetch all Car objects and count the pages until I hit the car. Is there a better way? -
Django multiple input field values with same name
i need to help.. how i can handle the form with multiple input field values with same name? and only once view, this actually for basic questions form.. another idea i found this method from http://stackoverflow.com/a/478406/6396981: relations = request.POST.getlist('relations') but the how i can handle it all? currently im doing with <input type="radio"..., but of course it couldn't work if has same name in once form. but if i use <input type="checkbox"..., the answers can be check more than 1 in once question... maybe like this: <input type="radio" name="answer-{{ question.id }}"> but how i can get it all in the view? -
Django: Update distinct queryset updates all records
For a reason I don't understand, When i create a distincted queryset and update it, Django updates all the items in the queryset as if it wasn't distinct in the first place for example: items = Item.object.filter(SOME-FILTERS).order_by('gender').distinct('gender') items.update(quantity=F('quantity') - 1) the result is 2 rows update If I iterate over items it updates only 1: for item in items: item.quantity -= 1 item.save() -
interpolate_text's text doesn't get translated, yet variables do
I have this code in django 1.18.13 and Python 2.7.10 <%= interpolate_text('You are taking "{exam_link}" as a {exam_type} exam. The timer on the right shows the time remaining in the exam.', {exam_link: "<a href='" + exam_url_path + "'>"+gtLtEscape(exam_display_name)+"</a>", exam_type: (!_.isUndefined(arguments[0].exam_type)) ? exam_type : gettext('timed')}) %> The part where it says "You are taking" doesn't get translated, yet the arguments {exam_type} do, same for "The timer...". The string with its variables is found in the PO files in this format msgid "" "You are taking \"{exam_link}\" as a {exam_type} exam. The timer on the right shows the time remaining in the exam." msgstr "" "أنت تتقدم لـ \"{exam_link}\" كـ {exam_type} م. الوقت المتبقي يظهر على يسار الشاشة. " I am running out of ideas why text interpolation doesn't get translated. Any help would be appreciated. -
Limit Django self-referential foreign key to anything but itself
I have a regular self-referential foreign key: idol = models.ForeignKey("self", on_delete=models.CASADE) The admin page allows me to choose the the same object id. How can I prevent the admin from showing it? -
HTTP headers list
I am studying Django and have created a page that shows all HTTP headers in a request using request.META dictionary. I'm running it locally and it the page shows me a weird amount of headers like 'TEMP' containing the path to my Windows temp folder, or 'PATH' with my full path parameters and much more information that I don't really find necessary to share in my browser requests (like installed applications). Is it normal? What do I do about it?