Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
efficient filter objects in django based on other tables objects
I have two models in django and I want to remove all objects from one table, that match a subset of the other tables params. My Question now is, what is the most efficient way. a are around 5000 Objects, while b are around 40.000 Objects. My current solution looks like this, but that doesn't feel right. a_with_a_and_b = a.objects.filter(param1='a', param2='b').values('c','d') for a in a_with_a_and_b: _b = b.filter(param3=a['c'],param4=a['d']) if _b: print('delete it') -
How to show controls based on condition in template django
In the template file, I have written condition as below: {% show_combobox form.hot_bubble_style %} {% if form.hot_bubble_style.data is None or form.hot_bubble_style.data == "1" %} {% show_input form.hot_bubble_diameter form.hot_bubble_diameter_units "hot_bubble_remove" %} {% else %} {% show_input_image form.hot_bubble_width form.hot_bubble_width_units "hot_bubble_remove" "eoc/images/oblong-bubble-width.png"%} {% show_input_image form.hot_bubble_length form.hot_bubble_length_units "hot_bubble_remove" "eoc/images/oblong-bubble-length.png"%} {% endif %} This is how I have completed my code. I am just curious to know the standard way to handle this condition in the Django-template. Notes: show_combobox, show_input_image, show_input are custom tags. -
How to create Dynamic Form fields in Django using MYSQL?
I want to create a Form in Django like CRM system have(e.g SalesForce) where users can create or remove any number of fields. My question is that How I will store data into the database? Should I create a table column for an individual field? Should I have to store DATA in Json Or Array field? -
Django - models - access a value of a field within a class
class Tag(models.Model): '''Items have tag will have according discount percentage''' tag_discount_percentage = models.IntegerField() slogan_default = 'Purchase NOW for extra {}% off!'.format(tag_discount_percentage.get_prep_value(value)) slogan = models.CharField(max_length=200, default=slogan_default) def __str__(self): return self.slogan `slogan_default = 'Purchase NOW for the extra {}% off!'.format(tag_discount_percentage.get_prep_value(value)) NameError: name 'value' is not defined` urggg! Question 1: How does one access a field's own value within that class? Or is there a better to set the default for slogan CharField? tag_discount_percentage itself is <django.db.models.fields.IntegerField> but I want the value Question 2: Could I set a digit limitation to an IntegerField? all I found was max_length which prompts a warning saying that 'max_length will be ignored'... -
Django Rest Framework pagination not working
These are my version Django==3.0.2 djangorestframework==3.11.0 and this is my setting REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } and this is my views: class CostList(ListCreateAPIView): serializer_class = CostSerializers def get_queryset(self): cost = Cost.objects.filter( id='filtered with one of my id' ) return cost this is my serializer: class CostSerializers(ModelSerializer): class Meta: model = Cost fields = '__all__' Everything is working fine but the only issue is pagination. I have 100+ entry in cost model and I see it is rendering all the entry together, not paginating item following my settings -
Elastic Beanstalk Django migrations not working
I've made a .ebextensions/02_python.config file: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true 02_createsu: command: "source /opt/python/run/venv/bin/activate && python manage.py createsu" leader_only: true 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" But when I run eb deploy, it throws me the following error: Creating application version archive "app-8987-200210_133822". Uploading vspmfinal/app-8987-200210_133822.zip to S3. This may take a while. Upload Complete. 2020-02-10 08:08:27 INFO Environment update is starting. 2020-02-10 08:08:52 INFO Deploying new version to instance(s). 2020-02-10 08:09:03 ERROR [Instance: i-0ba93a0edfd159030] Command failed on instance. Return code: 1 Output: (TRUNCATED)...ack(traceback) from exc_value File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "accounts_user" does not exist. container_command 01_migrate in .ebextensions/02_python.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-02-10 08:09:03 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2020-02-10 08:09:03 ERROR Unsuccessful command execution on instance id(s) 'i-0ba93a0edfd159030'. Aborting the operation. 2020-02-10 08:09:03 ERROR Failed to deploy application. My app name is accounts. I've created my own user class by overriding Django's user class. What am I doing wrong? Why is the migration not working? I'm creating this application for the first time. -
create objects in django at runtime and save them in the database
I want to save parameters in django. Now, however, I do not yet know which parameters will all appear in the future and I do not want to store this hard in the code. So my idea was that I simply create an instance with a list (many-to-many) for each new parameter. so that the user can create it himself at runtime. the problem, which may not be one, is that he writes all the different parameters in a table. So under one another are the parameters of different settings that have nothing to do with each other. However, many values can exist for a parameter. it is actually nicer to have a separate table for each parameter, isn't it? so purely from performence? how would you solve the problem? -
In django rest framework is it possible to get data in POST request
i want ur help pls help, i am creating a api to retrieve the data from db. My aim is to i have a model class (id,name, email, password, role, date) now in POST request in postman i want some data like (name, email, id) if i pass the key and value = email and password in form data. My Code `models.py class Students(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=50) email=models.CharField(max_length=50) password=models.CharField(max_length=100) role=models.CharField(max_length=50) date=models.DateTimeField(auto_now=False, auto_now_add=True) serializers.py class StudentsSerializer(ModelSerializer): class Meta: model=Students #fields='__all__' fields=['name', 'email', 'role', 'id', 'date'] views.py class Students(ModelViewSet): queryset=Students.objects.all() serializer_class=UsersSerializer urls.py router=routers.DefaultRouter() router.register('uapi',views.Students) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include(router.urls)), ]` -
Get list of all users in a ldap3 group Python
I have tried to get all the attributes of users inside a ldap3 group but I want to fetch only the usernames in that group. code : ldap_server = Server('abc.com', get_info=ALL) conn = Connection(ldap_server, auto_bind=True) conn.search('ou=groups,dc=abc,dc=com', '(cn={})'.format('mygroup.users'), attributes=['*']) group = conn.entries[0] group.member will give all the user details like this, uid=user1,ou=people,dc=abc,dc=com uid=user2,ou=people,dc=abc,dc=com I want to get all the user ids in a flat list like [user1,user2..] so that I can compare with the entries in DB and remove unnecessary entries. Thanks -
moving simple python web project using opencv.js with http.server to django web framework
I want to ask how to bring a project that uses the syntax "python -m http.server" to the django framework. I did this because I wanted to run opencvjs to my django web project. please help, and thank you in advance. -
json schema generator for django admin page
i have a model in django for category like below : class Category(models.Model): category_name=models.CharField(max_length=255,unique=True) type = models.ForeignKey(Type, on_delete=models.CASCADE) attributes_Schema = JSONField() in this model i need to save attribute schema like below in attributes_Schema field : DATA_SCHEMA = { 'type': 'object', 'title': 'Data', 'properties': { 'price': { 'title': 'color', 'type': 'string', }, 'color': { 'title': 'color', 'type': 'string', 'enum': ['red', 'blue', 'black'] }, 'size': { 'title': 'size', 'type': 'string', 'enum': ['L', 'M', 'S'] } }, "required": ['color','size'] } the problem is is need a form to generate something like DATA_SCHEMA in my admin page. i did it by jquery but i wanna know is there any widget for generating json like DATA_SCHEMA in which i can give data type and different variations and it convert the form to json schema. i searched a lot and just can find some widget to generate form from jsonSchema ,but i need the reverse . -
Django 3 autocomplete in ModelForm like in ModelAdmin
I've found Django 3.0 can use an autocomplete feature in the ModelAdmin. (see https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields) How can I use the same feature in a ModelForm ? Thanks -
Django date value prints comma in template
I am currently passing a data from model to html template in Django project via views. So model is called Student, there is a attribute called DOB. However, when I try Student.DOB.year on html template, instead of printing 1998, it would print 1,998. Is there a way to remove the comma? Thanks in advance -
How to configure settings.py for mongoengine via django
I am trying to connect to mongodb via mongoengine in django. But all i am getting is error while migrating. Any reference would be deeply appreciated DBNAME = 'blog' _MONGODB_USER = '' _MONGODB_PASSWD = '' _MONGODB_HOST = 'localhost:27017' _MONGODB_NAME = 'blog' _MONGODB_DATABASE_HOST = 'mongodb://localhost:27017/blogdb' mongoengine.connect(DBNAME, host=_MONGODB_DATABASE_HOST) -
insert html using js
I try using ajax after submitting the form to get another $(document).ready(function() { $("#my_form").submit(function(event) { event.preventDefault(); $this = $(this); $.ajax({ type: "POST", data: $this.serialize(), success: function(data) { console.log(data); document.getElementById("my_form").replaceWith(data.form1); }, error: function(data) { console.log(data); } }); }); }); but on the page the html code is inserted as a string, how can this be fixed? -
NoReverseMatch: with arguments '('',)' not found
Reverse for 'vehicle_details' with arguments '('',)' not found. 1 pattern(s) tried: ['Masterlist/VehicleMasterlist/Details/(?P[0-9]+)$'] <table id="vtable" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="/api/masterlist/?format=datatables"> <thead> <tr> <th>Activity No</th> <th>NO</th> <th>Plate Number</th> <th>Conductions Sticker No.:</th> </tr> </thead> </table> This is my Views.py path('VehicleMasterlist/Details/<int:pk>', vehicleMasterDetails.as_view(), name='vehicle_details'), I i'm trying to hold the value of PK to edit/view sa existing data using js and HMTL5. And also using a Django API Rest Framework for my table. How to get/hold the value of PK once it click the row in the table? Thanks This is my JS code: {% block extra_js %} <script> $(document).ready(function() { var table = $('#vtable').DataTable({ "serverSide": true, "scrollX": true, "ajax": "/api/masterlist/?format=datatables", "columns": [ { "targets": 0, "data": "Activity_Id", "render": function(data, type, row, meta){ var id = data.row( this ).attr("id"); if(type === 'display'){ data = '<a href="{% url 'vehicle_details' id %}">' + data + '</a>'; } return data; } }, {"data":"NO"}, {"data":"PLATE_NO"}, {"data":"CS_NO"}, ] }); $('#vtable').on( 'click', 'tr', function () { if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } } ); }); </script> {% endblock %} -
Django Pagination datatable (datatable.net) with data in ajax, need to filter data with form
I have successfully filtered data with a date range form with this code bellow. But there are some obstacles when the intended date filter is not encapsulated. So the data filter has an overall impact for users even anonymous users. So when returning to the home page and then returning back to the data page, the filter object does not return to normal but still with the previous filter data. How can I make those filter object only valid in each session in django, and also reset those filter object returns to normal (reset) when out from that data page. please take look in view.py in line: # was forced to do this because only this way i can filter the data succeed. # the problem is filter object data can not encapsulated to unique session. x = JurnalListViewAjax x.last_day_in_month = end x.first_day_in_month_date = start views.py class JurnalListViewAjax(generic.View): obj = models.Jurnal.objects # last_day_in_month = timezone.datetime(2017, 8, 31).date() # first_day_in_month_date = timezone.datetime(2017, 8, 1).date() last_day_in_month = timezone.now().date() first_day_in_month_date = last_day_in_month.replace(day=1) def post(self, request): jurnal = self._datatables(request) return HttpResponse(json.dumps(jurnal, cls=DjangoJSONEncoder), content_type='application/json') def _datatables(self, request): datatables = request.POST draw = int(datatables.get('draw')) start = int(datatables.get('start')) length = int(datatables.get('length')) search = datatables.get('search[value]') if self.obj.all().filter(dateday__range=[ self.first_day_in_month_date, … -
Paypal IPN validation always returning INVALID
This might seem like a duplicate question but I wouldn't be here if neither of the proposed solutions did work. I have been trying to integrate Paypal IPN on my server-side according to their docs and the Github code sample here https://github.com/paypal/ipn-code-samples/blob/master/python/paypal_ipn.py I have changed the encoding of my sandbox business account to UTF-8 as per this answer Paypal sandbox IPN return INVALID but I keep getting the same INVALID response. I am using python with Django REST framework. Here's my code. class PaypalWebhookAPIView(APIView): permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): VERIFY_URL_PROD = 'https://ipnpb.paypal.com/cgi-bin/webscr' VERIFY_URL_TEST = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr' # Switch as appropriate VERIFY_URL = VERIFY_URL_TEST data = { 'cmd': '_notify-validate', **request.data } # Post back to PayPal for validation headers = {'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Python-IPN-Verification-Script'} response = requests.post(VERIFY_URL, data=data, headers=headers) response.raise_for_status() import pdb pdb.set_trace() # Check return message and take action as needed if response.text == 'VERIFIED': pass elif response.text == 'INVALID': pass else: pass Please help. -
Django model foreignkey always defaults no matter what user is logged in
I have this django model for questions. class Question(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL) question_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False) question = models.CharField(max_length=150, null=False) question_description = FroalaField() created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) question_image = models.ImageField(upload_to=get_upload_path, blank=True, null=True) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) dynamic_link = models.CharField(max_length=225, null=False, default="") question_type = models.CharField( max_length=50, null=False, choices=QUESTIONSTYPE_LIST) question_status = models.CharField(max_length=150, null=False, default="unapproved") is_active = models.BooleanField(default=False) objects = QuestionManager() class Meta: ordering = ['-updated_at'] def __str__(self): return self.question_id def get_absolute_url(self): kwargs = { 'questiontype': slugify(self.question_type), 'questionid': self.question_id, 'slug': slugify(self.question) } return reverse("questions:detail", kwargs=kwargs) Everything seems to be working okay, except that the user user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.SET_NULL) always saves but the default which is 1. So no matter which user is logged in and in session, it always defaults to 1. I am using classed-based-views and the user is a CustomUser. I have the customUser set in settings.py auth_model_user as: AUTH_USER_MODEL = 'users.CustomUser' If I do a request.user in the views.py file, I always get the right user. So why is my model behaving this odd? -
How to customize the Page type model's IndexView - the listing view in Wagtail Admin
I have multiple types of Page models in wagtail with parent page and subpages hierarchy. I want to customize the Index-view or the listing view to add more fields in all the pages under the main dashboard page in the Wagtail admin. The Pages are registered by default to show in wagtail admin, can I write a method to overwrite the list of fields to show in index view or is there a way to overwrite the ModelAdmin for Page types and use list_display to add more fields? -
Many POST form in template of Django [duplicate]
I have 2 POST form in 1 template of Django. How can I solve any single form in one function of view.py: template/index.html # first form <form method="POST" name="form_1" action="#"> {# Something in form #} </form> # Second form: <form method="POST" name="form_2" action=""> {# Something in form#} </form> In the view.py: def process(request): if request.method == 'POST': # i want to solve form_1 in this function Pls help me. I can't find any django docs to solve it. Thanks a lot -
social-app-django - Setup REDIRECT URL for GoogleOAuth2 not working?
I am using social-app-django GoogleOAuth2 backend and hit a problem with redirect_uri I managed to setup INSTALLED_APP, AUTHENTICATION_BACKENDS, url.py and add below 3 in settings SOCIAL_AUTH_GOOGLE_OAUTH2_KEY='MY KEY' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET='MY SECRET' LOGIN_REDIRECT_URL='http://localhost:8000/api/auth/complete/google-oauth2/' I have http://localhost:8000/api/complete/google-oauth2/ added into my google Authorised redirect URIs. I triggered auth login by accessing http://127.0.0.1:8000/login/google-oauth2/ (yes, my project use react on frontend, so not using Django templates). Problem is I always get this error Error: redirect_uri_mismatch The redirect URI in the request, http://127.0.0.1:8000/complete/google-oauth2/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: .... It looks like redirect url settings does work, any idea what's wrong? -
Implement Many to Many with Django (No duplicates)
There is a table that has lob(one-to-many field) each lob is mapped to 1 or more client, so there is another table called client(many-to-many). Basically once you select a lob an ajax call is made and the related clients are fetched and displayed on the template client = models.ManyToManyField(Client) lob = models.ForeignKey( LoB, on_delete=models.SET_NULL, null=True ) Now there needs to change lob to many-to-many, but the issue is a client can be mapped to more than one lob, so once multiple lobs are selected it would end up showing duplicate clients. Any ideas how to handle this! Tables lob -->Testing -->Developing -->Designing client -->US -->IND -->AFRICA client-lob Testing-->US Testing-->IN Designing-->IN -
In Django, how to iterate Json directory?
I am trying to iterate Json directory in html file with Django. But my code does not work. Can you please check it? I have this Json directory, and I would like to iterate the directory[lists] part. directory = { 'amount': '50000', 'country': 'Philippines', 'lists': [ { 'id': 583, 'companyname': 'AIchat', 'country': 'Philippines', 'number': '081', 'howtohire': 'BT', 'how_long_take': '', 'below': 30001, 'upper': 100000, 'loyalty': 1280 }, { 'id': 709, 'companyname': 'Stoks', 'country': 'Philippines', 'number': '082', 'howtohire': 'BT', 'how_long_take': '', 'below': 3000, 'upper': 450000, 'loyalty': 1000 } ] } I have put the directory into views.py Also, in the html file, I have put the below part. {% for list in lists %} <p>{{list.companyname}}</p> <p>{{list.loyalty}}</p> <p>{{list.howtohire}}</p> {% endfor %} It does not print at all, though. When I checked the printout of directory["amount"], directory["country"], it worked in html. So, I think that the above syntax of Json would be wrong at some parts. Can I get help with this? Thank you. -
Django Constraint with (AND) OR (AND)
The documentation and other online resources seem unclear if I can actually do this, but I'm sure I can. I have the following MySQL constraint on table_a: CHECK ( ("column_a" IS NOT NULL AND "column_b" IS NOT NULL) OR ("column_x" IS NOT NULL AND "column_y" IS NOT NULL) ) How can I implement this into a Django 3 model? There doesn't seem to be a relevant Meta function available for custom constraints.