Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does gunicorn and django logging interact?
I have a Django app which I'm serving with Gunicorn. When I add --access-logfile=-, I get the access log to stdout, but when I add LOGGING to settings.py that looks like this: LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, } } the Gunicorn access log stop going to stdout. Why is that? I do get this: [2018-11-09 15:46:53 +0000] [19] [INFO] Starting gunicorn 19.9.0 [2018-11-09 15:46:53 +0000] [19] [INFO] Listening at: http://0.0.0.0:8000 (19) [2018-11-09 15:46:53 +0000] [19] [INFO] Using worker: sync [2018-11-09 15:46:53 +0000] [22] [INFO] Booting worker with pid: 22 which I understand is coming from gunicorn, but no further output from gunicorn. -
Django rest framework add extra context in response
I am using a updateapiview to the update my user information. This is my view class UserUpdateView(generics.UpdateAPIView): serializer_class = UserUpdateSerializer def get_queryset(self): print(self.kwargs['pk']) return User.objects.filter(pk=self.kwargs['pk']) def partial_update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, partial=True) if self.get_object() != request.user: return Response({'error': 'permission denied'}, status=status.HTTP_400_BAD_REQUEST) print(request.data['password']) request.data['password'] = make_password(request.data['password']) instance = super(UserUpdateView, self).partial_update(request, *args, **kwargs) return instance This is my serializer class UserUpdateSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) def validate_username(self, username): if User.objects.filter(username=username): raise serializers.ValidationError('Username already exists!!') return username def validate_email(self, email): if User.objects.filter(email=email): raise serializers.ValidationError('Email already exists!!') return email class Meta: model = User fields = ('pk', 'username', 'password', 'email') read_only_fields = ('pk',) I am getting the data updated and returned successfully. But I want to add some field like message with content 'successfully updated' on successful updation of the user profile. I searched if there is any way to perform this but can't find the appropriate way to do it (alike get_context_data method in django). So, is there any way to perform the above task ?? Question 2: How to prevent the self user ( i.e if has a email sample@gmail.com and if user clicks udpate with the same email, it should not raise an error that username already exists, I guess … -
request.BODY is empty in django 1.11 gae app in ajax call
I updated my django google app engine application from 1.2 to 1.11 and do "revelant" steps (python 2.7), such as urlpatterns = patterns('', url(r'^$','froom.views.index', name='index'), to urlpatterns = [ url(r'^$',views.index, name='index'), and start to use django cripsy forms. while I run 1.2 version and post form, and get request.POST has dict value with posted form values, however with 1.11 version, request.POST is empty. request.POST = <QueryDict: {}> I double check my ajax calls comes with Content-Type: application/x-www-form-urlencoded; charset=UTF-8 as noted here My method stays same: def edit_tenant(request, tenant_id=None): if (request.method == 'POST'): if tenant_id: tenant_id_int = long(tenant_id) tenant_org = db.get(db.Key.from_path('Tenant', tenant_id_int)) form = TenantForm(request.POST, instance = tenant_org, prefix = "edittenant") django settings.py as below: working version one's: TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates'), ) none working version one's: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(os.path.dirname(__file__), 'templates'), os.path.join(os.path.dirname(__file__), 'myapplication'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] What could be issue that upgraded versions request.POST is empty? -
Standard way to load initial (and ongoing) data into Django
Suppose I have a model with a field that restricts another model. For example, a Thing whose name has to be in the current set of AllowedThingNames. The set of allowed_thing_names changes (infrequently) by an external source. I have code to get that external source and create AllowedThingNames as needed. Here is some code: models.py: class AllowedThingName(models.Model): name = models.CharField(max_length=100, unique=True) class Thing(models.Model): name = models.CharField(max_length=100) def __save__(self, *args, **kwargs): if AllowedThingName.objects.filter(name=self.name).exists(): return super().save(*args, **kwargs) return None tasks.py: @shared_task def import_new_names(): response = request.get("some/external/url/where/allowed/names/are/listed") new_names = clever_way_of_parsing_response(response.content) for new_name in new_names: AllowedThingName.objects.get_or_create(name=new_name) I have created a fixture of AllowedThingNames and I run the loaddata command at startup. I'm not sure what the best way is to keep the set of AllowedThingNames up-to-date, though. One solution is to periodically (via a task, or a cronjob, or whatever) call the import_new_names function above and then call dumpdata to overwrite the fixture. This will save it in the db and make sure that it gets re-loaded the next time the project restarts. Does anybody in StackOverflow-Land have any better ideas? -
jQuery Datatables - Can't get input value from hidden pages
I have this table in my HTML: <table> <thead> <tr> <th>Id</th> <th>Actual weight</th> <th>New weight</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10</td> <td><input data-id="{{ object.id }}" type="number" name="input_new_weight" /></td> </tr> <tr> <td>1</td> <td>20</td> <td><input data-id="{{ object.id }}" type="number" name="input_new_weight" /></td> </tr> <!-- multiply by 10 the number of trs --> </tbody> </table> And I have this code in my javascript to get the input values: var new_weights = [] $("input[name='input_new_weight']").each(function(index, element){ if( $(this).val() != "" ){ var object_new_weight ={ id: $(this).data('id'), new_weight: $(this).val() } new_weights.push(object_new_weight); } }); console.log(new_weights); I'm using jQuery DataTables plugin to generate the tables and have the possibili ty to filter, paginate, ordenate and etc. In some tables I have more than 10 entries, so the paginations works here. In the example above, it will be 2 pages: 1 and 2. When my javascript code is executed, it does only gets the inputs values from the visible table page. The inputs from the hidden pages are not get! Let's suppose that in page 1 I put the new weight values as 35, 75 and 80 and in the page 2 I put 40, 54, 97. When my javascript code runs, it does just get the values from the … -
How do "apps" work from django's point of view?
First of all, the question is technical, not conceptual. The docs mention, in various places, that you are supposed to put in INSTALLED_APPS the root module of your app. However, what is that module supposed to contain? Most of the files created by startapp myapp are just there by convention. For example urls, views, admin files are imported from other modules by fully qualified name, and could really be anywhere, so they are just conventions. The only thing that seems to be "hard-coded" in the django logic is the models.py. So, from the INSTALLED_APPS point of view, does an app consist solely of its models.py? Or is there something else I'm missing? And does the documentation explicitly state this anywhere? -
How to access self.function from global class scope
How to pass Foo.finished callback into doSmthAsync. Is it possible somehow to access self while doSmthAsync(callback=self.finished) definition. import doSmthAsync from library class Foo: doJob = doSmthAsync(callback=self.finished) def finished(): pass For those who will suggest to reconstruct code: I know a lot of tricks how to workaround of it. But question is about accessibility of self while doSmthAsync(callback=self.finished) definition. -
Attribute in django django dispatch method
Below is the dispatch method in django view class def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) Can any one please tell me where the attribute .method defined ??which is used in the conditional (if request.method.lower() in self.http_method_names:) -
get django ajax request.POST and utf-8 problem
1. I had to send request.POST a dict of dict, big_dict = {k:{kk:vv, kk1: vv1}, k1:{kk:vv, kk1: vv1}} and ajax always somehow made it into one dict like one_dict = {k[kk]:vv, k[kk1]:vv1, k1[kk]:vv, k1[kk1]:vv1} someone told me to JSON.stringify(big_dict) before ajax request and then json.loads it in my python django views. json.loads(request.POST.get('data')) it worked all damn fine till someone uploaded a chinese charter named file. at the third step of json.loads in my view, the key and value of my big_dict is still good, looking fine, displaying proper chinese charcter. but when I try to for k, v in big_dict.items(): for kk, vv in v.items(): # do something with kk and vv chinese characters within vv becomes all wrong. and os is telling me no such file. It looked like a simple problem, I searched a web for over an hour and tried things, nothing worked.. Thanks anyone in advance for helping me out. -
Replacing an old table with a new one in the Django database?
Hi I am working on a Django Project and added the functionality of importing a csv file to the Django database using the following code class UploadFileForm(forms.Form): file = forms.FileField() def import_csv(request): if request.method == "POST": with open('C:/Users/admin/Desktop/Projekt/test2.csv') as file: reader = csv.reader(file) for column in reader: p = CSV(gebäude=column[0], etage=column[1], raum=column[2], dose=column[3]) p.save() return redirect('upload:index') form = UploadFileForm() return render( request, "upload/csv_upload.html", {"form": form} ) However if i make changes to the csv file and add it to the database it just adds everything and I have the data basically twice in the table. I would like to know if there is any option to just replace the old data in the table with the changed data, instead of just adding it to the table. I use the standard sqlite3 database. This is the csv file 25.41, 1, 21, 10 25.42, 2, 22, 14 25.43, 1, 23, 13 25.44, 3, 24, 12 25.45, 2, 25, 11 25.46, 0, 15, 23 This is my models.py class CSV(models.Model): gebäude = models.CharField(max_length=100) etage = models.CharField(max_length=100) raum = models.CharField(max_length=100) dose = models.CharField(max_length=100) And my Html form <h2>Upload CSV</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> Any help would be … -
Calling a custom middleware after Authentication Middleware
In django REST framework authentication middleware sets the user object in request ONLY after the views middleware is executed while any common custom middleware is executed before that. is there someway to change this order and execute custom middleware AFTER user object is set by authentication middleware As an alternative I create the user object in the middleware itself and it works fine but this is just a hack. -
Django template: {% if 5 in ['4', '3', '5'] %} doesn't work
form.tickets.value has the values ['29', '4', '7'] ticket_id has values such as 5, 3, 7 etc. Now I want to print YES if 7 exist in the list. But it always says 'No'. Anyone can tell me why? {% if ticket_id in form.tickets.value %} YES {% else %} {{ ticket_id }} not in {{ form.tickets.value }} {% endif %} -
Combine multiple models into one serializer using drf and also using the model field values as the model field name in viewset response
I have the following model: class KeyValue(models.Model): key = models.CharField(max_length=20) value = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Url(models.Model): url = models.CharField(max_length=200, null=True, blank=True) meta = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Doc(models.Model): card = models.CharField(max_length=30, null=True, blank=True) required = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) My seriliazers: class UrlSerializer(serializers.ModelSerializer): class Meta: model = models.Url class DocSerializer(serializers.ModelSerializer): class Meta: model = models.Doc class KeyValueSerializer(serializers.ModelSerializer): hybrid = UrlSerializer(read_only=True, many=True) legal = DocSerializer(read_only=True, many=True) class Meta: model = models.KeyValue fields = ['key', 'value', 'url', 'doc', 'created_at'] Is it possible to output the response in my viewset to be like this? { "key_entry_1": "value_entry_1", "key_entry_2": "value_entry_2", "urlConfig": { "urls": [ { "url": "one.com", "meta": true | false, }, { "url": "two.com", "meta": true | false, }, { "url": "three.com", "meta": true | false, } ], }, "documentConfig": { "docs": [ { "card": "0000", "required": true | false }, { "card": "1111", "required": true | false }, ], }, "created_at": "iso 8601 date", } With key_entry_1 and value_entry_1 be each value for the Keys Table. So instead of using the model field name, the response returns the values of each field in the database. My viewset currently is as … -
Django get mails from gmail 100 users
I need to come up with one thing. I have 100 users in system, these users was authorized(and registration on the django system) by google account. I need connect to gmail account by each of user of 100 and read emails from gmail. I cant understand how i can do it. I need connect by imap4 to gmail, but i have only user email, Authorization code(by google), Refresh token and Access token(need refreshing). May be someone did something like -
RESTAPI Versioning through headers Django
I'm trying to create my API versioning through the header Content-Type value. I'm using Django, Django Rest Framework and Django Rest Framework JSON API. I was able to create a Middleware to set the request urlconf depending on the value received. from __future__ import unicode_literals import re from reservas import settings from django.urls import set_urlconf # settigns.py # HTTP_HEADER_ROUTING_MIDDLEWARE_URLCONF_MAP = { # 'application/vnd.api.v1+json': 'v1.apps.urls' # } class VersionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: for content_type in settings.HTTP_HEADER_ROUTING_MIDDLEWARE_URLCONF_MAP: if request.META.get('CONTENT_TYPE') == content_type: url = settings.HTTP_HEADER_ROUTING_MIDDLEWARE_URLCONF_MAP[content_type] set_urlconf(url) request.urlconf = url request.urlconf except AttributeError: request.urlconf = settings.ROOT_URLCONF return self.get_response(request) -
PUT request to Django API to update list of objects with Many To Many relationships
I have a user model with a ManyToMany relationship with another Model class User(AbstractUser): countries = models.ManyToManyField(Country, blank=True) count = models.IntegerField(blank=True, default=0) def save(self, *args, **kwargs): # Must save model before Many To Many relationship can be used. super(User, self).save(*args, **kwargs) self.count = self.countries.count() super(User, self).save(*args, **kwargs) and my country model is a rather large model: 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 I'm trying to make a put request from my frontend to update the list of countries associated with (data is sent as an array of objects … -
How to impliment infinite scroll in Django with pure JavaScript?
I have a problem on return JSON response manly. Couln't find any solution. -
Django: Checkboxes are not saved while FormValidationError
I am working with a CreateView. When sending my form with all fields properly filled out, the field tickets (ManyToMany field) is also saved. However if I POST my form with some validation error (e.g. required field empty), then all the pre-filled fields are still field through request.POST. However, my pre-checked fields are not selected anymore. Do you know why? Demonstration view.py class DiscountCreate(AdminPermissionRequiredMixin, SuccessMessageMixin, FormValidationMixin, BaseDiscountView, CreateView): form_class = DiscountForm template_name = 'discounts/admin/create.html' success_message = _("Discount Code has been successfully created.") def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['event'] = self.request.event return kwargs def get_success_url(self): return reverse('discounts:admin:detail', kwargs={ 'organizer': self.request.organizer.slug, 'event': self.request.event.slug, 'discount': self.instance.pk }) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['type_fixed'] = Discount.TYPE_FIXED context['type_percentage'] = Discount.TYPE_PERCENTAGE return context def form_valid(self, form): self.instance = form.save(commit=False) self.instance.event = self.request.event self.instance.status = Discount.STATUS_ACTIVE return super().form_valid(form) Template <div class="card"> <div class="card-header"> <h4 class="card-header-title"> {% trans "Creating Discount Code" %} </h4> </div> <div class="card-body"> <form method="post" autocomplete="off" novalidate> {% csrf_token %} <div class="form-group"> <label for="{{ form.code.id_for_label }}"> {{ form.code.label }} </label> {{ form.code }} {% if form.code.errors %} <div class="invalid-feedback d-block"> {{ form.code.errors|first }} </div> {% endif %} </div> <div class="form-group"> <label for="{{ form.type.id_for_label }}"> {{ form.type.label }} </label> {{ form.type }} {% if form.type.errors … -
pip install gives error after installing anaconda
I am using Zsh. I had installed Anaconda a while back and presently when I tried to upgrade my pip I dot permission denied error even when used sudo. This is the result I got Also when I tried to install django it gave error Sorry for the less descriptive question. I am new to python and anaconda , so I don't know how to work with them. -
accessing django View variable inside angularjs
I have view function like this.(This is just sample data) def query(request): period_sum = [556,336,789] year = [2016, 2017, 2018] return render(request, "search_bar/query.html", {'period': period_sum, 'year': year}) Now I am trying to iterate this period and year using AngularJs at query.html page. As I know, inside verbatim tag, I cannot access Django variable. I also tried this links to get to some idea but it didn't work for me link! Can anyone help to figure out how can I access Django variable inside the Angular code. My angular code at html page look like this {% verbatim %} <div ng-app ng-controller="MyCtrl"> <ul> <li ng-repeat="data in {{period}}">{{data}}}</li> </ul> </div> {% endverbatim %} -
Django models don't work with Oracle database
I have several apps with different database connections. They all work fine. My new app needs an Oracle connection, which is set up in the settings.py: 'database_oracle' : { 'ENGINE' : 'oracle', 'NAME' : 'name', 'USER' : 'user', 'PASSWORD' : 'pw', 'HOST' : 'connection', 'PORT' : 1234, 'SCHMEA' : 'abc', }, The models in my models.py have additional meta classes: class Meta: db_table = '"abc.table1"' data_source = 'database_oracle' data_source_app = 'myapp' The problem is that Model1.objects.all() returns an error: ` django.db.utils.DatabaseError: ORA-00942: table or view does not exist But if I use the django.db connection: from django.db import connections db_conn = connections['database_oracle'] c = db_conn.cursor() c.execute("SELECT MAX(date) FROM abc.table1 WHERE key = 1234567").fetchall() It works perfectly fine. So I tried different spellings for db_table: db_table = 'table1' db_table = '"table1"' db_table = 'abc.table1' db_table = '"abc.table1"' Changes were migrtated every time and this is how my routers.py look like (the if-statements belong to other apps and other databases): myapps = ['myapp'] class DataRouter: def db_for_read(self, model, **hints): if [...] elif model._meta.app_label in myapps: return 'database_oracle' return None def db_for_write(self,model, **hints): if [...] elif model._meta.app_label in myapps: return 'database_oracle' return None def allow_relation(self, obj1, obj2, **hints): if [...] elif obj1._meta.app_label in … -
Django Nginx Staticfiles not showing in AWS
I have a Django project that I added to AWS. in the development server the site works perfectly fine however I am not able to get my static files to my aws site Below is my project Tree and static files are in the project Below is my settings.py Below is my nginx server I have checked the paths. they are good. However for some reason when I run the site from AWS it is not getting the staticfiles also when I got to the admin page. The static files for admin are not in there too. HOw can I get my static files in AWS -
Django 2 dev server logging issue
In old django(1.7)/ubuntu(14) we would run the development server in our local projects (from sys upstart) and then tail the upstart file generated: sudo tail -f /var/log/upstart/myapp.log While the django server ran, you could edit files, hit refresh in browser, and see all logging information. Most importantly though, if you created an error in one of your .py files, the server would stop, and print the usual error, once you have fixed the error the server would spot you've changed a file and reboot. Since upgrading to django2 and ubuntu18, Upstart isnt a thing anymore we're suppose to use journalctl, and we're no longer getting all the prints we used to have. Now we log to a file, (see below) which I can tail, but if I cause an error in a .py file (press Save), it prints that the dev server has restarted - cos ive changed a file - but it never shows me the error. If I fix the error, the server restarts, then prints the error - and continues as normal. Here is my settings.py logging object: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'filelog': { 'level':'DEBUG', 'class':'logging.FileHandler', 'filename': '/var/log/app/myapp.log', }, }, 'loggers': { … -
How to serialise the Model with the list containing querysets of that model?
class DummyModel(models.Model): dummyId = models.AutoField(primary_key=True) assetId = models.CharField(max_length=250) bounds = models.CharField(max_length=1000) Now i have dummylist containing queryset of DummyModel dummylist=[<QuerySet [<DummyModel>]>, <QuerySet [<DummyModel>]>] Now i have serialiser like this class DummySerialiser(serialiser.ModelSerialiser): class Meta: model=DummyModel Now i need to generate a json in with list of dummymodel { {"dummyId":1, .... }, {"dummyId":2, .... } } Any pointers on this would be a great help. Thanks in advance.!! -
jsonpickle - Wrong JSON format
I'm trying to use jsonpickle to send an Object to front-end in JSON format. Here is the code: #some code here... return render( request, 'template.html', { 'json_values': jsonpickle.encode(values), } ) But, when I try to echo the string generated in my javascript code I'm getting this result when I call console.log({{json_values}}): [{'&quotid&quot: 7, &quotnovo_peso&quot: &quot13&quot}, {&quotid&quot: 13, &quotnovo_peso&quot: &quot17&quot}] See the image below in console: I'm using the last Google Chrome version. Am I doing something wrong? Thank you