Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Formatting into td element in table
For a table, I have a th element called 'Tags'. For a td, I have a Queryset that contains what I want for the tags. For example, Queryset ['wipers', 'cars', 'Test']. I want to format the td element in a way where the objects are 'Wipers,cars,test' in a single td element. Image of current td element -
Setting timezone in Django
Similar question has been asked a lot of times, but somehow none of answers actually explains how timezone support in Django works. After reading Django documentation on the topic i still don't understand why my datetime instances in database keep being one hour different (earlier) than actual time I've put in the Form. In settings.py I've enabled timezone support and set it to the timezone I'm currently in: USE_TZ = True TIME_ZONE = 'Europe/Vienna' Yet if I do simple check: print(timezone.now()) print(datetime.datetime.now()) timezone.now() gives me wrong time, which is one hour earlier, datetime.datetime.now() on the other hand gives me my actual (correct) time. As a result of this all my records in DB (Postgres) are stored with 1 hour difference (earlier) than the time I provide in Forms. What have I done wrong and is there any additional configuration needed? -
Why is Idle Python Thread Consuming upto 90% of CPU?
This is my first threading program. I'm facing a strange issue here. I'm building a simple scheduler like application in Django, where function names (to be executed periodically) will be stored in Django Model along with their next execution time. A management command is executed to start a thread which runs continuously to check if execution of any function is due, if yes, a new thread is started for executing this function. This way, separate thread for each function is created (at least, that's the idea!). class Command(BaseCommand): def __init__(self): super(Command, self).__init__() self.lock = None def handle(self, *args, **kwargs): self.lock = threading.RLock() t1 = threading.Thread(target=self.cron_thread) t1.start() t1.join() def cron_thread(self): while True: # Fetch only Active records scheduled_actions = Scheduler.objects.filter(active=True) for scheduled_action in scheduled_actions: # check if execution is due if scheduled_action.next_execution_time == datetime.now(): # creating a new thread function_thread = threading.Thread(target=eval(scheduled_action.function_name), args=[self.lock]) function_thread.start() function_thread.join() scheduled_action.next_execution_time = local_timezone.localize(datetime.now() + relativedelta(minutes=scheduled_action.interval)) scheduled_action.run_now = False scheduled_action.save() def somefunction(self): self.lock.acquire() # function body self.lock.release() The command that I have created to start execution of whole program is: python3 manage.py runcrons-debit As soon as I execute this command, I can see in the htop results that two process are running and consuming almost 80% of … -
Django forms, many to many relations and array field results with resulting square braces
I have this model containing a M2M relationship: class Plane(models.Model): ... start_types = models.ManyToManyField(StartType, related_name='planes') class StartType(models.Model): ... name = models.CharField(max_length=16, verbose_name=_('Name')) From this, I generate a form where the start_types field is represented by a select multiple (select2). I do this manually, not with Django forms, so I'm not sure how it's solved in Django forms, but my problem lies in Django code, so please bear with me for a moment: When this form is sent filled-out from browser back to server, I do a jQuery PUT AJAX request. jQuery, seeing that value is an array, also modifies field name in the PUT request by adding square braces after field name, like so: start_types[] I debugged the code and saw that django.utils.MultiValueDict has no knowledge of such encoding and will return an empty list for data encoded this way. So my current workaround is to simply query for start_types[] as well and only if that one doesn't return a value, I use the default functionality (without the braces). This is not the first time I ran into this issue, so at this point I thought it a good idea to ask these two questions: Is this intentionally written so … -
Django ORM: All users which have at least one group
I want to find all users which are at least in one group. I found a solution from django import setup setup() from django.contrib.auth.models import User user_without_group = User.objects.update_or_create(username='user-without-group')[0] user_without_group.groups.clear() query = User.objects.filter(groups__isnull=False).values_list('username') print (query.query) print list(query) assert user_without_group not in query ... but the solution is not nice. Is there a more obvious solution than groups__isnull=False? -
How to implement Android style permissions in a Django Application?
I have a Django applictation. This has Users, and Groups. In this application Users can be in Groups. Each of the Users has a ID, Name, Address, and Job. When a Users becomes a Member of a Group, the User has the choice of sharing his Name, Address, and Job. Depending on the User's choices will the others in that Group be able to see his Name, Address, and Job. A possible way of making this work is by making a Memberships object. Users has a ManyToMany relation to Groups through this Memberships object. This object has a list of Booleans for each field. In the __init__ of the serializer the fields that have not been shared, are dropped. Is this a sensical way of doing this? Is there a more efficient way of doing this? -
Django rest API won't filter on fields created by MariaDB view
Djago rest API is not filtering on fields that were created by MariaDB view. selected cnrbillable Works fine for native db fields as: swcustomerid swparentid When I'm filtering on selected or cnrbillable then django is ignoring my filtering request. Can django filter on fields "created" by MariaDB view? Django model: class VwMrsCustomers(models.Model): swcustomerid = models.IntegerField(db_column='SWCUSTOMERID', primary_key=True) # Field name made lowercase. swname = models.CharField(db_column='SWNAME', max_length=70, blank=True, null=True) # Field name made lowercase. swparentid = models.IntegerField(db_column='SWPARENTID', blank=True, null=True) # Field name made lowercase. selected = models.IntegerField(db_column='SELECTED', blank=True, null=True) # Field name made lowercase. cnrbillable = models.IntegerField(db_column='CNRBILLABLE', default=1) # Field name made lowercase. us = models.SmallIntegerField(db_column='US', default=0) # Field name made lowercase. class Meta: db_table = 'vw_mrs_customers' MariaDB view: CREATE DEFINER = app_mrs_reporting VIEW vw_mrs_customers AS ( SELECT mrs_customers.SWCUSTOMERID, mrs_customers.SWNAME, mrs_customers.SWPARENTID, mrs_customer_settings.US, CASE when mrs_customer_settings.SWCUSTOMERID is null then 0 else 1 end AS SELECTED, CASE when mrs_customer_settings.SWCUSTOMERID is not null then mrs_customer_settings.CNRBILLABLE else 0 end AS CNRBILLABLE FROM mrs_customers LEFT JOIN mrs_customer_settings ON (mrs_customers.SWCUSTOMERID = mrs_customer_settings.SWCUSTOMERID) ) Django view: class CustomerSettingsList(generics.ListAPIView): queryset = VwMrsCustomers.objects.all() serializer_class = CustomerSerializerSettings filter_backends = (django_filters.rest_framework.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filter_class = VwMrsCustomersFilter filter_fields = ('swcustomerid', 'swname', 'swparentid', 'cnrbillable', 'selected') search_fields = ('swcustomerid', 'swname', 'swparentid', 'cnrbillable', 'selected') ordering_fields = ('swcustomerid', … -
Django unit testing - is it possible to specify a mime-type for file upload?
I have a Django (1.11) site that allows media file uploads. I have some basic checking against mime types (eg. to just accept 'video/m4v' files). This checking works fine when I use the site on my browser (through the web UI) - running through python manage.py runserver. I'm now writing some unit tests, but am finding that whatever file type I post, it's always picked up as an application/octet-stream mime type. My unit test code is as follows: media_file = open('sample_video.m4v','rb') self.client.login(username='admin', password='password') response = self.client.post(reverse('oppia_av_upload'), {'media_file': media_file }) self.assertEqual(response.status_code, 200) In the self.client.post command, is there a way I can specify the mime type so that it's picked up correctly? For info, I'm aware that mime types can be 'fiddled' with, so it won't be a guarantee that the file is of the type it claims. Any help much appreciated. -
decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value
I had pulled the project from GitHub repo link:https://github.com/silvareal/GGS-portal I had also installed all the required packages to run the project but the project could not able to run successfully Error Stack : <br>python manage.py Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\ProgramData\Anaconda3\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\ProgramData\Anaconda3\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\ProgramData\Anaconda3\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\chandan\Documents\GGS-portal-master\school\settings.py", line 25, in <module> SECRET_KEY = config('SECRET_KEY') File "C:\ProgramData\Anaconda3\lib\site-packages\decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\decouple.py", line 85, in __call__ return self.get(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\decouple.py", line 70, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value. -
Django UnitTesting raises string indices must be integers error [on hold]
I have this post method in my view.py which works fine when testing it manually using the rest client. Here is my code: class RequestReagentStock(generics.CreateAPIView): def post(self, request, format=None): newreagents = request.data['new'] try: for item in newreagents: product_name = item['name'] amount = item['amount'] description = [] d1 = {} d1['units'] = item['units'] d2 = {} d2['form'] = item['form'] description.extend(['reagents', d1, d2]) reagent_id = None stockitem_no = item['stock_item_id'] item_order_id = item['item_order_id'] except Exception as Err: import sys import linecache exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) print("Error Found: {}, {},{}".format(Err, filename, lineno)) return Response(status=status.HTTP_400_BAD_REQUEST) Now, On Unit-Testing side i have this tests.py which tests that endpoint but results saying AddNormalValue: string indices must be integers, ...views.py,2203 F ====================================================================== FAIL: test_can_add_ReqRea (lab.tests.RequestReagentUnitTest) ---------------------------------------------------------------------- Traceback (most recent call last): File ".../tests.py", line 1050, in test_can_add_ReqRea self.assertEqual(res.status_code, 201) AssertionError: 400 != 201 This is the Unit-Testing Implementation class RequestReagentUnitTest(APITestCase): @classmethod def setUpTestData(self): return setUpGlobal(self) def test_can_add_ReqRea(self): self.client.credentials(HTTP_AUTHORIZATION=self.token) # TestVariableUnitTest.test_can_add_test_variable(self) data ={ "new": [{ "name": "Reagent Amount", "amount": 500, "units": "SSS", "form": "Form2455", "stock_item_id": 1, "item_order_id": 1 }] } url = reverse('request_reagent_stock') res = self.client.post(url, data, formats="json") self.assertEqual(res.status_code, 201) And when testing … -
Do not include object if it's not direct descendant of parent object
I want to fetch organization model from Django REST Framework API and represent its Departments nested, without single department. Suppose I have an Organization model. In it I have a Department model linked by Foreign Key. Also Department model has 2 FKs on itself say Division (main Department) and Subdivision (depends on Division). Say I have an University Organization model, in it there is a Supervisory Board department. It's main department, so it doesn't have Divisions - it IS a Division. And in it I have an Administration Subdivision Department, going deeper: there is a Military Department. Administration is a child of Supervisory Board, Military Department is a child of Administration. I reckon that the trouble is in ViewSets. Maybe in Serializers too. # viewsets.py class DepartmentViewSet(ModelViewSet): queryset = models.Department.objects.all() serializer_class = serializers.DepartmentSerializer # serializers.py class SubdivisionSerializer(serializers.ModelSerializer): class Meta: model = models.Department fields = '__all__' class DivisionsSerializer(serializers.ModelSerializer): subs = SubdivisionSerializer(many=True, source='subdivisions') class Meta: model = models.Department fields = ['id', 'name', 'organization', 'chief', 'subs'] class DepartmentSerializer(serializers.ModelSerializer): divs = DivisionsSerializer(many=True, source='divisions') class Meta: model = models.Department fields = ['id', 'name', 'organization', 'chief', 'divs'] I have now: University Supervisory Board Administration Administration Military Department Military Department And what want: University Supervisory Board Administration … -
Windows authentication with Django and Angular?
I am trying to implement the single sign-on using Angular, Django, IIS server. In IIS windows authentication is enabled. Angular intercepter code : intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> { console.log("in intercept") req = req.clone({ withCredentials: true }); return next.handle(req); } Django settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend',) CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ["*"] Getting error: (IP-address) has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
Replace external library functions globally from Django Middleware
I want to replace a function from an external library in a custom Django middleware such that whenever it is imported in any file, it imports the replaced function instead of the original external function. This middleware does not run everytime and just when during the testing process. So, I cannot replace the original external function entirely. I am using Django version 2.1 -
How can i add a red asterisk (*) in my login?
I allready put the red asterisk (*) in my registration form. (Like xyres told me [a link] Display a red asterisk (*) in Django forms). Now i want to do the same in my login form. But i only use the standard Django-Login. My settings.py contains Do i have to change the default-files in django.contrib.auth? INSTALLED_APPS = [ # Django apps 'django.contrib.auth', ...] -
Django dropdown dependency on admin
i am only using the admin-interface of django , and i have a problem that , when someone select for exemple " country " i want to show on the second select the "city's " of that country.I have already done , my json file on my view and i want to get my json file and show it in javascript, and i dont know how to do it. MY APLICATION: myproject/ |-- myproject |-- daa/ |-- avarias/ |-- models.py |-- mapeamento/ |-- models.py |-- views.py |-- static/ |-- daa/ |-- avarias/ |-- admin/ |-- js/ |-- example.js |-- templates/ |-- admin/ |-- daa/ |-- change_form.html MY URLS urlpatterns = [ path('', admin.site.urls, name ='home'), path('rua/list/', get_ruas, name='get_ruas'), ] MY MODELS: #Mapeamento Model class Freguesia(models.Model): id = models.IntegerField("Freguesia ID", primary_key=True) nome = models.CharField("Freguesia",max_length=200) def __str__(self): return self.nome class Rua(models.Model): id = models.IntegerField("Rua id", primary_key=True) freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE) nome = models.CharField("Rua",max_length=200) def __str__(self): return self.nome #daa/avarias Model from mapeamento.models import freguesia from mapeamento.models import rua class Avaria(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua") def __str__(self,): return str(self.id) MY MAPEAMENTO.VIEW import json from django.http import HttpResponse from django.shortcuts import get_object_or_404 from .models import Freguesia, Rua def get_ruas(request): freguesia_id = … -
Display values from related model in the django tables 2
I am struggling with a django application where i have to display values from a model linked to another model. I have a studentProfile model that inherited from User, in my studentProfile, i have semester and department foreign keys as well as avatar, I have used StudentProfile as my model to get the values but it is showing "-" for all fields in that model. And at the same time, i was able to get values from user model. Anyone could help with what i am doing wrong or what i needed to do? here is my table.py class StudentTable(tables.Table): user_id = tables.Column(attrs = {'th': {'class': 'danger'}}) first_name = tables.Column(attrs = {'th': {'class': 'danger'}}) last_name = tables.Column(attrs = {'th': {'class': 'danger'}}) avatar = tables.Column(accessor ="user", verbose_name = "ass" ) active = tables.Column(attrs = {'th': {'class': 'danger'}}) last_login = tables.Column(attrs = {'th': {'class': 'danger'}}) edit_Action = tables.LinkColumn('system:semester_edit', text='Edit', args=[A('pk')],attrs={'a':{'class':'btn btn-info btn-sm'}, 'td':{'align': 'center'}, 'th': {'class': 'danger'}}, orderable=False) class Meta: model = StudentProfile attrs = {'class':'table table-hover table-bordered table-responsive'} sequence = ('user_id', 'first_name', 'last_name', 'avatar') exclude = {'id', 'user', 'password', 'staff', 'admin'} empty_text = _("There are no students yet") template_name = 'django_tables2/bootstrap4.html' I would love to get the department_name, semester_name as well … -
i want to add my custom middellware to verify the jwt token in django but i when i run the server it gives me the error
Unhandled exception in thread started by .wrapper at 0x03D26780> Traceback (most recent call last): File "E:\virualevn\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "E:\virualevn\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "E:\virualevn\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "E:\virualevn\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "E:\virualevn\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "E:\virualevn\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\hp\AppData\Local\Programs\Python\Python35-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 662, in exec_module File "", line 222, in _call_with_frames_removed File "E:\registration_jwttoken\registration_jwttoken\wsgi.py", line 16, in application = get_wsgi_application() File "E:\virualevn\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "E:\virualevn\lib\site-packages\django\core\handlers\wsgi.py", line 136, in init self.load_middleware() File "E:\virualevn\lib\site-packages\django\core\handlers\base.py", line 36, in load_middleware mw_instance = middleware(handler) TypeError: object() takes no parametersenter code here -
How many bytes will Django/postgress use for a decimalfield?
I would like to like to store a percentage with two decimal places (0 to 100). Thus a decimalfield (5 digits total) seems like a good choice but smallint would also get the job done with only two bytes. How many bytes would be utilized in the database for this configuration of decimalfield? And as a follow-up question how would I query postgress to investigate the details of the data structure behind used. Thanks -
Update data to serializer when creating object with django rest framework
My models.py look like this: class Activity(models.Model): name = models.CharField(max_length=50, unique=True) description = model.TextField(max_length=500) class Jira(models.Model): jira_id = models.CharField(max_length=50, unique=True) activity = model.ForeignKey(Activity, null=True on_delete=models.SET_NULL) One activity can have multiple Jira tickets associated with it.Hence I am using a foreign key to denote one to many relationship. My serializer to create a new activity is as follows: class ActivityCreateSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=50) description = serializers.CharField(max_length=50) jira_ticket = serializers.ReadOnlyField() My view is as follows: class ActivtyViewSet(viewsets.ViewSet): def create(self, request): serializer = ActiityCreateSerializer(data=request.data) if serializer.is_valid(): #jira_ticket = make call to jira and get a valid ticket number serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) As is evident, while a new Activity is created, an external API call needs to go out to the Jira ticketing system to create a new jira_ticket. This is happening successfully and I am getting back a jira_ticket number. My question is two fold: How do i save the Jira ticket in the DB since it is not part of the serializer and is obtained only once the request is made from an external API call ? How do i add the jira ticket number to the serializer output since serializer.data is immutable and i am not able to append the … -
Django display two diffrent model objects on the same page
i want to list my posts from two diffrent models "Post" and "Superpost" but how to i access it at that point? def post_list(request): list_posts = Post.objects.get_queryset().order_by('-pk') paginator = Paginator(list_posts, 10) # Show 10 Posts per page page = request.GET.get('postpage') posts = paginator.get_page(page) categories = Category.objects.all() return render(request, 'MyProject/post_list.html', {'posts': posts, 'categories':categories}) -
Return a list from asyncio function
I have the following code from below. I know that probably is wrong somewhere, but how it must be to can return the list telegramlist after it is run ? Just want to can acces list items globally ? telegramlist = [] telegramchannellist = ['TelethonChat-anti-kyle'] async def telegram_method(): api_id = * api_hash = '*' client = TelegramClient('trendingsesion', api_id, api_hash) client.start() telegramdict = {} for ch in telegramchannellist: channel_username = ch channel_entity = client.get_entity(channel_username) posts = client(GetHistoryRequest( peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) telegramdict[ch] = posts.messages # here if i write .messages shows a weird error, he want to be only posts telegramlist = list(telegramdict.values()) return telegramlist shuffle(telegramchannellist) async def main(): telegramlist = telegram_method() return telegramlist if __name__ == '__main__': loop = asyncio.get_event_loop() telegramlistt = loop.run_until_complete(asyncio.gather(telegram_method())) loop.close() -
How to create hierarchical urls within django app?
I have multiple app based django project and within some apps url scheme getting complicated due to number of models. Hence I'm looking a way to make a hierarchical url structure within the app. In my project's urls file I do the following. from order import urls as order_urls In the order app I have urls.py and urls directory which contains separate url patterns for each model as follows. In the app's urls.py file I import the model's urls as follows. from urls import rental as rental_urls urlpatterns = [ url(r'^rental-request/', include(rental_urls)), ] This gives me the error: ModuleNotFoundError: No module named 'urls' If I put __init__.py it gives me circular import error. I'm not sure this is the correct way/possible for my requirement. Anyone could explain the correct way to achieve it? -
Error when testing the view with a file upload
I would like to test a file upload from my view with the following function: def test_post(self): with open("path/to/myfile/test_file.txt") as file: post_data = { 'description': "Some important file", 'file': file, } response = self.client.post(self.test_url, post_data) self.assertEqual(response.status_code, 302) document = Document.objects.first() self.assertEqual(document.description, "My File") self.assertEqual(document.filename, 'test_file.txt') When I test the file upload on the actual website, it works. But when I run this test, I get the following error: django.core.exceptions.SuspiciousFileOperation: Storage can not find an available filename for "WHJpMYuGGCMdSKFruieo/Documents/eWEjGvEojETTghSVCijsaCINZVxTvzpXNRBvmpjOrYvKAKCjYu/test_file_KTEMuQa.txt". Please make sure that the corresponding file field allows sufficient "max_length". Here is my form save method: def save(self, commit=True): instance = super(GrantDocumentForm, self).save(commit=False) instance.filename = self.cleaned_data['file'].name if commit: instance.save() return instance Seeing as it works on the actual website, I suspect it has something to do with the way I setup the file in the test; probably something small. -
Get Foreign Key Model's name in DRF serializer
I have 2 models - QuestionSession and Project. Project just stores these sessions, so my models as simple as: class Project(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class QuestionSession(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='sessions', blank=True, null=True, default=None ) And my serializers: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = [ 'id', 'name', 'sessions' ] class QuestionSessionSerializer(serializers.ModelSerializer): class Meta: model = QuestionSession fields = [ 'id', 'questions', 'project' ] The result I am trying to achieve is to retrieve Session with its project's name. But the project field in QuestionSession serializer only returns project's id. Looks like this: {"sessions":[{"id":4,"questions":[12,13],"project":3}]} How can I get project's name with these serializers? -
Django Error 400 with variable in urlopen
I have 500 error in my Django app, and a 400 error code when I turned on the debug mode. I use Python 3.5 This is about this : url = "https://graph.facebook.com/v3.2/lamontagnesolitaire?access_token="+str(token)+"&fields=posts{id}" fb_query = urlopen(url).read().decode('utf-8') The query is working fine, because when I put my 'token' as a plain string, I don't have any error and I can properly read the URL. I already tried this methode, or some variantes : url = "https://graph.facebook.com/v3.2/lamontagnesolitaire?access_token=%s&fields=posts{id}" %token fb_query = urlopen(url).read().decode('utf-8') I still get a 400 error message : Django Traceback : Environment: Request Method: POST Request URL: http://localhost:9000/api/likes Django Version: 1.11.4 Python Version: 3.5.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'start', 'myaccount', 'wall', 'api', 'gunicorn', 'django.contrib.sites', 'django.contrib.sitemaps', 'compressor'] 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/django-project/seigneurdesanneaux/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/django-project/seigneurdesanneaux/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/django-project/seigneurdesanneaux/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django-project/seigneurdesanneaux/api/views.py" in view_likes_synchronization 48. fb_query = urlopen(url) File "/usr/lib/python3.5/urllib/request.py" in urlopen 163. return opener.open(url, data, timeout) File "/usr/lib/python3.5/urllib/request.py" in open 472. response = meth(req, response) File "/usr/lib/python3.5/urllib/request.py" in http_response 582. 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.5/urllib/request.py" in error 510. …