Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect in django does work in POST method
i have views in django that is called by $.post() method of jquery that is working fine. But when i redirect inside that post it's not redirecting me but outside its redirecting me. here is view called by jquery $.post() @csrf_exempt def order_detail(request): category_name = request.session.get('category_name') category = Category.objects.get(name=category_name) price = Price.objects.get(category=category) if request.session['industry_name']: industry_name = request.session.get('industry_name') industry = Industry.objects.get(name=industry_name) images = SampleImages.objects.filter(category=category, industry=industry) colors = SampleColor.objects.all() else: images = SampleImages.objects.filter(category=category) colors = SampleColor.objects.all() if request.method == 'POST': image_list = request.POST.getlist('idSelectedImages[]') color_list = request.POST.getlist('idSelectedColors[]') package_price = request.POST.get('packagePrice') package_name = request.POST.get('packageName') if image_list: for image_id in image_list: request.session['image_list']['{}'.format(image_id)] = image_id request.session.modified = True if color_list: for color_id in color_list: request.session['color_list']['{}'.format(color_id)] = color_id request.session.modified = True return redirect('order:order_brief') else: request.session['image_list'] = {} request.session.modified = True request.session['color_list'] = {} request.session.modified = True return render(request, 'order/order_detail.html', {'images': images, 'colors': colors, 'price': price}) and urls.py app_name = 'order' urlpatterns = [ path('', views.index, name='index'), path('order/detail/', views.order_detail, name='order_detail'), path('order/brief/', views.order_brief, name='order_brief'), ] -
printing db values to html django
can anyone help? I want to print some counts from the DB (total records where the complete field = true and another when it equals false. What have I done wrong in the below? Thanks VIEWS def task_count(request): completetasks = Todo.objects.filter(complete=True).count() incompletetasks = Todo.objects.filter(complete=False).count() return render(request, 'counts.html') URLS urlpatterns = [ url(r'^$', views.todo, name='index'), url(r'^create/$', views.create_task, name='create'), url(r'^counts/$', views.task_count, name='counts'), COUNTS.HTML {% extends 'base.html' %} {% block content %} <br><br><br> {% if user.is_authenticated %} <div class="container"> {% filter upper %} <h3>Notes for task</h3> {% endfilter %} </div> {{ completetasks }} {% else %} <h2><a href="/login">Login</a></h2> {% endif %} {% endblock %} -
Django-Tables2 LinkColumn link goes to wrong item
I have a Django project and I am having issues with the hyperlink (LinkColumn from Django-tables2) going to the incorrect entry and I cannot figure out why it is occurring or how to fix it. Very specifically, I can go to the admin view and create a publication. When it comes to setting the author (a.k.a. pi) or sample, there is a drop down menu for foreign key fields (sample/pi) that shows all existing entries from which I can choose one. When I choose a sample and pi then look at the table rendering, the hyperlink is there for the sample, pi, and the publication title. The publication title correctly takes me to the publication_detail page but the hyperlink for the sample will take me to a sample detail page, but it is not the same sample I selected. I have the same issue for the author; it takes me to the detail view page of AN author, just not the one I selected for the admin page. I use django-tables2 several times throughout the project and like how the tables are rendered, but cannot figure out how to address this problem. I have included some of my code (please … -
Multiple object-create with form and validation
I try to make multiple objects with one form. Without validation - all works perfectly. When I try to validate - I can't get Tram object. Model Gate has ForeignKey Tram. During creating object, user is allowed to create the same Gate for multiple Tram's. Unfortunatelly, Gate can be various type of object, and for each type of Gate, validation unique_together is various. I overwrited validate_unique in models.py. models.py class Gate(models.Model): GATE_TYPE = ( ('BJC', u'Bramka jakościowa - człon'), ('BJW', u'Bramka jakościowa - wózek'), ('IKS', u'Inspekcja końcowa - Solaris'), ('IKK', u'Inspekcja końcowa - klient') ) CAR_SYMBOLS = ( ('C1', u'C1'), ('C2', u'C2'), ('C3', u'C3'), ('C4', u'C4') ) BOGIE_TYPES = ( ('WN1', u'Wózek napędowy 1'), ('WN2', u'Wózek napędowy 2'), ('WT', u'Wózek toczny'), ('WN3', u'Wózek napędowy 3'), ('WN4', u'Wózek napędowy 4'), ) GATE_STATUSES = ( ('R', u'Realizacja'), ('O', u'Ocena DZJ'), ('P', u'Ponowna realizacja'), ('A', u'Archiwum') ) GATE_GRADES = ( ('OK', u'Zaakceptowany'), ('NOK', u'Odrzucony') ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(choices=GATE_TYPE, default='BJC', max_length=3) tram = models.ForeignKey(Tram, null=True, on_delete=models.CASCADE) bogie = models.ForeignKey(Bogie, null=True, on_delete=models.CASCADE) bogie_type = models.CharField(choices=BOGIE_TYPES, null=True, max_length=3) car = models.CharField(choices=CAR_SYMBOLS, max_length=2, null=True) area = models.ForeignKey(OperationArea, null=True, on_delete=models.CASCADE) operation_no = models.CharField(max_length=6) name = models.CharField(max_length=200) content = models.TextField() gate_status = models.CharField(choices=GATE_STATUSES, default='R', … -
Django - limit key size on unique_together columns
Using MySQL, I am trying to have a table with a composite key of multiple fields. The issue is that some of the fields are large (255 - 1024 length), if I try to run the migration, I will get: django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') Instead of increasing the DB's key length (or changing some other DB / table settings), I found out that I can just limit the value of the field used as a key in the migration file so that it remains within the max key length, like this: ALTER TABLE <table> ADD UNIQUE KEY `<table>_composite_key` (`col1`, `col2`(75), `col3`, `col4`, `col5`(150)); However, this is an issue if I were to change the db engine, as that syntax might not be compatible with other. So I'm wondering is there a way to impose limit for each field in unique_together? Thanks in advance! -
IntegrityError in TestCase runs after updating to Django 2.0
I upgraded from Django 1.11 to Django 2.0 and my tests started failing. I have 7 TestCase classes and all use the setUpTestData provided by Django. When I run them all together one of them fails to set up because of an psycopg2.IntegrityError: duplicate key value violates unique constraint "doctors_doctor_pkey". When I run one of those TestCase classes alone it works fine. It seems like they're influencing each other in some way, but it's strange that it would fail after upgrading to Django 2.0. I've also noticed it's not at the create() it's at the save(). In the setup for the dashboards app I have some creation data: cls.d1 = doctor_models.Doctor.objects.create(email="johndoe@example.com", name="John Doe", specialization=cls.s1, premium=True, premium_price=4310, consultation_price=341) ... cls.b1 = doctor_models.DoctorBooking.objects.create(clinic=cls.c1, doctor=cls.d1, status=2, premium_booking=True, patient_name="example", patient_phone_number="+9747721234", confirmed_date=datetime.strptime( "16 Jun 2017 14:22:26:000 +0300", receive_format), handled_on=datetime.strptime( "17 Jun 2017 14:22:26:000 +0300", receive_format)) The second line from above would call it's save() function that would call save() on cls.d1 def save(self, *args, **kwargs): if self.doctor.premium: self.premium_booking = True else: self.premium_booking = False super(DoctorBooking, self).save(*args, **kwargs) self.doctor.save() # <- here it raises an IntegrityError This is the simplest code I could extract, but this happens all over for different classes. To reiterate this gives … -
dj-stripe webhook product not created
I'm trying to set up dj-stripe webhooks on my development server. I'm using ngrok.io and the webhooks are coming through ok but when I create a new product or plan in the Stripe dashboard, I initially get a http 500 error aka "POST /stripe/webhook/ HTTP/1.1" 500 0 and on the first retry it goes through but the product isn't created. The traceback for the 500 error is below: Traceback (most recent call last): File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 3389, in from_request obj.process(save=False) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 3448, in process self.event = Event.process(self.json_body) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 1486, in process ret.invoke_webhook_handlers() File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 1498, in invoke_webhook_handlers webhooks.call_handlers(event=self) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/webhooks.py", line 104, in call_handlers handler_func(event=event) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/event_handlers.py", line 146, in other_object_webhook_handler _handle_crud_like_event(target_cls=target_cls, event=event) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/event_handlers.py", line 264, in _handle_crud_like_event data = target_cls(**kwargs).api_retrieve() File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 202, in api_retrieve return self.stripe_class.retrieve(id=self.stripe_id, api_key=api_key, expand=self.expand_fields) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_resources/abstract/api_resource.py", line 13, in retrieve instance.refresh() File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_resources/abstract/api_resource.py", line 17, in refresh self.refresh_from(self.request('get', self.instance_url())) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/stripe_object.py", line 207, in request response, api_key = requestor.request(method, url, params, headers) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_requestor.py", line 153, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_requestor.py", line 365, in interpret_response self.handle_error_response(rbody, rcode, resp.data, rheaders) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_requestor.py", line 178, in handle_error_response raise err stripe.error.InvalidRequestError: Request req_7pF2asxJ89UmoZ: No such product: … -
How to setup AdminLTE-2.4.5 theme + CRUD in Django App?
The issue is: I want to set up "AdminLTE-2.4.5" theme+CRUD in Django2 App at frontside, I get many answers like direct cmd through installing it and I do it but I don't know how to set up for the view Please give solution step by step or any other solution regarding how to install AdminLTE-2.4.5 theme and show in front side ? Thanks -
CORS error using localhost but not using domain
I'm developing a react web app which communicates with a DRF backend via axios. While developing locally, I handled CORS by installing django-cors-headers and adding localhost:3000 to CORS_ORIGIN_WHITELIST (3000 is the default port for react w/ create-react-app): CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) This worked fine until I deployed to a remote server, when I suddenly started seeing CORS errors again: Access to XMLHttpRequest at 'http://localhost:8000/api/path/' from origin 'http://example.com:3000' has been blocked by CORS policy... which was baffling to me, since it already worked when I was developing locally. This had me stumped for hours until sheer frustration led me to change the react request from axios.post(localhost:8000/api/path/, { key1: val1, key2: val2, ... }) .then(response => { doSomeStuff(response); }); to axios.post(example.com:8000/api/path/, { key1: val1, key2: val2, ... }) .then(response => { doSomeStuff(response); }); and the whitelist from CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) to CORS_ORIGIN_WHITELIST = ( 'example.com:3000', ) At which point the CORS errors stopped. My question is: why did this happen? My understanding was that localhost and example.com were two names for the same server, but every other combination of whitelisting localhost/example.com and requesting localhost/example.com results in an error. What is the difference from a CORS perspective? -
how to get reverse relation in django serializers SlugRelatedField
I have two models ProductTypeModel and ProductModel, product_type is the foreign key in the product. Then I wrote a ModelSerializer for a product to get all the entries of ProductModel and along with some additional info. Now I'm unable to get product_sub_type from the ProductTypeModel in ProductSerializer I have tried SlugRelatedField in serializers, tried to set slug_field=product_sub_type and slug_field=product_type__product_sub_type and slug_field=product_type.product_sub_type models.py class ProductType(models.Model): """Product type model.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) hsn = models.ForeignKey(HSN, related_name='product_types', on_delete=models.SET_NULL, null=True, blank=True) product_type = models.CharField(max_length=255, null=True, blank=True) product_sub_type = models.CharField(max_length=255, db_index=True) description = models.CharField(max_length=255, null=True, blank=True) # !TextFiled? def __str__(self): return str(self.product_type) def get_sub_type(self): return str(self.product_sub_type) class Meta: db_table = 'ProductTypes' unique_together = ('product_type', 'product_sub_type') class Product(models.Model): """Products model.""" product_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_type = models.ForeignKey( ProductType, related_name='related_products', on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=255, db_index=True) code_name = models.CharField(max_length=255, null=True, blank=True) href = models.CharField(max_length=500, blank=True, null=True) full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True) manufacturer = models.ForeignKey( Manufacturer, related_name='manufactured_products', on_delete=models.SET_NULL, null=True, blank=True) packing = models.CharField(max_length=255, null=True, blank=True) packing_detail = models.CharField(max_length=255, null=True, blank=True) mrp = models.DecimalField( max_digits=8, decimal_places=2, null=True, blank=True) created_at = models.DateTimeField('created at', db_index=True, default=timezone.now) # !auto_add_now? def __str__(self): return str(self.full_name) class Meta: db_table = 'Products' unique_together = ('code_name', 'product_type') serializers.py class ProductTypeSerializer(serializers.ModelSerializer): # Serialize/Deserialize … -
django.db.connection don't support fileno() method
I have a custom method on my model manager that allows me to listen for notifications from modifications on the DB using postgreSQL. A short version of this code looks like this: def listen_for_notify(self): import select import psycopg2 import psycopg2.extensions from django.conf import settings db_data = settings.DATABASES['default'] listened = None returned_empty = None search_timeout = 15 conn = psycopg2.connect(dbname=db_data['NAME'], user=db_data['USER'], password=db_data['PASSWORD'], host=db_data['HOST'], port=db_data['PORT']) conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) curs = conn.cursor() curs.execute("LISTEN default;") timeout = timezone.now() + timezone.timedelta(0, search_timeout) while timezone.now() < timeout: time_diff = timeout - timezone.now() if select.select([conn], [], [], float(time_diff.seconds)) == ([], [], []): listened = False timeout = timezone.now() else: conn.poll() while conn.notifies: notify = conn.notifies.pop(0) if notify.payload == "notified": listened = True returned_empty = False timeout = timezone.now() if notify.payload == 'search request returned empty': listened = True returned_empty = True timeout = timezone.now() curs.close() conn.close() return listened, returned_empty It would be really nice if instead of using the psycopg2 library, I could use only django.db. Something like this: def listen_for_notify(self): from django.db import connection as conn listened = None returned_empty = None search_timeout = 15 with conn.cursor() as curs timeout = timezone.now() + timezone.timedelta(0, search_timeout) while timezone.now() < timeout: time_diff = timeout - timezone.now() if select.select([conn], [], [], … -
How to make username field to accept email in django?
I have a Django application that accepts username to login to the application. I want to change it from username to email, without using a custom user model. Here i am using the Django's in built user model and now i don't want to change it. How can i do that? -
django - Unsupported lookup for JSONField or join on the field not permitted
I am having a Json field in my models as - class Product(models.Model): ... detailed_stock = JSONField(load_kwargs={'object_pairs_hook': collections.OrderedDict},default=dict) I am having values in my database like - { "total":0, "5[1]":0 } I am trying to filter objects with total = 0, for that I tried - Product.objects.filter(detailed_stock__total = 0) but it throws error - Unsupported lookup 'total' for JSONField or join on the field not permitted. as per the documentation the following code is permitted. this is full traceback- Traceback (most recent call last): File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\braces\views\_access.py", line 102, in dispatch request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\views\generic\base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\views\generic\list.py", line 142, in get self.object_list = self.get_queryset() File "c:\Users\lenovo\Desktop\My_Django_Stuff\bekaim\accounts\views.py", line 142, in get_queryset queryset = Product.objects.filter(detailed_stock__total = 0) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 836, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1271, in _add_q current_negated, allow_joins, … -
static file are not loading in templates django
i am very new to django . m adding static files but they are not being shown in m templates when i runserver. if i add an static image the image does not load but only shows a img icon. #settings.py STATIC_DIR=os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIR=( STATIC_DIR, ) #INDEX.HTML <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>hey eeyone</h1> <img src="{% static "images/hotel.jpg" %}"> </body> </html> -
javascript code not working for external file
i have javascript code that send data to backend which when i place inline then work fine but when i place in external file it does not work.meanwhile other javascripts is working in external file. <script> $('#submit-ajax').click(function(event) { console.log('working or not') $.post( '/order/detail/', { 'test': 'hi i am here', }, function() { alert( "Data Loaded: " ); } ) }); </script> in external file code is: $(document).ready(function(){ $('#submit-ajax').click(function(event) { console.log('working or not') $.post( '/order/detail/', { 'test': 'hi i am here', }, function() { alert( "Data Loaded: " ); } ) }); } -
How to call 'set password' in Django using a fetch request - issue with csrfmiddlewaretoken?
I'm trying to create a 'reset password' function in my Django / React app. I'm using django-contrib-auth for the back end and most of this is working OK. However I can't get the POST request right in order to actually update the password. Here's the workflow. The user clicks a "forgot password" link and is shown a form where they enter their email address. They receive an email containing a link to click. They click the link and visit a page where they enter their new password twice and click "Submit". This is where the problem lies. If I use the built-in form generated by django-contrib-auth, the password is reset correctly. But I want to use a form generated by React, and in that page I'm sending a fetch request to the same endpoint. Here's a fetch request generated by the form which works: curl 'http://localhost:8000/api/v1/reset/Mw/set-password/' -H 'Cookie: meteor_login_token=OG2fh2iVTkn5AOujhdaBXCsetV-CQ1lS6ZLdtrtzFYC; csrftoken=uSEF8NQB0lUpimwfQcOWLt118igo0bQq2gbpTaGq7zvgQMeF4oM2cu3ZwfgmuDOa; sessionid=39awyoab3wouvxmacbzbxez2hrfoa498' -H 'Origin: http://localhost:8000' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Cache-Control: max-age=0' -H 'Referer: http://localhost:8000/api/v1/reset/Mw/set-password/' -H 'Connection: keep-alive' --data 'csrfmiddlewaretoken=ASbYGmwXWOTKagND1hWHK0DQt5Qo9MPq8gIIrJmM32uBIGv3ftUNb1FOR2QmDeNa&new_password1=sometext&new_password2=sometext' --compressed Here's my fetch request that … -
Accessing django template's dictionaries given a variable?
My question is if there's a way to obtain a value of a dictionary given a key. For example, imagine that my_dictionary is {1:'a', 2:'b', 3:'c'}and I have an attribute which is key which equals 1. How can I obtain 'a'? I tried with {{my_dictionary.key}}and {{my_dictionary.{{key}} }}but none of them worked. My idea is to do the same as with python, which is my_dictionary[key] but in a Django Template. Thank you -
Exclude And Operations Conditions Django
i want to AND and put all exclude query in one exclude function. User.objects.exclude(role_title='Super Admin').exclude(user_is_deleted = False) Above i have two exclude instead i want one User.objects.exclude(role_title='Super Admin', user_is_deleted = False) But it is not working in my view -
submit selected fields in many-to-many relation
I created a node and scheduled action models with manyTomany relation: class Node(models.Model): name = models.CharField(default='node', max_length=32) nb_solenoid = models.DecimalField(max_digits=19, decimal_places=10, null=True, blank=True) connexion = models.CharField(max_length=255) class ScheduledAction(models.Model): date = models.DateTimeField(default=datetime.now, blank=True) firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True) node_ids = models.ManyToManyField(Node) In forms.py: class ScheduledActionForm(forms.ModelForm): date = forms.DateTimeField() firm = forms.ModelChoiceField(queryset=Firme.objects.all()) node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.filter(), widget=forms.CheckboxSelectMultiple) class Meta: model = ScheduledAction fields = [ 'date', 'firm', 'node_ids' ] in views.py: def planification_view(request): scheduledAction = ScheduledActionForm(request.POST or None) nodes = Node.objects.all() if scheduledAction.is_valid(): scheduledAction.save() print('formulaire enregistre') scheduledAction = ScheduledActionForm() context = { 'form': scheduledAction, 'nodes': nodes } return render(request, "node/planification.html", context) The view works fine but how many nodes I check it always saves all the nodes in the many-to-many field. How can I make it only submit selected fields? -
AttributeError at /accounts/signup/ 'str' object has no attribute 'add'
Am new using django so i used practical example on this tutorial on extending user model using User Profile, am having trouble on form.py it gives that error, on removing this line; supervisor.su_mobile_number.add(*self.cleaned_data.get('su_mobile_number')) it works smoothly but no data for su_mobile_number was inserted o the database view.py class SupervisorSignUpView(CreateView): model = User form_class = SupervisorSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'supervisor' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('home') model.py class User(AbstractUser): is_supervisor = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Supervisor(models.Model): user = models.OneToOneField('User', on_delete=models.CASCADE, primary_key=True, related_name='supervisor') su_mobile_number = models.CharField(max_length=200) forms.py class SupervisorSignUpForm(UserCreationForm): su_mobile_number = forms.CharField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_supervisor = True user.save() supervisor = Supervisor.objects.create(user=user) supervisor.su_mobile_number.add(*self.cleaned_data.get('su_mobile_number')) return user -
Models.py Issue (Keys)
I'm trying to make a basic web application for as a small project and I'm facing an issue where whenever I use any type of relationship between 2 attributes. Like when I try to pull some data from another table, it gets displayed as "Person object(1)" or "project object(1)". How do I ensure that this doesn't happen and the name of the person and the name of the project shows up? Im also willing to accept any sort of help with improving my database codes.. Thank you in advance. Attached below is the source code. When I try to pull some data from another table, it gets displayed as "Person object(1)" or "project object(1)". How do I ensure that this doesn't happen and the name of the person and the name of the project shows up? from django.db import models from django.db import models from django.contrib.auth.models import User, Group from django.db import models from django.core.mail import EmailMessage from django.contrib import admin class Project(models.Model): STATUS_CHOICE = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ) project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=100) status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) finish_date = models.DateTimeField(null=True, blank=True) supporting_documents = … -
enumeration and capping items within either inlineformset_factory or modelformset_factory in Django
I have something that looks like this: https://imgur.com/gallery/9pnbBmJ and aside from adding a bit of "CSS/HTML makeup" I'm stuck here at the very last step of the very last leg of the project before I need to start looking into production settings and the like. Now, according to https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#inline-formsets (quite at the bottom; "Using an inline formset in a view") it should be possible to mass produce class objects, and it is, it would appear. I believe I'm on the right track, but I'm no expert in neither Python nor Django, unfortunately. What I'm trying to do is to: 1) limit/cap the objects to 9 items per user each of which may be edited later if the user should wish to do so, and 2) enumerate those items, ie. "(1), (2) ... (9)" so that I may avoid receiving the embarrasing MultipleObjectsReturned at /user/vulpes/ - get() returned more than one Gallery -- it returned 2! error. I've commented out some things: Firstly there's the matter of the modelformset_factory VS inlineformset_factory. I don't really know which to chose as the former returns one image per user whilst respecting the cap, while the latter returns many an image not respecting the cap … -
celery task status showing pending
I am working with celery and i am getting tasks status is pending, may be it is implementation problem. please check my code. I am trying to save task info like id, name, status in my mongodb database, for this i am using a function which my task will call to save data in mongodb. Am i getting my task pending because my function call is happening before return statement of task? settings.py CELERY_BROKER_URL = 'mongodb://localhost:27017/jobs' CELERY_RESULT_BACKEND = "mongodb" CELERY_IGNORE_RESULT = False CELERY_TRACK_STARTED = True CELERY_MONGODB_BACKEND_SETTINGS = { "host": "127.0.0.1", "port": 27017, "database": "jobs", "taskmeta_collection": "my_taskmeta_collection", } CELERY_BEAT_SCHEDULE = { 'add-every-minute-contrab': { 'task': 'username_length_periodically', 'schedule': crontab(minute='*/1'), #'args' : (2,3), }, } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE celery.py from __future__ import absolute_import, unicode_literals import os, logging from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestUserAPI.settings') app = Celery('UserAPI') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app … -
How does AUTH_LDAP_REQUIRE_GROUP work in django?
I am using following block of code , I copied from web : AUTH_LDAP_REQUIRE_GROUP = "cn=GALAXY_login,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM" AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active":"cn=GALAXY_login,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM", "is_staff": "cn=GALAXY_login,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM", "is_superuser":"cn=GALAXY_superuser,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM" } If i am only allowing GALAXY_login to login into application how will "is_superuser":"cn=GALAXY_superuser,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM" ever return true? My understanding is , I am only permitting the user which is in group GALAXY_login. Then how will "is_superuser" be true for any user? -
'User' object has no attribute 'soft_delete' - Django Soft Deletion
i have created soft delete in my project and it is working fine. But the problem is that i am using User in-built model and OneToOneField with UserProfile. Now soft_delete function is in UserProfile Model where im using generic.DeleteView to delete user. The problem is that i could not pass object of User to UserProfile to set user_is_deleted to True. Here is my Code. Views.py class UserDeleteView(LoginRequiredMixin, generic.DeleteView): model = User template_name = 'users/user_confirm_delete.html' success_url = '/users/' def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.soft_delete() return HttpResponseRedirect(self.get_success_url()) Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_role = models.ForeignKey(Roles, on_delete=models.CASCADE) user_is_deleted = models.BooleanField(default=False) user_deleted_at = models.DateTimeField(blank=True, null=True) def soft_delete(self): self.user_is_deleted = True self.user_deleted_at = timezone.now() - tdelta(days=-1) self.save()