Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django groups and special permissions
Can any one guide me in this is there any way to create django groups where there should be a group admin who can control the activity of the group and cand add members and themembers can share any kind of photos within the group and the other members outside the group cant view/access the photos/media Thanks in advance -
Convert uploaded file with Wand to PDF and save to model
Here is my code: class ToPng(APIView): def post(self, request, *args, **kwargs): revision = request.data.get('revision', None) file = request.data.get('file', None) with tempfile.TemporaryFile() as tmp: tmp.write(file.read()) all_pages = Image(blob=file.read()) single_image = all_pages.sequence[0] with Image(single_image) as img: img.format = 'png' img.background_color = Color('white') img.alpha_channel = 'remove' MyModel.objects.create(revision=revision, file=img) return Response(HTTP_200_OK) I get the error: "no decode delegate for this image format `' @ error/blob.c/BlobToImage/353" Obviously I am making a grave mistake since wand with imagemagick can convert Pdf to Png right away. I am probably reading the wrong thing but I don't know what else to do. -
How to get most recent list elements in Django template?
I want to get most 4 recent elements from a list ? I can get elements in increasing order but no idea about getting recent elements. for example: news_list[n], news_list[n-1] .... Template Code: {% for obj in news_list|slice:"last:" %} <div class="sub_highlights"> <a href="/news#{{obj.title}}"> <img src="/static/images/{{obj.imgs}}" alt="Thumbnail"> <label>{{obj.info}}</label> </a> </div> {% endfor %} views.py class NewsTemplateView(TemplateView): template_name = 'index.html' def get_context_data(self,*args, **kwargs): qs = News.objects.all() q = Reviews.objects.all() context = { "news_list" : qs, "review_list" : q } return context -
Support write operation for two-deep reverse relation serializer in Django Rest
Hi I need an API to write/post two-deep reverse relation in django rest. Here is my models.py: class Projects(TimeStampModel): project_name = models.CharField(max_length=30) project_dsn = models.CharField(max_length=30) class Objects(TimeStampModel): projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE) object_name = models.CharField(max_length=50) object_description = models.TextField() object_main_table = models.CharField(max_length=50) class Rule(TimeStampModel): obj = models.ForeignKey(Objects,related_name='obj_rule',on_delete=models.CASCADE) rule_description = models.TextField() legal_hold = models.BooleanField(default=False) My serializers.py: class RuleSerializer(serializers.ModelSerializer): proj = serializers.RelatedField(source='obj.projects', queryset=Objects.objects.all()) class Meta: model = Rule fields = ('obj','rule_description','legal_hold','proj',) I need to create a Rule object. My Django rest API properly shows a dropdown for Objects model (one-deep relation) but how do I make it show a dropdown for Project model (two-deep relation) as well? The above implementation gives me this error: Exception Type: NotImplementedError Exception Value: RelatedField.to_representation() must be implemented for field proj. If you do not need to support write operations you probably want to subclass `ReadOnlyField` instead. I don't want to put read_only=True since I want a write operation. Please suggest how to accomplish this. -
Can't test successfully for view that puts form data in session
I'm trying to test a view that stores validated form data in the session. However when I try to test this I get back None for the session value and the error: AssertionError: 'example_postcode' != None The test is: class TestSignup(TestCase): def test_postcode(self): postcode = 'example_postcode' self.client.post('/users/postcode', {'postcode': postcode}) self.assertEqual(postcode, self.client.session.get('postcode')) the view is: @require_http_methods(['GET', 'HEAD', 'POST']) def postcode_view(request,): if request.method == 'POST': form = PostcodeForm(request.POST) if form.is_valid(): request.session.update(form.cleaned_data) return redirect('users:signup_2') else: form = form_class() context.update({'form': form}) return render(request, 'pages/signup_postcode.html', context) form class PostcodeForm(forms.Form): postcode = GBPostcodeField(label='Please enter your postcode', error_messages={'invalid': 'Please enter a valid postcode'}) -
How to add pagination for custom Apiview result data in DRF
I have create an api Listview in DRF 3. As database structure is complex I have written a custom query ie raw query to fetch the data. But as the data size is huge it takes a lot of time to load the data. So I need to implement the pagination. Below is the code. class SubnetList(APIView): def get(self, request, format=None): subnet_list = get_subnet_details(None) return Response(subnet_list, status=status.HTTP_200_OK) def get_subnet_details(subnet_id=None): if subnet_id: subnets = Subnet.objects.filter(id=subnet_id).values() if not subnets: raise Http404 else: subnets = Subnet.objects.values() subnet_list = [] subnet_option_query = ' SELECT ' \ ' options_value.id as value_id,' \ ' options_value.content,' \ ' options_option.id,' \ ' options_option.name' \ ' FROM subnets_subnetoption' \ ' INNER JOIN subnets_subnet ON (subnets_subnetoption.subnet_id = subnets_subnet.id)' \ ' INNER JOIN options_value ON (subnets_subnetoption.value_id = options_value.id)' \ ' INNER JOIN options_option ON (options_value.option_id = options_option.id)' \ ' INNER JOIN options_scope ON (options_option.scope_id = options_scope.id)' \ ' WHERE subnets_subnetoption.subnet_id = %s ' try: for subnet in subnets: subnet_dictionary = collections.OrderedDict() subnet_dictionary['subnet_id'] = str(subnet['id']) subnet_dictionary['name'] = str(subnet['name']) subnet_dictionary['base_address'] = str(subnet['base_address']) subnet_dictionary['bcast_address'] = str(subnet['bcast_address']) subnet_dictionary['bits'] = str(subnet['bits']) subnet_dictionary['begin'] = str(subnet['base_address']) subnet_dictionary['end'] = str(subnet['bcast_address']) subnet_dictionary['parent_id'] = str(subnet['parent_id']) subnet_dictionary['vlan_common_name'] = str(subnet['vlan_common_name']) subnet_dictionary['admin'] = str(subnet['admin']) subnet_dictionary['responsible'] = str(subnet['responsible']) subnet_dictionary['comments'] = str(subnet['comments']) super_subnet = 'True' if … -
New Urls patterns and multiple variables with the same name
I'm using Django 2.0 type of urls, and I have urls with multiple variables in them, with the same name. I'm using also ClassBasedView path('/companies/<int:pk>/products/<int:pk>/', AccountCompanyProductDetailView.as_view() In a CBV how can I get the parameters and know which is which. ? How Django knows pk from which Model I need in each position ? -
Django url.py regex not working
I am trying to catch all URLs from the safer app and send them to a catch all view; for example: http://127.0.0.1:8000/saferdb/123 http://127.0.0.1:8000/saferdb/12 I think I have an issue with my reg ex in url.py: from django.conf.urls import url from . import views app_name = 'saferdb' urlpatterns = [ url(r'^/$', views.index, name='index'), url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'), ] Views.py is the sample code from the django tutorial: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.all()[:5] output = ', '.join([q.DOT_Number for q in latest_question_list]) return HttpResponse(output) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) I noticed that /saferdb/ will not work unless the reg ex contains a slash: r'^/$' instead of r'^$' as shown in the django tutorial. -
ERROR: Form object has no attribute 'save_m2m'
i am working on a django project. I have created a custom user model which is called Employee and extends AbstractUser model like this : models.py from django.db import models from django.contrib.auth.models import AbstractUser from .model_manager import EmployeeManager class Employee(AbstractUser): department = models.OneToOneField(Department, on_delete=models.SET_NULL, null=True) position = models.OneToOneField(Designation, on_delete=models.SET_NULL, null=True) dob = models.DateField(verbose_name="Date of Birth", null=True) manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='manger', null=True) REQUIRED_FIELDS = [] objects = EmployeeManager() model_manager.py from django.contrib.auth.models import BaseUserManager from config.settings import COMPANY_EMAIL_DOMAIN class EmployeeManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): if not email: email = username + '@' + COMPANY_EMAIL_DOMAIN extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, password, email=None, **extra_fields): if not email: email = username + '@' + COMPANY_EMAIL_DOMAIN extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fields) I wanted to … -
Django Test client.get() returns 302 code instead of 200
Running a test on a url returns 302 instead of 200. Yet testing the same urls in production with a redirect tester returns 200. Not really sure what's going on. tests.py def test_detail(self): response = self.client.get('/p/myproduct-detail.html') self.assertEqual(response.status_code, 200) urls.py url(r'^p/(?P<slug>[-\w\d]+).html$', main.views.product_detail, name='product-detail'), views.py def product_detail(request, slug): stuff... return render(request, 'product-detail.html', {}) If I add follow=True to client.get() I receive 200 code as expected. -
Django rest framework Anonymous user is always Authenticated
I'm trying to authenticate my web API method using django rest framework isauthenticated permission and TokenAuthentication The API method: @api_view(['Post']) @permission_classes((IsAuthenticated,)) def listofgroups(request): try: logout(request) data = request.data page_size = data.get('pagesize') page_number = data.get('pagenumber') group_qs = Group.objects.all() paginator = Paginator(group_qs, int(page_size)) group_list = paginator.page(int(page_number)) #group_list = tools.paginate_query_set(group_qs, 1, 3) #list = group_list[0]['model'] groups = [get_group_dto(g) for g in group_list] sorted_groups = sorted(groups, key=lambda k: k['user_count'], reverse = True) group_list_dto = { "grps": sorted_groups, "success":1, "fail":0 } return Response(group_list_dto) except Exception as e: #.error("Error %s"(e), exc_info = 1) return Response({"success" : 0, "error": str(e)}) Basically i should always set Authorization in the header like : "Authorization":"Token a26171d30745cc94bcd6ac42d9bc94e1d3992948" this token is based on rest_framework.authtoken The Error is that I can get the data with response 200 without even setting the Token in the header because its returning anonymous user which is authenticated from the back end in django. How can I prevent anonymous users from being authenticated and return 403 response error for them using django rest framework I appreciate any help -
Django user account creation confirmation email
I have a django project where I want to create users, and some time later be able to send a welcome email with a link inviting them to log in and set a password. I'm using django-allauth. I found this SO question which shows how to call allauth's password reset form, which is close to what I need, except that: I want to send a "welcome" email, which would be worded differently. I want it to send them to a "welcome" page, which would be different to a password reset (although perhaps operate the same way in that it use a token etc...) I'm thinking I could somehow hijack that, but am not sure how or where that email gets sent. django-allauth docs mention the routes /accounts/password/set/ and /accounts/password/set/ but I can't access either without logging in first. This is an existing project I inherited, and I do have a template for "/account/password_reset_from_key.html". Just not sure how it all gets wired together. Has anyone done anything similar? -
Convert PDF to Image and save to model
Pardon my ignorance if the question is in fact nonsensical. I have an ImageField in a model, field itself is stored in S3 Bucket. Model serializer gets the data sent from front and saves it. Now if the file is pdf, I have to convert it and save it. I try to write an APIView for it. Something like: class ToPng(APIView): def post(self, request, *args, **kwargs): revision = request.data.get('revision', None) file= request.data.get('file', None) import tempfile with tempfile.TemporaryFile() as tmp: tmp.write(file.read()) # write the subprocess here. # linux command: pdftoppm input.pdf outputname -png -f 1 -singlefile So am I in the right direction? How can I get the input.pdf? How can I save output.png to the model? And how can I write the subprocess? -
Retrieving related polymorphic set with django-polymorphic
I have three simple models: class Employee(models.Model): [...] class AttendanceLog(models.Model): employee = models.ForeignKey(Employee, [...]) from_datetime = models.DateTime([...]) to_datetime = models.DateTime([...]) class Salary(models.Model): employee = models.ForeignKey(Employee, [...]) [...] What I need is to make a query that will return the total (SUM) amount of time an employee was in work (attendance). What I have right now: # method in Salary def get_attended_hours(self): qs = AttendanceLog.objects.employee(self.employee).filter(to_datetime__year=self.year, to_datetime__month=self.month) qs = qs.values('employee') # group by employee (should not be needed) duration = ExpressionWrapper(F('to_datetime') - F('from_datetime'), output_field=fields.DurationField()) qs = qs.annotate(duration=Sum(duration)).values_list('duration', flat=True) # expected output: {'duration': datetime.timedelta(0, x)} # actual output: <AttendanceLogQuerySet [datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 3600), datetime.timedelta(0, 14400), datetime.timedelta(0, 10800), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), datetime.timedelta(0, 14400), '...(remaining elements truncated)...']> # qs.query: SELECT SUM(django_timestamp_diff("human_resources_attendancelog"."to_datetime", "human_resources_attendancelog"."from_datetime")) AS "duration" FROM "human_resources_attendancelog" WHERE ("human_resources_attendancelog"."employee_id" = 22 AND "human_resources_attendancelog"."to_datetime" BETWEEN 2017-01-01 00:00:00 AND 2017-12-31 23:59:59.999999 AND django_datetime_extract('month', "human_resources_attendancelog"."to_datetime", None) = 11 AND "human_resources_attendancelog"."attendance_type" = RE) GROUP BY "human_resources_attendancelog"."employee_id", "human_resources_attendancelog"."to_datetime" ORDER BY "human_resources_attendancelog"."to_datetime" ASC # problematic part: GROUP BY "human_resources_attendancelog"."employee_id", "human_resources_attendancelog"."to_datetime" Basically, why is it also using GROUP BY on to_datetime? I tried to force the … -
Cross Table Left Join, Django ORM
I have the following models: class TradeDetails(models.Model): created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP', primary_key=True) trade_name = models.CharField(db_column='TRADE_NAME', max_length=45) trade_image = models.CharField(db_column='TRADE_IMAGE', max_length=500, blank=True, null=True) class Meta: managed = False db_table = 'TRADE_DETAILS' class TradeNotifications(models.Model): client_id = models.CharField(db_column='CLIENT_ID', primary_key=True, max_length=15) created_timestamp = models.DateTimeField(db_column='CREATED_TIMESTAMP') updated_timestamp = models.DateTimeField(db_column='UPDATED_TIMESTAMP', blank=True, null=True) platform_notification = models.IntegerField(db_column='PLATFORM_NOTIFICATION', blank=True, null=True) sms_notification = models.IntegerField(db_column='SMS_NOTIFICATION', blank=True, null=True) email_notification = models.IntegerField(db_column='EMAIL_NOTIFICATION', blank=True, null=True) caller_notification = models.IntegerField(db_column='CALLER_NOTIFICATION', blank=True, null=True) caller_id = models.IntegerField(db_column='CALLER_ID', blank=True, null=True) client_confirmation = models.IntegerField(db_column='CLIENT_CONFIRMATION', blank=True, null=True) device_id = models.CharField(db_column='DEVICE_ID', max_length=256, blank=True, null=True) platform = models.CharField(db_column='PLATFORM', max_length=15, blank=True, null=True) ip_address = models.CharField(db_column='IP_ADDRESS', max_length=50, blank=True, null=True) expired = models.IntegerField(db_column='EXPIRED', blank=True, null=True) trade_sent = models.IntegerField(db_column='TRADE_SENT', blank=True, null=True) class Meta: managed = False db_table = 'TRADE_NOTIFICATIONS' unique_together = (('client_id', 'created_timestamp'),) I want to perform a left join on another table on the same db using the following sql query: SELECT TRADE_DETAILS.TRADE_NAME FROM TRADE_NOTIFICATIONS LEFT JOIN TRADE_DETAILS ON TRADE_NOTIFICATIONS.CREATED_TIMESTAMP = TRADE_DETAILS.CREATED_TIMESTAMP Is there a more Django-Like way of doing this or should I just go with raw sql? -
django 1.5 python set X-Content-Type-Options nosniff
We would like to add X-Content-Type-Options nosniff . We can't upgrade to newer django version (1.5), so we can't use the SECURE_CONTENT_TYPE_NOSNIFF because we don't have SecurityMiddleware. Any help is appriciated. -
NoReverseMatch at /sitemap.xml when generating sitemap.xml django website
Apologies for the long post.I am trying to generate sitemap.xml for a basic django blog application with a few static pages. I am not sure why the error occurs. Note: I have already created a dummy blog post and it exists when I get the error. I tried to look at the django documentation but found it too confusing. The tutorials online weren't much helpful either. **Error:** NoReverseMatch at /sitemap.xml Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)$'] **sitemap.py** from django.contrib.sitemaps import Sitemap from blog.models import Post from blog.urls import urlpatterns as homeUrls from django.core.urlresolvers import reverse class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.5 def items(self): return Post.objects.all() class StaticSitemap(Sitemap): priority = 0.8 changefreq = 'weekly' # The below method returns all urls defined in urls.py file def items(self): mylist = [ ] for url in homeUrls: if url.name is None: pass; else: mylist.append(''+str(url.name)) return mylist def location(self, item): return reverse(item) **models.py** class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) **urls.py** ... from django.contrib.sitemaps.views import sitemap from .sitemaps import * sitemaps = { 'posts': PostSitemap(), 'static': StaticSitemap(), } urlpatterns = [ … -
What would be the robust design pattern for multiple class forms render/process (create, update) on single page in django
I am working on a django project in which I have to design a sales order page for order processing,now as per requirement I have to create multiple information forms on single page with different fields (formset does not helpful in this case) which I achieved by creating specific form class and then render them in template through class view function def get_context_data(self, **kwargs): context = super(CreateOrderView, self).get_context_data(**kwargs) context['ord_info_form'] = OrderInformationForm() context['billing_form'] = BillingInformationForm(prefix='billing') context['shipping_form'] = ShipingInformationForm(prefix='shipping') context['payment_form'] = PaymentInfoForm() context['summary_form'] = OrderProductsForm() return context Now, I have to save data for all forms which belongs to multiple models like billing, contact and shipping information. So for save information I created another form class for create order and set it in form_class variable in Createview class, and I override the save function in form class in which I manipulate the data for all model forms. For update order (put operation) I did the same I create another form class for update like create one in form class. As per my understanding I implement this strategy, but this seems to me repetitive design. How can I design it better for multiple forms with different fields. Please let me know what kind … -
django form without id=id_fieldname
I have the following form in django: class Person(forms.Form): first_name = forms.CharField() last_name = forms.CharField() age = forms.IntegerField() When I render the form, the html output is the following: <input id="id_age" name="age" type="number"> Is it possible to NOT include the input id? My desired output would be: <input name="age" type="number"> -
Integrate Django app as Page in Mezzanine Admin interface
I have existing apps in Django. I want to integrate them with mezzanine project in a way that the apps are available in form of pages. I followed this method. The steps I followed- I created a fresh vanilla mezzanine project- it works! Then I created theme for website- it works! From admin interface if i add a page, the page renders along with website theme. Copy pasted the Django apps in mezzanine project. Added the app names in mezzanine project's settings.py file at the beginning of INSTALLED_APPS. Added corresponding URL patterns in mezzanine project's urls.py file The related code snippets (example app, About Us)- testproject/aboutus/views.py from django.shortcuts import render def aboutus(request): context=locals() #context=page(about) template = 'aboutus/aboutus.html' return render(request,template,context) testproject/aboutus/urls.py import mezzanine from django.conf.urls import url from aboutus import views from mezzanine.conf import settings urlpatterns = [ url(r'^aboutus.html',views.aboutus,name='aboutus'), ] testproject/urls.py from __future__ import unicode_literals import mezzanine from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.views.i18n import set_language from mezzanine.core.views import direct_to_template from mezzanine.conf import settings from aboutus import views urlpatterns += [ url("^$", direct_to_template, {"template": "index.html"}, name="home"), url(r'^',include('aboutus.urls')), url("^", include("mezzanine.urls")), ] I'm missing out on something minute but very important. We want the existing … -
MultiDict Error Django
Im using Django and trying to get a response by using AJAX. I have two forms, the first one works just fine. Though I use the same logic in my second form handling it does not work well. models.py class AskMe(models.Model): name = models.CharField(max_length=1000) views.py def AskMeQ(request): if request.method == POST: name = request.POST['name'] AskMe.objects.create(name=name) urls.py url('r^askmeQ/$', views.AskMeQ) ERROR Traceback: File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__ 77. list_ = super().__getitem__(key) During handling of the above exception ('name'), another exception occurred: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ 40. name = request.POST['name'] File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__ 79. raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /askmeQ/ Exception Value: 'name' The logic I use above used to work in all the previous forms, but here it throws me an error. The SQLite3 table has been created as projectname_model.name. How can I correct this? -
python social_auth facebook can't get extra scopes
I'm using social_auth in my django project in order to provide facebook login. I'm trying to get the user email. Note that i'm testing it locally. I can see the email being supplied from facebook in the popup but it appears to be empty in my custom pipeline. in kwargs: { [some stuff], 'username': 'xxx','email': '', 'last_name': 'xxx'}) Here is my configuration in settings.py (I tried everything) : SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', ] SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email',] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {'fields': 'id,name,email,first_name,last_name'} -
AttributeError with Django Rest nested serializer
I'm following the Django Rest documentation for writing nested serializer but it is giving me attribute error. Here are my models: class Objects(TimeStampModel): projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE) object_name = models.CharField(max_length=50) object_description = models.TextField() object_main_table = models.CharField(max_length=50) object_primary_key = models.CharField(max_length=50) object_age_field = models.CharField(max_length=50) date_format = models.CharField(max_length=50) def __str__(self): return self.object_name class ObjectDefinition(TimeStampModel): ATTRIBUTE = 'Attribute' RELATION = 'Relation' TYPE_CHOICES = ( (ATTRIBUTE, 'Attribute'), (RELATION, 'Relation'), ) obj = models.ForeignKey(Objects,related_name='obj_def',on_delete=models.CASCADE) from_table = models.CharField(max_length=50) from_table_field = models.CharField(max_length=50) to_table = models.CharField(max_length=50) to_table_field = models.CharField(max_length=50) relation_type = models.CharField(max_length=50,choices=TYPE_CHOICES) relation_sequence = models.CharField(max_length=50) value_field = models.CharField(max_length=50, blank=True, null=True) Here is my serializers.py snippet: class ObjectDefinitionSerializer(serializers.ModelSerializer): class Meta: model = ObjectDefinition fields = ('from_table','from_table_field','to_table','to_table_field','relation_type','value_field') class ObjectSerializer(serializers.ModelSerializer): definition = ObjectDefinitionSerializer(many=True) object_description = serializers.CharField(required=False, allow_null=True, allow_blank=True ) class Meta: model = Objects fields = ('projects','object_name','object_description','object_main_table','object_primary_key','object_age_field','date_format','definition') def validate(self, data, *args, **kwargs): date_format = data.get('date_format') if date_format not in ['YYYYMMDD', 'DDMMYYYY']: msg = ('Date format is incorrect') raise serializers.ValidationError({'error_msg': msg}) return super(ObjectSerializer, self).validate(data, *args, **kwargs) def create(self, validated_data): definition_data = validated_data.pop('definition') obj = Objects.objects.create(**validated_data) for data in definition_data: ObjectDefinition.objects.create(obj=obj, **data) return obj My views.py: class CreateObject(CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = ObjectSerializer After hitting POST, objects.create works fine for both the models but at return obj, it throws me this error: Exception Value: … -
Django Form save - circular dependency
I have 2 models Account and User. An Account can have multiple users. When the first User(Owner) is created at the same time the Account will be created. Because User have a ForeignKey to Account, I need first to create the Account, and after the User. But Account had a field created_by which is request.user. So is a circular problem. I think I need to create first the Account and created_by to be a superuser(first) and than create the User, and update the Account with the new user. class Account(MetaData): name = models.CharField(max_length=255) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) class User(AbstractBaseUser): account = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='owner') How can I do that ? I need this only first time, for the first user, because after that for the other users the Account will exist. -
Python dict, extracting values
I am having trouble to query my database maybe someone could give me a hand. I am using a django application so I guess Sqlite3 >> and the output I would like to get is the score value b = Answer.objects.get(id = 23) which give me an output of : <Answer: Answer to questionID '4' : AnswerID '23'> when I do : b.values I get a dict in the form : ['{ "1)Long descriptive text":Score, "2)Long descriptive text":Score, "3)Long descriptive text":Score, "4)Long descriptive text":Score }'] with score beeing an Integer from 0 to 100 so for example "Long descriptive text":85 I need to extract the score using a query but I can't manage to do it Normaly for a Dict[key:value] I would do a Dict[key] but here I do not know how to do it could you give me a hand Thx you very much