Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Easy editable table in django
I am new to programming and learning as I build more... I am working on creating a view to show a data table on the html page and used the below code so far.. Models.py from django.db import models class MySetters(models.Model): mytsettername = models.CharField(max_length=100) Allowed = models.BooleanField(default=False) def __str__(Self): return self.mytablename views.py def setterveiew(request): context = {'setterlist':MySetters.objects.all} return render(request,'setterspage.html',context) I was able to add it to the template and display the table and data. However, this table is currently readyonly.. is there a way to make it editable in line. read a lot of articles online however all of them are using ajax and jquery and I have no clue in that language and how to implement that. Also, Can someone please advise how to add a check box to the table so that users can select multiple of them and hit a button so that an action can be performed. Please advise. Thank you -
uwsgi: RuntimeError: cannot release un-acquired lock
I am running uwsgi (with django in a docker container), and every worker that spawns comes with this error: spawned uWSGI master process (pid: 1) web_1 | spawned uWSGI worker 1 (pid: 18, cores: 2) web_1 | Exception ignored in: <function _after_at_fork_child_reinit_locks at 0x7fd944954ca0> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/logging/__init__.py", line 260, in _after_at_fork_child_reinit_locks web_1 | spawned uWSGI worker 2 (pid: 19, cores: 2) web_1 | _releaseLock() # Acquired by os.register_at_fork(before=. web_1 | File "/usr/local/lib/python3.8/logging/__init__.py", line 228, in _releaseLock web_1 | _lock.release() web_1 | RuntimeError: cannot release un-acquired lock Here is my uwsgi .ini file: [uwsgi] strict = true ; only explicitly understood configration allowed module = myapp.wsgi need-app = true ; don't start if can't find or load django app ### PROCESS SETTINGS ############### master = true ; gracefully re-spawn and pre-fork workers, consolidate logs, etc enable-threads = true processes = 10 ; maximum number of worker processes threads = 2 thunder-lock = true socket = 0.0.0.0:8000 ; too complicated for me to get a unix socket to work with docker, this is fine. #socket = /tmp/myapp.sock vacuum = true ; on exit, clean up any temporary files or UNIX sockets it created, such … -
TypeError: createTask() got an unexpected keyword argument 'prefix'
I'm currently working on some presence project. Actually i did asking other question about this project before (but my coworkers suggest me to change some of the structure) I think this one is promising. But unfortunately, we get some error like TypeError: createTask() got an unexpected keyword argument 'prefix' Here's my app.py problematic programs: @app.route("/database", methods=['GET', 'POST']) def database(): cform = createTask(prefix='cform') dform = deleteTask(prefix='dform') uform = updateTask(prefix='uform') reset = resetTask(prefix='reset') if not session.get('email'): return redirect(url_for('login')) elif request.method == 'POST': if cform.validate_on_submit() and cform.create.data: return createTask(cform) if dform.validate_on_submit() and dform.delete.data: return deleteTask(dform) if uform.validate_on_submit() and uform.update.data: return updateTask(uform) if reset.validate_on_submit() and reset.reset.data: return resetTask(reset) # read all data docs = db.tasks.find() data = [] for i in docs: data.append(i) return render_template('database.html', cform = cform, dform = dform, uform = uform, data = data, reset = reset) here's my database.html <html> <head> <title>Simple Task Manager</title> <style> .newspaper { -webkit-column-count: 2; /* Chrome, Safari, Opera */ -moz-column-count: 2; /* Firefox */ column-count: 2; } .head { text-align: center; } </style> </head> <body> <div class="head"> <h1>SIMPLE TASK MANAGER</h1> <h2>using MongoDB</h2> </div> <div class="newspaper"> <form method="POST"> {{ cform.hidden_tag() }} <fieldset> <legend>Create Task</legend> {{ cform.nama.label }}<br> {{ cform.nama }}<br> {{ cform.tanggal.label }}<br> {{ cform.tanggal }}<br> … -
How to get foreign key id in serializer?
How can I get status_name and status id in Course serializer? Updated with status My models: class Course(models.Model): name = models.CharField(max_length=255) class Status(models.Model): COURSE_STATUS = ( ('DONE', 'Done'), ('IN PROGRESS', 'In progress'),) course_status = models.CharField(max_length=9, choices=COURSE_STATUS, default='DONE' ) course = models.ForeignKey(TrainingCourse, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="students") class Meta: verbose_name_plural = 'Statuses' verbose_name = 'Status' unique_together = ('user', 'course') My serializer: class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ['name'] -
Django rest-frameowrk required = False for nested serializer not working
Struggling since 2-3 hours now. Don't understand why I am not able to save VisVisitParametersSerializer. It gives an error This field may not be null. for parameter_values when I don't pass data for parameter_values. I have gone through the similar kind of issues disscussed here but that does not solve my problem. can someone help me on this? However, when trying to use this serializer and not supplying the details, I receive the following: Serializers: class VisVisitParametersSerializer(serializers.ModelSerializer): parameter_values = VisVisitParameterValuesSerializer(many=True, required=False, allow_null=True, ) class Meta: model = VisVisitParameters fields = '__all__' def create(self, validated_data): parameter_values = validated_data.pop('parameter_values') d = VisVisitParameters.objects.create(**validated_data) vparameter_id = VisVisitParameters.objects.latest('vparameter_id') for parameter_value in parameter_values: VisVisitParameterValues.objects.create(vparameter=vparameter_id, **parameter_value) return vparameter_id Models class VisVisitParameters(models.Model): vparameter_id = models.AutoField(primary_key=True) parameter_name = models.CharField(max_length=300, blank=True, null=True) parameter_description = models.TextField(blank=True, null=True) value_type = models.CharField(choices=value_type_text, max_length=8, blank=True, null=True) class VisVisitParameterValues(models.Model): vpvalue_id = models.AutoField(primary_key=True) vparameter = models.ForeignKey('VisVisitParameters', models.DO_NOTHING, blank=False, null=False) parameter_value = models.CharField(max_length=100) -
Better way of choosing foreign key option in django admin? (without the traditional dropdown and a method which allows filtering)
Is there a better way of selecting foreign key of a model in django admin? At the moment, the selection is the traditional dropdown, however, it is not scalable. Is there a feature which enables, perhaps a pop-up windows, which allows filtering the foreign key options (by its own foreign key) and choosing? -
Trigger Django Signal from Shell
I have configured a signal to run on post_save and its working fine in Django admin and API. But when I try to update the model using mymodel.save() using django shell it does not get triggered. Is there a workaround as I have to manually update the model and call the save method in some cases. -
Unable to load Static files into my Index.html in Django
I am new to Django and I am having a challenge in importing static files into my main HTML document. Can anybody help? Below is the approach I am following My project structure looks like below. Hi2 is the project settings.py looks like below. I did all the Important settings related to Static Files # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFIELS_DIRS=[ STATIC_DIR, ] Finally imported CSS into my index.html in the below way. In the 3rd line Used {% load static %} and in 14th and 17th lines used "{% static "file location" %}". But it's not all reflecting when viewd Index.html page. 1) <!DOCTYPE html> 2) <html lang="en"> 3) {% load static %} 4) <head> 5) 6) <meta charset="utf-8"> 7) <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 8) <meta name="description" content=""> 9) <meta name="author" content=""> 10) 11) <title>Home</title> 12) 13) <!-- Bootstrap core CSS --> 14) <link href="{% static "myapp/vendor/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> 15) 16) <!-- Custom styles for this template --> 17) <link href="{% static "myapp/css/simple-sidebar.css" %}" rel="stylesheet"> 18) 19) </head> Any help is highly appreciated Thanks … -
Why django model save function does not respond?
I am trying to create a blog post model and i added a schedule filed on Django model that i can schedule my post by date and time if schedule time == now then post should be verified and display to dashboard so for this i used def save function but save function does not respond when i tried to schedule a blog post from admin panel it did not change verified = True here is code what i did so far. class Blog(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post") title = models.CharField(_("Title of blog post"), max_length=250, null=True, blank=True) header = models.CharField( _("Blog title eg. TIPS, "), max_length=250, null=True, blank=True) slug = models.SlugField(_("Slug of the title"), max_length=250, unique_for_date='publish', null=True, blank=True) photo = models.ImageField(_("Blog post main image"), default="img.png", null=True, blank=True, upload_to='users/avatar') read_time = models.TimeField( _("Blog post read time"), null=True, blank=True) category = models.ForeignKey(Category, verbose_name=_( "Blog category list"), on_delete=models.CASCADE, null=True, blank=True) publish = models.DateField() tags = TaggableManager(blank=True) description = HTMLField() views = models.IntegerField(default="0") # <- here verified = models.BooleanField( _("Approved post before push on production"), default=False) schedule = models.DateTimeField( _("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True) class Meta: verbose_name = _('blog') verbose_name_plural = _('blogs') def __str__(self): return self.title def … -
While building wheel for pdftotext, command 'gcc' failed with exit status 1
I am using Python 3.7.0, Django 3.0.4, and trying to host in Heroku. I am using windows OS and the most solution I found is on Linux. Every time I tried to push into the master of Heroku, it occurs the following error. Could anyone please help me out? ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-vu13x6kn/pdftotext/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vu13x6kn/pdftotext/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-quoxq88r remote: cwd: /tmp/pip-install-vu13x6kn/pdftotext/ remote: Complete output (14 lines): remote: /app/.heroku/python/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' remote: warnings.warn(msg) remote: running bdist_wheel remote: running build remote: running build_ext remote: building 'pdftotext' extension remote: creating build remote: creating build/temp.linux-x86_64-3.6 remote: gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPOPPLER_CPP_AT_LEAST_0_30_0=0 -I/app/.heroku/python/include/python3.6m -c pdftotext.cpp -o build/temp.linux-x86_64-3.6/pdftotext.o -Wall remote: pdftotext.cpp:3:10: fatal error: poppler/cpp/poppler-document.h: No such file or directory remote: #include <poppler/cpp/poppler-document.h> remote: ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: ---------------------------------------- remote: ERROR: Failed building wheel for pdftotext -
python open function path
Could you please help me to understand how to set the path from where the file needs to be saved. def service_area_by_region_top_category_count(self, services_in_service_area_by_region, region_name, limit): print('#### ' + region_name + ':') with open("how to give the path here?/location.txt", "a") as file_prime: file_prime.write(str('#### ' + region_name + ':')+ '\n') region_queryset = services_in_service_area_by_region[region_name] with open("how to give the path here?/location.txt", "a") as file_prime: for category in Category.objects.all().annotate( service_count=Count(Case( When(services__in=region_queryset, then=1), output_field=IntegerField(), )) ).order_by('-service_count')[:limit]: print(" - " + category.name + ": " + str(category.service_count)) file_prime.write(str(" - " + category.name + ": " + str(category.service_count))+ '\n') Thank you for the help. -
How to implement ldap authentication(without admin credentials) in django
My setup: Django-3.0, Python-3.8, django_auth_ldap I have LDAP Server (Active Directory Server) in my organization. I am building a Django Application which serves some operations for all the users. I know Django has built-in User Authentication mechanism, But it authenticates if users are present in User Model Database. But my requirement is. All user entries are in LDAP Server(Active Directory). Using proper user credentials LDAP server authenticates me. I Created a Login Page in Django 'accounts' app, 1. whenever I enter username and password from Login Page, it should Authenticate using My Organization LDAP Server. 2. After Login I have to hold the session for the logged in user for 5 active minutes. (Django auth session) I saw django_auth_ldap package gives some insight for my purpose. I have these contents in settings.py. import ldap ##Ldap settings AUTH_LDAP_SERVER_URI = "ldap://myldapserver.com" AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS : 0} AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s, OU=USERS,dc=myldapserver, dc=com" AUTH_LDAP_START_TLS = True #Register authentication backend AUTHENTICATION_BACKENDS = [ "django_auth_ldap.backend.LDAPBackend", ] Calling authenticate in views.py. from django_auth_ldap.backend import LDAPBackend def accounts_login(request): username = "" password = "" if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') auth = LDAPBackend() user = auth.authenticate(request, username=username, password=password) if user is not None: login(request, … -
How to parse this Postgresql query into Django
I have this Postgresql query: select a.code from accounts a where a.code like '0077-7575%' or '0077-7575' like a.code||'%' At django I am trying to do this: q = Accounts.objects.filter(Q(code__startswith='0077-7575') | Q('0077-7575'__startswith=code)) But, of course, it doesn't work... How can I solve this? -
Checkout Not Working in Django, Even With Test Card Details
I've been following along with a tutorial for my project and I've created a checkout page, with the relevant views, models etc being created as well. The issue I'm currently having is that my website won't accept the test card details I'm putting in and it keeps throwing the error "We were unable to take a payment with that card!". Below are the test card details I'm using. Below is the checkout view that is being used. The error message I'm getting is the error message shown in the second from bottom 'else' statement. def checkout(request): if request.method=="POST": order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price order_line_item = OrderLineItem( order = order, product = product, quantity = quantity ) order_line_item.save() try: customer = stripe.Charge.create( amount = int(total * 100), currency = "GBP", description = request.user.email, card = payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: messages.error(request, "You have successfully paid") request.session['cart'] = {} return redirect(reverse('products')) else: messages.error(request, "Unable to take payment") else: print(payment_form.errors) messages.error(request, "We were unable … -
How to get the total count of followers filter by user in Django?
I have a ManyToManyfield in Django and im trying to get the total count of users that are following a specific user. Anyone know how to make this? I've tried this code 'focount' context in views.py but is not working. Thanks! views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name='posts' paginate_by = 15 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) context['focount'] = Friend.objects.filter(current_user=self.request.user).count() return context Models.py class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner', null=True) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create(current_user=current_user) friend.users.remove(new_friend) user_posts.html <div class="followers-col-st"><span class="follower-color">{{ focount }}&nbsp;</span> -
Django running migrations after cloning project is failing
I just cloned my project from a git repository. After installing all dependencies and a virtual environment I proceeded to set up the database by running migrations as follow: python3.6 manage.py makemigrations python3.6 manage.py makemigrations api python3.6 manage.py migrate but the last command is failing: python3.6 manage.py migrate Operations to perform: Apply all migrations: account, admin, api, auth, authtoken, contenttypes, sessions, sites, socialaccount Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 394, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: users_user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/bigweld/Desktop/webdev/projects/koffeecultor-api/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line … -
Building an AJAX pagination
I am building an AJAX pagination for my Django Project. Couldn't find any decent tutorial so I started on my own, step after step, debugging with the console. But I am not an expert in JQuery but love how AJAX bring any app to the next level. I want to display a list of users favorites products and I want the user to navigate through it with AJAX. Pagination is set to five. Here is my code o far: views.py: def nav(request): data = {'saved_list': 0} if request.method=='POST': user_id = request.user sub_list = SavedProduct.objects.filter(username=user_id) paginator = Paginator(sub_list, 5) page = request.POST.get('page') saved_list = paginator.get_page(page) data['saved_list']= saved_list return JsonResponse(data) urls.py: app_name = 'register' urlpatterns = [ path('nav/', views.nav, name='nav') ] My AJAX: $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); var url = '/register/nav/'; $.ajax({ url: url, type: "POST", data:{ 'page': page, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['saved_list']) console.log('working so far'); } }); }); My AJAX is not complete because I debug it after each new step. Now when I run my code, I have this error: TypeError: Object of type Page is not JSON serializable. What I understand is that I can't send data['saved_list'] back to AJAX. … -
Tools required for creating a website to verify authenticity of social media posts
I'm working on a project where users can report social media posts they feel are spreading fake information on a website. I have no experience with web development and even for machine learning, I've only completed Andrew Ng's course on Coursera. I've learnt some basic html/css and some very basic django. This project is actually more of a research-oriented one and I'm not expected to actually create a working website. But I really want to create one even if it is barely functional. I have come up with what I believe is a concrete work plan, and I am looking for the tools that could help me realize the plan in about 10 days. What I intend to do: The user will be asked to put up the link to the post they feel is fake, along with some additional information such as the place, time etc mentioned in the post, and a single line summary of the post(not exceeding a certain number of characters). So for eg. if the post is about "Extension of Lockdown till Aug 1st in India", they would post the link along with the "place and time period mentioned" as "India" and "Aug 1st", "Summary": … -
Inline Editing of Textarea with jquery.inline-edit.js – Get the id and save
I am looking for a simple way to implement inline editing in a table (with Django). I did not test stuff like Django-Front or django-inlineedit so far. I already found out, that not all simple solutions work for me. jqInlineEdit and inline-edit.jquery.js do work only with unique selectors, as I described here. With jQuery.editable (jquery.inline-edit.js), I do not have these problems, but I do not know how to get the id and save the data. <div id="remark4" class="remark">Test #4</div> <div id="remark5" class="remark">Test #5</div> <div id="remark6" class="remark">Test #6</div> <script src="file:jquery.inline-edit.js"></script> <script> $('.remark').inlineEdit('click', { // use textarea instead of input field type: 'textarea', // attributes for input field or textarea attributes: { id: 'remark14755', class: 'input-class-1 input-class-2 input-class-3', style: 'background:#ffe;' } }); </script> How can I get const c_id = $(this).attr("data-cid"); and let's say alert(c_id + content) running after the content in the form has changed? I did not found a documentation or an example for that and trial and error was not successful so far. -
Local -> Github working | Github -> Heroku not working
I have a Django application which is present in my local system. As I want to ignore db.sqlite3 files while transferring the repository, I have put the following in .gitignore db.sqlite3 I push it to Github using: git push origin master When I do this, the updated db.sqlite3 from local system is NOT transferred to git. As the next step, I need to transfer the files from local system to Heroku using: git push heroku master However, it seems that the file from Github is copied to heroku, which is weird. Perhaps my understanding of the git push heroku master is incorrect. Deployment method is using heroku cli To check this weird way of working : I added couple of entries in db.sqlite3 in my local system I made a small change to the code in my local system I made new entries in the Django application which is deployed to heroku I pushed the application to Github using git push origin master and checked the timestamp on db.sqlite3 in git and it wasn't changed - I downloaded the db.sqlite3 from git and checked, the new entries that I made to the local system weren't there. This is good. I … -
django email authentication with mysqll
my code it not working it never log me but runs without errors i am using mysql database i tried alot to solve it but i wasnt able to solve it as i am new to python web programming please help. views.py from django.shortcuts import render from django.contrib.auth import authenticate from Play.models import user from django.contrib.auth.models import User from django.contrib.auth.models import auth from django.shortcuts import redirect from django.shortcuts import HttpResponse from django.contrib.auth.hashers import make_password def JoinRequest(request): if request.method == 'POST': fullname = request.POST['fullname'] email = request.POST['email'] phone = request.POST['phone'] password = request.POST['password'] cpassword = request.POST['cpassword'] #encpass = make_password(password) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip if password != cpassword: return HttpResponse('Password Not Matching To Confirm Password Value..') else: senddata = user(fullname=fullname, email=email, phone=phone, password=password , ipaddress=get_client_ip(request)) senddata.save() return HttpResponse('') def Join_View(request): return render(request, 'Join.html', {}) def login_view(request): return render(request, 'Login.html', {}) def LoginREQUEST(request): if request.method == 'POST': username = request.POST['email'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponse('DONE') else: return HttpResponse("NONE") EmailAuthentication.py from django.contrib.auth import get_user_model from django.http import HttpResponse from django.contrib.auth.backends import ModelBackend as _ModelBackend User = get_user_model() class EmailOrUsernameModelBackend(_ModelBackend): """ Authenticate … -
Facing Multi Dict Key Error while integrating facebook api endpoint
I'm trying to include facebook messenger in my project. My requirements is just to send message to the facebook page when ever any user submit a form. But before that, i want to just test facebook api endpoint. But unfortunately I'm facing error. views.py class YoMamaBotView(generic.View): def get(self, request, *args, **kwargs): if self.request.GET['hub.verify_token'] == '2318934571': return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') and here is callback settings -
Django: create a database that allow user to create character templates and then to create characters based on those
I am currently re-learning computer programming, 5 years after completing my University related courses, and I lost almost all of my knowledge and I am back to a beginner's level. I am trying to learn how to do a website using Python (3.8.3) and Django (2, 2, 13, 'final', 0), with the default SQLite database. My long term goal would be to create a personnel Website with multiple apps (e.g. Forum, Blog about multiple theme...) and my priority is focused towards creating a Roleplay management app, but I'm having trouble understanding how to create my database or what to use. I want the following requirements : A table containing Users personnals information Each User can create « Worlds » where they are gamemasters ; They can create multiple worlds A gamemaster is able to create a character template, which allows to define min, max, default and distributable stats, spells format, inventory size and objects A gamemaster will be able to create items that aren't in any inventories and to give them later When creating a new World, the gamemaster can link multiple character templates to the world ; Those stats can be separated into groups (e.g. main stats and secondary … -
Django redirect doesn't work in class based view
I have a class based view which i am checking some conditions and redirecting to another page, i see the GET request to that page in the terminal and it returns 200, but it doesn't redirect to the page: class CheckoutFinalView(CartOrderMixin, View): def post(self, request, *args, **kwargs): return redirect("carts:success") I tried return HttpResponseRedirect(reverse('carts:success')) , too. But it doesn't work, too. -
Django user settings model
would it be wise to create a custom user model if I wish for settings to be tied to the user (AbstractUser would be used)? the other seemingly simpler option would be to create a Settings model in my main app and tie it to the user with a foreign key. some examples would be private profile, hidden in search, profile pictures