Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get attribute 'CronTrigger'
Unable to restore job "b'30'" -- removing it Traceback (most recent call last): File "/opt/py3/lib64/python3.6/site-packages/apscheduler/jobstores/redis.py", line 131, in _reconstitute_jobs jobs.append(self._reconstitute_job(job_state)) File "/opt/py3/lib64/python3.6/site-packages/apscheduler/jobstores/redis.py", line 119, in _reconstitute_job job_state = pickle.loads(job_state) AttributeError: Can't get attribute 'CronTrigger' on <module 'apscheduler.triggers.cron' from '/opt/py3/lib64/python3.6/site-packages/apscheduler/triggers/cron/__init__.py'> Random errors encountered after Django restart,I don't know why def add_daily_task(task_id): crontab = CrontabTask.objects.get(pk=task_id) scheduler.add_job(func=crontab_task, args=[task_id], trigger=CronTrigger.from_crontab('%s %s %s %s %s' % (crontab.crontab_minute, crontab.crontab_hour, crontab.crontab_day, crontab.crontab_month, crontab.crontab_week)), id=str(task_id), jobstore='eazyops', replace_existing=True) this my add_job code -
chart is not getting updated from the values it received from Jquery
Use Case : I am trying to populate my chart based on the data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; chart.update(); } output of console.log(test_data) data: Array(3) 0: 500 1: 200 2: 50 length: 3 However this is not updating my chart . When i hard code the value as shown below , the chart is getting updated. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=[500,200,50]; chart.update(); } What is the trick i am missing here? -
Exception Value: no such table: phone_popular
im facing exception like no such table..also table is not creating in django database even after applying the makemigrations and migrate both. this is phone/models.py i tried "python manage.py migrate --run-syncdb phone" & many solutions but nothing happen.imagethis is my admin panel..here you can seen Popular table is shown -
Create txt file template with django email
I have a question according to emails generated in my Django application. I created an HTML file, but I have question with my txt file and tags used. In my HTML file: links look like: <a href="....">My link</a> bold looks like: <b>My text</b> variables look like: {{ my_variable }} But in my txt file, HTML tags work ? How I can display links and bold text in my .txt file which will send by email ? Thank you very much, -
problem in my regular expression when it should ask for pk and load next page it shows error
i am trying sort my web data by requesting primary keys. but it not going to that detail page. need some help. my urls.py file from django.conf.urls import url from django.contrib import admin from myapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^album/?$', views.music, name='music'), url(r'^detail/(?P<album_id>\d+)/$', views.detail, name='detail'), url(r'^Database/?$', views.Database, name='Database'), ] my views.py file def detail(request, album_id): try: album = Album.objects.get(pk=album_id) except album.DoesNotExist: raise Http404("Album does not exist") return render(request, 'album.html', {'album': album}) error messege: Page not found (404) Request Method: GET Request URL: http://localhost:8000/myapp/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='home'] ^album/?$ [name='music'] ^detail/(?P<album_id>\d+)/$ [name='detail'] ^Database/?$ [name='Database'] The current path, myapp/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
How can I create a view that retrieves all objects with matching primary key in url?
I have two models that form a one-to-many relationship. One pallet has multiple images associated with it. models.py class Pallet(models.Model): pallet_id = models.IntegerField(primary_key=True) def __str__(self): return str(self.pallet_id) class Meta: ordering = ('pallet_id',) class Image(models.Model): created = models.DateTimeField(auto_now_add=True) pallet = models.ForeignKey(Pallet, on_delete=models.CASCADE) image = models.FileField(upload_to="") def __str__(self): return str(self.created) I'm trying to create a view where I get all images associated with a particular pallet_id from the url. serializers.py class ImageSerializer(serializers.HyperlinkedModelSerializer): pallet = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Image fields = '__all__' class PalletSerializer(serializers.ModelSerializer): class Meta: model = Pallet fields = '__all__' urls.py urlpatterns = [ url(r'^pallets/', include([ url(r'^(?P<pk>[0-9]+)/$', views.PalletDetail.as_view(), name='pallet-detail'), ])), ] I think the issue is in the views.py with the PalletDetail class. I am confused on how to write the view based on the primary key from the URL. I've tried to use **kwargs['pk'] but does using this make it a function-based view? If so, would it be bad form to mix class-based and function-based views? How can I get similar behavior from class-based views? I'm really struggling with the views here: views.py class PalletDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Image.objects.prefetch_related('pallet_id').all() serializer_class = ImageSerializer -
Django 2 lose the change on models even after saving the update
I'm working on a project using Python(3.7) and Django(2.1) in which I'm updating a model and save it, after that if I check the list view first it shows the update correctly but once I opened the detailed view it loads the update and return back to previous state. Here's What I had tried: From models.py: class Order(models.Model): status_choices = ( ('Active', 'Active'), ('Completed', 'Completed'), ('Late', 'Late'), ('Short', 'Short'), ('Canceled', 'Canceled'), ('Submitted', 'Submitted') ) delivery_status_choices = ( ('Accepted', 'Accepted'), ('Rejected', 'Rejected') ) gig = models.ForeignKey('Gig', on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='selling') buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='buying') created_at = models.DateTimeField(auto_now=timezone.now()) charge_id = models.CharField(max_length=234) days = models.IntegerField(blank=False) status = models.CharField(max_length=255, choices=status_choices) delivery = models.FileField(upload_to=content_file_name, blank=True) def __str__(self): return f'{self.buyer} order from {self.seller}' From template.html: {% if not order.status == 'Completed' and not order.status == 'Submitted' and not order.status == 'Canceled' %} {% if order.buyer.username == user.username %} <form method="post" action="{% url 'order-cancel' %}"> {% csrf_token %} <input type="text" name="id" value="{{ order.id }}" hidden /> <button type="submit" class="btn btn-primary align-content-center">Cancel the Order</button> </form> {% elif order.status == 'Canceled' %} <p> Your order has been canceled already!</p> {% endif %} {% else %} <p> You can't cancel this order now.</p> {% endif %} and … -
Want to disable CSRF in openedx for one specific post request
In openedx I have used Xblock.json_handler for third party api consumption . But I want to disable csrf authentication for that one post api , can anyone help me out with that ? -
How can i pass my data in sqlite database to templates? ( to make line chart using highcharts)
i'm developing web application using dJango. My current situation is as below When users do something, the data is saved into sqlite database I want to pass my data to templates and draw line chart I want X-axle : YYYY-MM-DD / Y-axle : the count of request But, i have no idea how to make it. {{ addRequestCnt }} is presented like as below. "QuerySet [{'doDate':datetime.datetime(2019,4,15,0,0),'requestType__count':11}, {'doDate':datetime.datetime(2019,4,16,0,0),'requestType__Count':7}]>" ...... Thank you for helpful answer in advance. My models.py class ActivityLog(models.Model): doDate = models.DateTimeField() requestType = models.CharField(max_length=200) My views.py def dashboard(request): addRequestCnt = ActivityLog.objects.filter(requestType='add').values('doDate').annotate(Count('requesetType')) context = { 'addRequestCnt':json.dumps(addRequest, default=str), } return render(request,'dashboard.html',context) -
How to validate django custom model field attributes?
I am writing custom model field called EnumField for mysql database, which looks like below class EnumField(models.Field): def __init__(self, *args, **kwargs): self.values = kwargs['values'] kwargs['choices'] = [(key, value) for key, value in self.values] super().__init__(*args, **kwargs) def db_type(self, connection): enum_values = ",".join([key for key, value in self.values]) return f"ENUM({enum_values})" I hope this works well, but i can't figure out way to enforce constraints such as the values attribute should be list or tuple., and values attribute should contain unique key and values. for example if anyone tries to use EnumField like below with duplicate values i need to throw exception., How can i achieve that. option = EnumField(values=(('Y', 'yes'), 'Y', 'Yes')) -
How to enforce Uniqueness of a ManyToMany with through joiner to outside table
I don't even know if my title accurately describes what I'm looking for. So here it goes. I have 4 models: Person, Project, Group, GroupMember (joiner). I want to make sure a Person is only ever in one Project. The trick is, Person isn't joined to Project, it's joined to Group. I don't know if the __ reference for relational tables can do this? class Person(models.Model): name = models.CharField() class Project(models.Model): note = models.CharField() class Group(models.Model): project = models.ForeignKey(Project) members = models.ManyToManyField(Person, through='GroupMember') class GroupMember(models.Model): group = models.ForeignKey(Group) person = models.ForeignKey(Person) # Can only be in ONE group PER Project field = models.CharField() -
No admin address given, so no admin http server started
Running our docker-compose up code on macs and ubuntu causes no problems. Having some issues when we run it on Windows, and we have enough people on the project using Windows that we need to figure out the problem. I believe the problem is with envoy proxy, though I am very new to both Docker & envoy proxy so I am open to suggestions. When I run docker-compose up I get the following output: C:\Users\Kristi\gsn\api>docker-compose down Removing api_gsn_web_1 ... done Removing api_db_1 ... done Removing network api_edgeproxy_proxy-mesh C:\Users\Kristi\gsn\api>docker-compose up Creating network "api_edgeproxy_proxy-mesh" with the default driver Creating api_db_1 ... done Creating api_gsn_web_1 ... done Attaching to api_db_1, api_gsn_web_1 db_1 | 2019-04-16 11:13:15.927 UTC [1] LOG: listening on IPv4 address "0. 0.0.0", port 5432 db_1 | 2019-04-16 11:13:15.928 UTC [1] LOG: listening on IPv6 address ":: ", port 5432 db_1 | 2019-04-16 11:13:15.930 UTC [1] LOG: listening on Unix socket "/va r/run/postgresql/.s.PGSQL.5432" db_1 | 2019-04-16 11:13:15.945 UTC [21] LOG: database system was shut dow n at 2019-04-16 11:10:48 UTC gsn_web_1 | Running Django Migrations. gsn_web_1 | No changes detected gsn_web_1 | Operations to perform: gsn_web_1 | Apply all migrations: admin, auth, contenttypes, gsndb, sessions gsn_web_1 | Running migrations: gsn_web_1 | No … -
i want to sum up expense totals and return the value as Report total in totalAmount
from django.contrib.auth.models import Permission, User from django.db import models from django.utils import timezone class Movement(models.Model): startDate = models.DateField(default=timezone.now) recordTime = models.DateTimeField(default=timezone.now) endDate = models.DateField(max_length=50) purpose = models.CharField(max_length=250) location = models.CharField(max_length=250) noOfDays = models.IntegerField vehicleType = models.CharField(max_length=100) bookingStatus = models.CharField(max_length=250) done = models.BooleanField(default=False) cancelled = models.BooleanField(default=False) def __dir__(self): return self.location + '|' + self.done + '|' + self.cancelled class Report(models.Model): createdOn = models.DateField(default=timezone.now) SubmittedOn = models.DateField(default=timezone.now, null=True,blank=True) userName = models.CharField(max_length=250) weekNo = models.CharField(max_length=20) location = models.CharField(max_length=100) projectCode = models.CharField(max_length=100) totalAmount = models.FloatField(max_length=300, default=0) flatsComment = models.CharField(max_length=300, default="") financeComment = models.CharField(max_length=300, default="") def __str__(self): return self.userName + '|' + self.location + '|' + self.weekNo class Expense(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE) date = models.DateField(default=timezone.now) item = models.CharField(max_length=250) unit = models.CharField(max_length=20) unitPrice = models.FloatField(max_length=100) quantity = models.FloatField(max_length=100) total = models.FloatField(max_length=250) i want the result to be a summation of all of the expense_total that belong to a report object. whenever a new expense is created it's total should be added automatically to the report_toalAmount -
Profile module not syncing, neither the groups (django_auth_ldap)
I am using django_ldap_auth 1.7 with django version 2.2. According to their documentation, one can populate the UserProfile model also along with User model. I have read the documentation, arranged my settings.py and models.py it that way. But no success,I am only able to populate the User model only but the profile model. account/models.py `class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) user_id = models.CharField(max_length=16, null=True, blank=True) firstname = models.TextField(null=True, blank=True) lastname = models.CharField(max_length=16, null=True, blank=True) role = models.CharField(max_length=16, null=True, blank=True) class Meta: app_label = 'account' def __str__(self): return self.user.username def __init__(): print("Initiated User Profile")` settings.py import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, GroupOfUniqueNamesType import logging AUTH_PROFILE_MODULE = 'account.UserProfile' AUTH_LDAP_SERVER_URI = 'myURl' AUTH_LDAP_BIND_DN = '' AUTH_LDAP_BIND_PASSWORD = '' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=People,dc=cse,dc=iitb,dc=ac,dc=in', ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', } AUTH_LDAP_PROFILE_ATTR_MAP = { 'userid': 'uid', 'firstname': 'givenName', 'lastname': 'sn', 'role' : 'employeeNumber', } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=People,dc=cse,dc=iitb,dc=ac,dc=in",ldap.SCOPE_SUBTREE,"(objectClass=groupOfNames)") AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_MIRROR_GROUPS = True .... logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) console output of logger search_s('ou=People,dc=cse,dc=iitb,dc=ac,dc=in', 2, '(uid=%(user)s)') returned 1 objects: uid=csehem,ou=pg17,ou=pg,ou=students,ou=people,dc=cse,dc=iitb,dc=ac,dc=in Creating Django user csehem Populating Django user csehem search_s('ou=People,dc=cse,dc=iitb,dc=ac,dc=in', 2, '(&(objectClass=groupOfNames)(member=uid=csehem,ou=pg17,ou=pg,ou=students,ou=people,dc=cse,dc=iitb,dc=ac,dc=in))') returned 0 objects: What's wrong? Can anyone please tell me, why I am not able … -
How to generate Queues per user inside celery?
So I'm trying to move blocking stuff from web request as background tasks and leveraging queue. I'm also new to messaging and pub/sub. Users push there data and it is processed and later users are notified about that. I made a celery setup for this and found that it doesn't satisfy my use case for having private queue for every user for their own tasks. I tried specifying creation of missing queues and during worker spawning (sending queue names comma separated) and also listing them in queues settings as stated in previous answers over internet for "dynamic queue creation with celery". It creates the queues, but doesn't when I specify different queue name than specified names in settings and command line. The solution is to spawn more workers with queue names which doesn't satisfy the use case as there will be millions of data processing requests. I've found that python-rq has Queue object initialization with its name, which I think creates new queue. If it does, will shifting to RQ will be right? redis_conn = Redis() q = Queue('some_queue', connection=redis_conn) What I want is per user queue for their own tasks in the background. I don't see any solutions online … -
why i am getting RecursionError?
so i am using django==1.11.2. where i have 2urls.py. which i linked with include but while running i am getting recursion error issue. my main urls.py file from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('project1.urls')), ] my apps url.py file from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.blogIndex, name='blogindex'), url(r'^detail/(?P<postid>.+)$', views.blogDetail, name='blogDetail'), ] error messege: File "/Users/shahariarshanto/Desktop/blog/env_week2/lib/python3.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/shahariarshanto/Desktop/blog/env_week2/lib/python3.7/site-packages/django/urls/resolvers.py", line 255, in check warnings.extend(check_resolver(pattern)) File "/Users/shahariarshanto/Desktop/blog/env_week2/lib/python3.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/shahariarshanto/Desktop/blog/env_week2/lib/python3.7/site-packages/django/urls/resolvers.py", line 255, in check warnings.extend(check_resolver(pattern)) File "/Users/shahariarshanto/Desktop/blog/env_week2/lib/python3.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/shahariarshanto/Desktop/blog/env_week2/lib/python3.7/site-packages/django/urls/resolvers.py", line 170, in check warnings = self._check_pattern_name() RecursionError: maximum recursion depth exceeded my views.py file from django.shortcuts import render, get_object_or_404 from .models import BlogPost def blogIndex(request): blogposts = BlogPost.objects.order_by('-pub_date') context = { 'heading':'The Blog', 'subheading':'', 'title':'Blog', 'copyright':'Pending', 'blogposts':blogposts, } return render(request,'blog-home-2.html',context) def blogDetail(request,postid): post = get_object_or_404(BlogPost, pk=postid) context = { 'post' : post, 'copyright':'Pending', } return render(request,'blog-post.html',context) i want this blog page to run. can anyone please give some suggestion.. -
Can i use stored procedures in displaying the data in the data table
i need to display a data-table in django and the data needs to be retrieved from the stored procedure. which plugin can i use to meet the requirement. I have used BaseDatatableView for data-table.I have used django-orm queries while working with BaseDatatableView.But when i tried to call a procedure it is showing error.My requirement have changed from queries to stored procedures.How can i achieve that? In Views.py: def get_initial_queryset(self): ret,count = getdbvalues.proc_Common_Report(str(reportType),str(self.request.POST.get('data[isentity]')),str(searchFromDate),str(searchToDate),str(CommID)) return ret In Procedures.py: cur.callproc('USP_RTM_SUMMARY_REPORT',(flag,startdate,enddate,serviceArea,UCCType)) response=cur.fetchall() cur.nextset() count=cur.fetchall() cur.close() return response,count -
How to get foreign key value in django aufitlog using bulit in django audilog
In my case i need to get foreignkey value using built in django auditlog with inser,update and delete operations. models.py def _get_fk_value(self, instance): fk_field = instance._meta.get_field('donor_n_key') fk = getattr(instance, fk_field, None) if isinstance(fk, models.Model): fk = self._get_fk_value(fk) return fk Please anyone help me to solve this. -
How can i implement push notification in android application?
I want to implement push notification in for android application, i am using server side django notification will push by django server, how can i implement push notification(note. I don't want use firebase shoud i write it using django channel or someting lisk pub-sub services) -
How to use objects.filter() to select the Boolean True posts only
i want to establish a queryset of Post(model) which filters only the published=True in the Public view. i have tried .... return Post.objects.filter('published'==True).all() Views.py class PublicList(ListView): template_name = 'publish.html' context_object_name = 'items' model = Post def get_queryset(self): return Post.objects.filter('published'==True).all() models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() created_on = models.DateTimeField(default=timezone.now) published = models.BooleanField(default=False) def publish(self): self.published=True self.save() def unpublish(self): self.published=False self.save() def __str__(self): return self.title the traceback errors: File "C:\Users\AngryBuLLz\Desktop\Django\prac_18\firstapp\views.py" in get_queryset 82. return Post.objects.filter('published'==True).all() File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) -
How to fix django app error in edx-platform
I want to add a new app in the https://github.com/edx/edx-platform. I am following this https://docs.djangoproject.com/en/2.2/intro/tutorial01/ document /edx/app/edxapp/edx-platform/myapp/url.py from django.conf.urls import url from . import views urlpatterns = [ url('', views.hello, name = 'hello'), ] /edx/app/edxapp/edx-platform/lms/envs/common.py INSTALLED_APPS = [ # Standard ones that are always installed... 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.redirects', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'djcelery', 'myapp', ............. /edx/app/edxapp/edx-platform/lms/urls.py urlpatterns = [ url(r'^$', branding_views.index, name='root'), # Main marketing page, or redirect to courseware url(r'', include('student.urls')), # TODO: Move lms specific student views out of common code url(r'^dashboard/?$', student_views.student_dashboard, name='dashboard'), url(r'^change_enrollment$', student_views.change_enrollment, name='change_enrollment'), url(r'^myapp/', include('myapp.urls')), My Error Traceback (most recent call last): File "manage.py", line 123, in <module> execute_from_command_line([sys.argv[0]] + django_args) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/urls/resolvers.py", … -
Django: How do I include username in url?
Django2.1 My application wants to include twitter username in url, but an error occurs. I can get uesrname correctly, but I can not connect to url correctly. What is the cause? An error occurs when accessing detail. ValueError at /Temporary username/detail invalid literal for int() with base 10: 'Temporary username' #views.py class MyCreateView(LoginRequiredMixin, CreateView): model = Mymodel form_class = MyForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user return super(MyCreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('detail', kwargs={"pk": self.request.user.username}) #urls.py urlpatterns = [ path('<slug:pk>/detail', MyDetailView.as_view(), name="detail"), path('create/', MyCreateView.as_view(), name="create"), ] Thank you -
How to retrieve user data from database and validate it?
In Django login forms ,how to retrieve user data from database and verify it? How to send otp to registered mobile number in django? -
Why is django get request returning 400 status code when get parameter is not included in the request url?
I have created rest API endpoint which requires one get parameter 'id'. When I am including 'id' in url it is working fine but when I am excluding 'id' it is giving 400 status code. I am using Django 1.10 as web framework and Django rest framework for APIs. The class based view is written to return empty object if 'id' parameter is not present in the get request. I have tried different url patterns but nothing seems to work. The url pattern is as below- urlpatterns = [ url(r"^scheme/", APIScheme.as_view()), ] I am using Postman to send request. For url {{base}}/scheme/?id=1 I am getting expected result but for url {{base}}/scheme/ it is returning status code as 400. What can be the reason for this and how to debug this? -
Django how to make createsuperuser checks for duplicate email adress
def create_superuser(self, username, email, password=None): user = self.create_user( username, email, password=password ) user.is_admin = True user.is_staff = True user.active = True user.save(using=self._db) return user I have made a custom user model. When I call createsuperuser, if the username I entered is already in the database, it will prompt 'Error: That username is already taken.' But if I entered a email address which already exists in the database, it will not prompt the email has been taken error. Instead, it let me pass through and gave me the following error after I entered the password: django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email Is there a way to make it also check the email address like the way it checks the username?