Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Delete or Update if 3 object existed at the same time - Django Rest Framework
I'm building LIKE, UNLIKE and CLAPPING function for my blog website. I have models like this: Model REACTION (Like, unlike and clapping) class Reaction(models.Model): REACT_TYPES = ( (LIKE, 'Like'), (CLAPPING, 'Clapping') ) user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE') timestamp = models.DateTimeField(auto_now_add=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') class Meta: unique_together = ('user', 'content_type', 'object_id') Serializers model REACTION from models import Reaction class ReactCreateUpdateSerializer(ModelSerializer): class Meta: model = Reaction fields = [ 'user', 'react_type', 'content_type', 'object_id', ] I assumed there is a object with LIKE available created before. I want to build a function can do these things: If user use again POST methods with 4 objects existed: user, content_type, object_id, react_type=LIKE. It becomes deleting object. (UNLIKE). Then if post one more, it becomes creating object again. (LIKE) If user use POST methods with 4 objects existed: user, content_type, object_id, react_type=CLAPPING. It becomes updating the available reactions in database with update 2 fields: react_type and timestamp, all other fields not changed. I think this is a problem for every one when he build API for website needs reaction. So Hope your enthusiastic help. Thanks in advance! -
What django model field should I use to store a duration of time less than a full day?
I am storing the duration of time for a time keeping system. No need to store timezone info. Initially I decided to store the value a a DecimalField because there was a restriction of closest 15 minutes meaning the decimal would work as it would be restricted to 0.25 increments. Eventually I decided that is no good as what if in future the 15 minute increments requirement is removed. I do not need to store seconds I need to report on totals at the end of the month So I pretty much have these 3 data types and I am struggling to choose which would be best. TimeField PositiveIntegerField DurationField -
Python firebase admin sdk - Realtime update listener
Do you have any plan to add realtime update listener in python firebase admin sdk? I have django api service.I want to change my current authentication and authorization system to firebase authentication.Realtime data update listener is not available for python .So I have to call firebase server every time to authorize my user.It will make my api slower.What to do now for django in this situation? Thanks in advance. Goutom Roy -
ValueError: invalid literal for int() with base 10: '' Can't I cast int to None?
I got an error,ValueError: invalid literal for int() with base 10: '' . I wrote def convert_json(request): id = None print(type(id)) json_body = json.loads(request.body) for index, content in json_body.items(): if index == "ans": id = content id = int(id) return id When json_body does not have "ans" key,id has None and the error happens in the code of id = int(id) .print(type(id)) print out class 'str' so I really cannot understand why I cannot convert str into int.Is None special kind of str?I wanna put empty value to id when json_body does not have "ans" key.How should I fix this? -
Django error after changes to the model.py and then migrations
So before everything went south, i have this user model with a mobileNo attribute, it is using a CharField at first. So i decided to change it to IntegerField then proceed to do the makemigrations then migrate command. But suddenly this error pop up after doing that Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\operations\fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "C:\Users\Baka No Onii Chan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\postgresql\schema.py", line … -
Django page not found 404
i get this error while i am trying to run my django server and i am getting the following error I don't know why and the urls file is in the myproject/test/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('wars.urls')), ] myproject/test/settings.py ROOT_URLCONF = 'test.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] in the same folder I have another folder wars which has the urls too , in myproject/wars/ursl.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^auth/$', views.authenticate_for_token, name='authenticate'), url(r'^records/all/(?P<token>[1-9]_[a-z]*)/$', views.records_list_all, name='records_all'), url(r'^records/(?P<offset>[0-9]*)/(?P<limit>[1-9][0-9]*)/(?P<token>[1-9]_[a-z]*)/(?P<comp_code>[0-9]{2,8})/$', views.records_list_subset, name='records_all'), url(r'^records/save/$', views.records_save, name='records_save'), url(r'^dropdown/(?P<comp_code>[0-9]{2,8})/(?P<token>[1-9]_[a-z]*)/$', views.get_dropdown_lists, name='dropdown_lists'), url(r'^approve/$', views.approve_category, name='approve_category'), url(r'^approve/delete/$', views.approve_category_delete, name='approve_category_delete'), url(r'^hide-sheet/$', views.hide_sheet, name='hide_sheet'), url(r'^hide-sheet/delete/$', views.hide_sheet_delete, name='hide_sheet_delete'), url(r'^template/download/$', views.template_download, name='template_download'), url(r'^template/upload/$', views.template_upload, name='template_upload'), url(r'^overview/$', views.Overview.as_view(), name='admin_overview'), url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', views.logout_func, name='logout'), url(r'^user/$', views.UserManagement.as_view(), name='user_mgmt'), url(r'^user/upsert/$', views.user_create, name='user_create'), url(r'^debug/$', views.debug_func, name='debug'), ] I am trying to figure out the problem. it seems that i cant reach the page. and in the python server it says Not Found: / [27/Nov/2017 09:44:54] "GET / HTTP/1.1" 404 5189 -
How to delete a django model from an application to result in a table drop
I have a django model in my app that looks like this(assuming all required modules are imported) class profile(models.Model): user = models.OneToOneField(User) mobile_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="phone number must be entered in hte format '+23474857934'. Up to 15 digits allowed") mobile = models.CharField(validators=[mobile_regex], max_length=15, blank=True, null=True) I made a (silly)mistake spelling the profile name, and would like to correct this, is there a way to this without affecting the data that might already be stored. changing the name and making a migration doesn't reflect the change sorry if this question seems a bit trivial,I'm a newbie at django thanks for understanding -
django model field default function calls two times
I've got model FTPUser. Field password populates automatically by function pass_generator. class FTPUser(models.Model): ...... password = models.CharField(max_length=250, default=pass_generator) def pass_generator(size=12, chars=string.ascii_letters + string.digits): passwd = ''.join(random.choice(chars) for _ in range(size)) return passwd Model FTPUser is managed in django admin: class FTPUserAdmin(admin.ModelAdmin): readonly_fields = ['password', ] As shown above, field password is read only and when admin creates new instance in FTPUser model he can't change field password, only read it(what I need), vaule of password field generates by function. The problem is django calls function pass_generator two times! First time, when inicializes create form and second time whem saves instance to database. So in database we got absolutely different password than was shown to admin! I tested to set password filed editable and in that case it works correctly, so I think probles is when password filed is read only it shown as string at creation, not an inpun filed, so on save model FTPUser doesn't get that vaule from creation form and calls function pass_generator second time. How can I solve this? -
Workaround for missing Distance function in Django 1.8
Let consider the following models: class Event(models.Model): name = models.CharField(max_length=255) class Address(models.Model): event = models.ForeignKey(to=Event,related_name='addresses') coordinates = models.PointField() Now I want to find events within some proximity. I can do this: Event.objects.filter( addresses__in=Address.objects.filter( coordinates__distance_lte=(my_location, D(km=42)) ) ) However, I also want to have the distance value in that queryset but I don't know how to annotate this. In latest Django, I could use https://docs.djangoproject.com/en/dev/ref/contrib/gis/functions/#distance How can I achieve this 1.8? -
Unable to integrated bootstrap template into django (python)
I am new to Django and python. I am struggling with integrating bootstrap template into my simple django application. I tried all "static" related django stuffs at (https://docs.djangoproject.com/en/1.11/howto/static-files/) but not get solution yet. When I check under "Network" in Google chrome browser console all css, Javascript & images are loaded successfully and gives "200" code. But at the time of execution classes are not applied and simple html page appears. Project directory structure and template are loaded here : https://github.com/husainathar/parking/tree/master/parking Please advise me to resolve this issue. Thanks -
How to use authentication token in Django with Django OAuth Toolkit (not REST)
I'm using the following library http://django-oauth-toolkit.readthedocs.io/ which seems to not be as well documented as I would like, and after I followed its tutorial I am able to have a working system in which I have protected views that need the authorization token, and I can access them using curl and adding the token. Curl is nice to test, but it's not practical, and I failed at developing it. So I have a very simple protected view: class Test(ProtectedResourceView): def get(self, request, *args, **kwargs): return HttpResponse('Hello, OAuth2!') If I try to access, I will get a 403, and if I ask for the token and put it in the header using curl I can actually get it to work. In the other hand, I have another view that gets the authorization_token, lifetime, refresh_token, .. in a dictionary (after using JSON from Django). At this point I'm lost. I don't know what to do with the authorization token so that the user can actually use it and access to the protected view. I tried to manually add the token to the cookies but it didn't work and doesn't seem to be a good idea neither. I guess after I do something, … -
Remove inline styles from django-tinymce html content
When I save content through django-tinymce it adds its own inline styles. However I'd like to remove this behaviour and just save the content in plain html. Can you please help me on this issue? -
TastyPie custom API key authorization
I am new TastyPie guy, I would like to ask some questions about TastyPie API. post/models.py class Tweet(models.Model): PRIVACY_CHOICES = ( ('0', 'Public'), ('1', 'Private'), ) name = models.CharFile(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) privacy = models.SmallIntegerField(choices=PRIVACY_CHOICES) I would like to create some APIs to: Get all posts with privacy is public (0) api/v1/post/ Owner can see/update/devete private posts (need api_key - api/v1/post/1/) User can create new post with all fields not empty (need api_key) Thanks all -
Python post forms error for manytomany relationship
My approach to creating a new instance of a new Media_Group object is: (views.py) #pk=="-1" is what i passed in as a URL parameter group_instance = None if(pk=="-1"): #Create new group group_instance=Media_Group() else: #If we're selecting an existing group from the list group_instance=get_object_or_404(Media_Group, pk = pk) #If we are editing or creating a new page we will need to submit a form... Lets do that: form = GroupForm(request.POST,pk) if form.is_valid(): group_instance.members = form.cleaned_data['members'] group_instance.name = form.cleaned_data['group_name'] group_instance.save() return HttpResponseRedirect(reverse('edit_group') ) #if pk =="-1" then lets create a new Media_Group and create a title and members if (pk == "-1"): return render( request, 'edit_group.html', context={'form': form, 'group_instance':group_instance,'all_user_groups': all_user_groups, 'user': user, 'group_members': group_members,'no_group_selected':False}) (forms.py) class GroupForm(forms.Form): group_name = forms.CharField(label='group_name',max_length=50) members = forms.ModelMultipleChoiceField(label='group_name', queryset=Member.objects.all()) class Meta: model = Member fields = ['name'] When I attempt to submit a form I get an error "<Media_Group: >" needs to have a value for field "id" before this many-to-many relationship can be used. From my understanding I need to create an id field to identify this new object and allow it to be reference but I'm not sure how to go about doing that. I also may be entirely wrong and if anyone has a suggestion … -
Deleting a table in django 1.11
How to delete an entire db table including its structure and data of a particular app? I already tried python manage.py flush. But I think it just deletes the data. I want to delete the entire table. I am using Django 1.11.4 and sqlite3 database. -
Serializing Django M2M
I am trying to serialize a django model with a many to many field in order to get them into Elasticsearch. I am not using DRF: #! usr/local/bin/python3.6 # coding: utf-8 from django.db import models from django.core.urlresolvers import reverse from .aw_search import EntryIndex class Tag(models.Model): tag = models.CharField(max_length=100, default='') slug = models.SlugField(max_length=100) class Meta: verbose_name = "Tag" verbose_name_plural = "Tags" def __str__(self): return self.slug def get_absolute_url(self): return reverse('list', kwargs={"slug": self.slug}) class Entry(models.Model): title = models.CharField(max_length=100, blank=False, null=False) slug = models.SlugField(max_length=100) content = models.TextField() posted_date = models.DateTimeField(auto_now=True) chron_date = models.DateField(auto_now=False, auto_now_add=False, blank=True) clock = models.TimeField(auto_now=False, auto_now_add=False, blank=True) ALIGN = "Align" CULTURE = "Culture" EXPENSE = "Expense" INCOME = "Income" HUMAN_RELATIONSHIPS = "Human Relationships" CATEGORY_CHOICES = ( (ALIGN, "Align"), (CULTURE, "Culture"), (EXPENSE, "Expense"), (INCOME, "Income"), (HUMAN_RELATIONSHIPS, "Human Relationships"), ) category = models.CharField(max_length=25, choices=CATEGORY_CHOICES, default=INCOME) tags = models.ManyToManyField(Tag) class Meta: verbose_name = "Diary Entry" verbose_name_plural = "Diary Entries" ordering = ["-chron_date", "clock"] def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={"slug": self.slug}) def indexing(self): obj = EntryIndex( meta={'id': self.id}, title=self.title, chron_date=self.chron_date, text=self.content, category=self.category, tags=(self.tags.values_list('tag',)) # this is my ongoing stumbling block ) obj.save() return obj.to_dict(include_meta=True) An 8 year old bug report https://code.djangoproject.com/ticket/11310 indicates that: when you have a through relationship, you need to … -
Django RF, React, Heroku & Amazon S3 - Correct file storage
I'm using a django backend, which merely serves as an api server (no templates and HTML files are rendered). On the frontend I use react and redux to access this api and render content. The question is, should I use Django to connect to Amazon S3 and have corresponding FileField() or should I instead use React to connect to Amazon S3 and then in my django models use a CharField() to store the URL to the file? -
How to write a custom exception for TemplateView and APIView in Django which will return custom error for request.
I have written class CustomApiException(APIException): #public fields detail = None status_code = None # create constructor def __init__(self, status_code, message): #override public fields CustomApiException.status_code = status_code CustomApiException.detail = message CustomApiException.message = message which is working for APIView but for TemplateView it gives error. What is the proper way to write custom API Exception which will work for both views. -
Django UpdateView and ChoiceField issue. Django 1.11 python 3.6
I am facing a strange problem while implementing ChoiceField and UpdateView in django. I have made a small clip showing the problem that I am facing. Please watch it with subtitles/cc enabled. It will give an idea about the problem I am facing. https://youtu.be/M36TnlJvrZs. The problem goes like this..... During CreateView, I set the 'gender' ChoiceField as 'Female'. But in UpdateView it pre-populates the 'gender' ChoiceField as Male. However, The ListView renders the 'gender' field properly as 'Female'. And strangely, the django admin panel, displays no value at all for the 'gender' field. Here are all the codes: models.py: from django.db import models from django.core.urlresolvers import reverse gender_choices = (('Male', 'Male'), ('Female', 'Female')) class Birth(models.Model): full_name = models.CharField(max_length = 100) gender = models.CharField(max_length=6, choices=gender_choices) date_of_birth = models.DateField() place_of_birth = models.CharField(max_length = 50) mother_name = models.CharField(max_length = 50) father_name = models.CharField(max_length = 50) address_at_time_of_birth = models.TextField(max_length = 500) permanent_address = models.TextField(max_length = 500) registration_no = models.CharField(max_length = 50) remarks = models.CharField(max_length = 200) registration_date = models.DateField() issue_date = models.DateField() def get_absolute_url(self): return reverse('birth:birth_update', kwargs={'pk':self.pk}) #return reverse('birth:birth_home') def __str__(self): return self.full_name forms.py: from django import forms from .models import * class BirthForm(forms.ModelForm): full_name = forms.CharField() gender = forms.ChoiceField(choices = gender_choices, widget=forms.Select()) date_of_birth … -
Gunicorn 'Worker failed to boot' when running Dockerized Django application
I have a distributed Dockerized application, with four services: Django, Postgres, Caddy. All three are hosted privately on Docker Hub. I am attempting to get them running via Docker Cloud with a DigitalOcean node. The problem is with the Django service, which runs with Gunicorn. When I attempt to start the service, I get the following error: [django-1]2017-11-27T05:58:33.944903048Z Postgres is unavailable - sleeping [django-1]2017-11-27T05:58:35.176033131Z Postgres is up - continuing... [django-1]2017-11-27T05:58:36.023305930Z DEBUG 2017-11-27 00:58:36,023 base 8 140468605011712 Configuring Raven for host: <raven.conf.remote.RemoteConfig object at 0x7fc15b2b59b0> [django-1]2017-11-27T05:58:37.755913984Z 0 static files copied. [django-1]2017-11-27T05:58:38.117470416Z [2017-11-27 05:58:38 +0000] [12] [INFO] Starting gunicorn 19.7.1 [django-1]2017-11-27T05:58:38.118213362Z [2017-11-27 05:58:38 +0000] [12] [INFO] Listening at: http://0.0.0.0:5000 (12) [django-1]2017-11-27T05:58:38.118423391Z [2017-11-27 05:58:38 +0000] [12] [INFO] Using worker: sync [django-1]2017-11-27T05:58:38.122410705Z [2017-11-27 05:58:38 +0000] [15] [INFO] Booting worker with pid: 15 [django-1]2017-11-27T05:58:38.127667063Z [2017-11-27 05:58:38 +0000] [16] [INFO] Booting worker with pid: 16 [django-1]2017-11-27T05:58:38.131574049Z [2017-11-27 05:58:38 +0000] [17] [INFO] Booting worker with pid: 17 [django-1]2017-11-27T05:58:38.219843431Z [2017-11-27 05:58:38 +0000] [18] [INFO] Booting worker with pid: 18 [django-1]2017-11-27T05:58:38.702716621Z [2017-11-27 05:58:38 +0000] [23] [INFO] Booting worker with pid: 23 [django-1]2017-11-27T05:58:38.876025732Z [2017-11-27 05:58:38 +0000] [24] [INFO] Booting worker with pid: 24 [django-1]2017-11-27T05:58:39.063798754Z [2017-11-27 05:58:39 +0000] [26] [INFO] Booting worker with pid: 26 [django-1]2017-11-27T05:58:39.312288894Z [2017-11-27 05:58:39 +0000] [28] [INFO] … -
Why is Django not taking the integer in the DB and displaying it in the HTML template?
I have the following basic code, which is meant to get number X, add a simple value "+1" just as proof of concept, then save that number back into the database. Also, I require a Django based, jinja template to pull that number and render it onto a website. My question is, why is the number failing to show up? I only get a blank space where the number is supposed to be rendered and if I remove the [:1] filter, the div is generated 3x; this tells me that the issue might be somewhere in that line but I am at a loss. The code is: /views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import Context, loader from home.models import DeathNum def index(request): counter = DeathNum.objects.get(pk=1) fj = counter.deaths t = loader.get_template('home/basenum.html') c = {'number_post': str(fj)[:1]} return HttpResponse(t.render(c)) def increment(request): counter1 = DeathNum.objects.get(pk=1) counter1.deaths += 1 counter1.save() t = loader.get_template('home/basenum.html') c = {'number_post': str(counter1)[:1]} return HttpResponse(t.render(c)) /models.py: from django.db import models class DeathNum(models.Model): deaths = models.IntegerField() def __str__(self): return "{0}/{1}\n".format(self.id, self.deaths) /basenum.html: {% extends "home/index.html" %} {% block content %} <br /> <div class="banner"> <div class="bannerNum"> <p div class="numberOf"> Number of deaths in Blank since 1999: … -
annotate a label to query based on thresholds that it falls within
I am trying to label my results based on two properties of my query set which falls within each combination of two threshold of another query. Here is a piece of code for clarification: threshold_query = threshold.objects.all() main_query = main.ojbects.values( 'Athreshold', 'Bthreshold' ).annotate( Case( When( Q(Avalue__lte=threshold_query['Avalue']) & Q(Bvalue__lte=threshold_query['Bvalue']), then=Value(threshold_query['label']) ... ) ) ) the model for thresholds is like: class threshold(models.Model): Avalue = models.FloatField(default=0.1) Bvalue = models.FloatField(default=0.3) label = models.CharField(default='Accepted') so there is a matrix that decides the labels. Is it possible to obtain what is in my mind using one query? my purpose is to minimize the number of queries due to enormity of Data. -
Error - NoReverseMatch
I am stuck with this : < a href="{% url 'newapp:home' %}" > revWaves< /a> Error message is : "NoReverseMatch" Reverse for 'home()' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have created namespace for 'newapp' and url path is also correct i.e. /static/newapp/home.html and above < a href="{% url 'newapp:home' %}"> revWaves< /a> goes into header.html So i am not able to figure out what is the error. Kindly help. -
How can I get JSON from request?
How can I get JSON from request?I wrote codes, @csrf_exempt def get_json(request): print(request) return HttpResponse('<h1>OK</h1>') I post data to POSTMAN like but print(request) print out <WSGIRequest: POST '/app/get_json'> . I wanna get json in this part.So I wrote print(request.text) but error happens.Why can't I get it?I think request has json data,but is it wrong?How can I do it? -
How to convert String "[7, 9]" to Array in Javascript
I'm getting this string. (I'm getting Comma Separated Character String from Backend) "seasons": "[7, 9]" I want to iterate the array of Array like this. // example this.props.data.seasons.map((element) => console.log(element)); How do we convert "[7, 9]" to Array [7, 9]? Is it usual for you guys to handle array string?