Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django The login is successful, but the user information cannot be read when the page is changed?
oh,f**k ,I solved this problem all afternoon State of mind explosion,I think I'm going crazy. This mistake hasn't been met before, but it is today. ok,but,i don't know how to solve. i login my blogs,flush my view.py login: class LoginView(View): #todo login def get(self,request): is_active = "login" return render(request, 'login.html', {"is_active": is_active}) # login def post(self,request): loginform= LoginForm(request.POST) if loginform.is_valid(): email = request.POST.get('email', '') pass_word = request.POST.get('password', '') user = myauthenticate(request,email,pass_word) if user: login(request,user) return render(request,'home.html',{'user':user}) else: return render(request,'login.html',{'msg':"user account or password error"}) else: return render(request,'login.html',{'msg':LoginForm.errors}) my base.html {% if request.user.is_authenticated %} <li style="float:right;"><a href="{% url 'users:logout' %}" class="glyphicon glyphicon-off" >注销</a></li> <li class="{% ifequal is_active 'login' %}active{% endifequal %}" style="float:right;"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <img src="{{ MEDIA_URL }}{{ user.image }}" width="20" height="20"> {{ user.username }} <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="{% url 'users:user_info' user.username %}">用户中心</a></li> <li><a href="#">我的粉丝</a></li> <li><a href="#">我的收藏</a></li> <li><a href="#">我的关注</a></li> <li><a href="{% url 'blog:myblogs' %}">我的博客</a></li> </ul> </li> {% else %} <li class="{% ifequal is_active 'login' %}active{% endifequal %}" style="float:right;"><a href="{% url 'users:login' %}" class="glyphicon glyphicon-user">登录/注册</a></li> {% endif %} in my settings,my middleware is open: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'quwen_users', "pythons", 'blog', 'captcha', "pure_pagination" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Setting a field as primary key in django model
I am using django 2.2 with python 3.6.8 on ubuntu 18.04. I created a model like below : @reversion.register() class Courses(BaseModel): coursecode = models.AutoField(primary_key=True, verbose_name=_("Kurs Kodu")) coursename = models.ForeignKey(CourseNames, on_delete=models.PROTECT, verbose_name=_("Kurs")) teacher = models.ManyToManyField(Staff, blank=True, related_name='teacher', verbose_name=_("Öğretmenler")) courseroom = models.ForeignKey(CourseRoom, on_delete=models.PROTECT, verbose_name=_("Kurs Yeri")) credit = models.DecimalField(verbose_name=_("Kredi"), default=0.0, max_digits=3, decimal_places=1) student = models.ManyToManyField(Student, blank=True, verbose_name=_("Öğrenci")) createdon = models.DateField(verbose_name=_("Oluşturulma Tarihi")) createdby = models.ForeignKey(Staff, on_delete=models.PROTECT, related_name='creatorstaff', verbose_name=_("Kaydeden Personel")) coursenotes = models.TextField(null=True, blank=True, verbose_name=_("Kurs Notları")) class Meta: permissions = ( ("list_course", _("List Courses")), ) ordering = ['coursename'] def __str__(self): return "%s - %s" % (self.coursename, self.courseroom, self.teacher) When i try to makemigrations i get below error : project1app.Courses: (models.E026) The model cannot have more than one field with 'primary_key=True'. As i set a primarykey field django should not set automatic primarykey and use mine. There is only one field with primarykey. But giving below error. -
What is the lifetime of a Django WSGI application object when served using Gunicorn or WSGI?
I'm using Django with Gunicorn. Since I don't know much about the Gunicorn internals, so I'm wondering what is the lifetime of an WSGI application object. Is it forever, or created for every request, or lives as long as the worker lives? Similarly in uWSGI seems to invoke an application callable for one request as per this. So, does this mean that application objects lives for a while (and uWSGI invokes the same object for every request)? This might be stupid but I'm trying to figure this out while trying to cache some stuff (let's say in some global or file level variables) at the application level to avoid cache (Redis/Memcached) or db calls. I'm wondering if application object lives for at least some time, then may be a good thing to cache data at regular intervals without making cache requests (after all it's a N/W request) as well. Please help me understand this. -
TypeError: Object of type Decimal is not JSON serializable during Django data migration
I added a postgres JsonField in my model, and created data migration for it. new_column = pg_fields.JSONField(default=dict, encoder=DjangoJSONEncoder) Same logic is used for future data(in save() of model) and for historic data(data migration). This is the format of data I am trying to save data = { 'premium': obj.amount * obj.persons, } proposal.new_column = data proposal.save() Here, obj is the instance of some other model, and amount is the DecimalField of that model. The logic runs fine in save() method of model class. But on running data migration, I am getting this error TypeError: Object of type Decimal is not JSON serializable Stacktrace Traceback (most recent call last): File "./manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/simarpreet/Envs/j/lib/python3.7/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 "/home/simarpreet/Envs/j/lib/python3.7/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 "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File … -
Send task to specific celery worker
I'm building a web application (Using Python/Django) that is hosted on two machines connected to a load balancer. I have a central storage server, and I have a central Redis server, single celery beat, and two celery workers on each hosting machine. I receive files from an API endpoint (on any of the hosting machines) and then schedule a task to copy to the storage server. The problem is that the task is scheduled using: task.delay(args) and then any worker can receive it, while the received files exist only on one of the 2 machines, and have to be copied from it. I tried finding if there's a unique id for the worker that I can assign the task to but didn't find any help in the docs. Any solution to this ? Given that the number of hosting machines can scale to more than 2. -
Removing a css blur affect after user authentication - django
I am currently working on a project with Django. The home / main page of the project is locked behind a login form. I have the background blurred with the login form on top of the blur and I am looking to remove that form and blur when the user logs in with a valid account. Is this possible and where should I look, googling has turned up nothing. the blur is applied via css. Also is it possible to stop the user from interacting with the elements behind the blur until they log in? thank you -
KeyError: 'REDIS_URL' Error when running server
I have installed all the requirements for a project successfully. However, when trying to run python manage.py runserver I get the error: KeyError: 'REDIS_URL' How could I solve this? I'm struggling in finding a solution. -
How to build GraphQL schema for reverse lookup from Content Type model to usual model?
I have 4 types of profiles. Some fields are the same, some are different. Each profile has its own url, so I use ContentType as a central place of mappring urls<->profiles. # profiles/models.py class Sport(models.Model): pass class ProfileAbstract(models.Model): pass class ProfileOrganization(ProfileAbstract): pass class ProfilePlace(ProfileAbstract): pass class ProfileTeam(ProfileAbstract): pass class ProfileUser(ProfileAbstract): pass class ProfileURL(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=30) # Url content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) # CharField because I use UUID content_object = GenericForeignKey('content_type', 'object_id') P.S. Example of direct lookup can be found in this github issue. -
Calling a modal based on logic from views.py in Django?
I have a page with a form that is used to track entry/leave times. Currently, entries with errors (missing enter or exit) get flagged from views.py. I created a modal based on some templates I was given, but I have no idea how to call it from views.py. Basically, after a submission gets flagged with an 'N', the modal would need to appear, asking the user to give a value. Right now the modal just says "Hi" because I'm trying to get it to appear first, before diving into the functionality of it. Below is my views.py, with a comment of where the modal call would need to happen. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) # If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N' if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).count() > 1: first = EmployeeWorkAreaLog.objects.filter(employee_number=emp_num, time_out__isnull=True).order_by('-time_in').first() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(time_out__isnull=True))).exclude(pk=first.pk).update(time_exceptions='N') # Here's where the modal would need to be called because the record was flagged … -
Django gis query on annotated spatial filed
I am currently building a web app based on GeoDjango and I want to check if a number of points lie within a multipolygon. To form the multipolygon, I check which areas are selected and then aggregate them into one multipolygon with the following query: area = Area.objects.filter(id__in = area_ids).aggregate(area=Union('geom'))['area'] print(area) SRID=4326;MULTIPOLYGON (((5.014146 52.371687, 5.013973 52.371632, 5.013238 52.37166, 5.012505 52.372437, 5.01294 52.372787, 5.012977 52.373, 5.013142 52.373072, 5.014488 52.373032, 5.014564 52.372957, 5.014701 52.37272, 5.01461 52.372181, 5.014372 52.371786, 5.014146 52.371687)), ((5.014054 52.367988, 5.014448 52.368027, 5.014532 52.367978, 5.014079 52.367899, 5.014033 52.367822, 5.01398 52.367882, 5.012914 52.367781, 5.013032 52.367372, 5.012751 52.367294, 5.00198 52.366278, 5.001809 52.366739, 5.000036 52.366614, 5.000086 52.366682, 5.013941 52.367968, 5.013987 52.36805, 5.014054 52.367988)), ((4.997837 52.350827, 4.997581 52.350302, 4.996731 52.35072, 4.996493 52.350708, 4.991906 52.352949, 4.989279 52.354708, 4.990234 52.354938, 4.993064 52.353655, 4.997837 52.350827)), ((5.021518 52.384118, 5.018382 52.380388, 5.01628 52.377323, 5.014382 52.37417, 5.014296 52.374171, 5.014094 52.37425, 5.014288 52.374504, 5.014268 52.374785, 5.013763 52.374812, 5.013434 52.375018, 5.013673 52.375082, 5.01377 52.375441, 5.014177 52.375737, 5.014467 52.375531, 5.014801 52.375961, 5.014822 52.376498, 5.014295 52.376588, 5.014194 52.376725, 5.014413 52.377446, 5.015047 52.378, 5.015372 52.378016, 5.015413 52.377633, 5.01574 52.377412, 5.015965 52.377466, 5.015873 52.378071, 5.016008 52.378355, 5.015993 52.378669, 5.016702 52.380502, 5.016514 52.380922, 5.016989 52.381336, 5.017121 52.381644, 5.017756 52.381984, 5.017666 52.382471, 5.018341 52.383453, 5.018662 52.383813, 5.018769 52.383778, … -
Creating PDF reports in Django backend or frontend?
I'm currently trying to create reports and was wondering what the best practices around generating PDF reports are. Should I create them in the backend (using elasticsearch for querying and aggregating the data) or rather send the data to the frontend and generate them there? -
Django migrate error :TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'
I'm having issues with Django . I get the error i have tried setting a default but it still causes the error here's my files. Please explain the solution thanks Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. STATUS = [ (0, "Draft"), (1, "Publish") ] class Posts(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') content = models.TextField() created_on = models.DateTimeField(db_index=True,auto_now=True) status = models.IntegerField(choices=STATUS, default=0) it gives the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' -
How to fix css of form in django?
Hi Everyone How To Fix this error you can see in image i don't want this border but i'm getting this border again and again error: i don't want that back border how to fix that? I'm Using Bootstarp forms.py class user_buy_form(forms.ModelForm): Terms_of_trade = forms.CharField(widget=forms.Textarea) class Meta: model = user_buy widgets = { 'Currency':forms.Select(attrs={'class':'form-control currency','label':''}), 'Bank_Name':forms.TextInput(attrs={'class':'form-control Bank-Name'}), 'Min_transaction_limit':forms.TextInput(attrs={'class':'form-control Min-transaction-limit'}), 'Max_transaction_limit':forms.TextInput(attrs={'class':'form-control Max-transaction-limit'}), 'Terms_of_trade':forms.TextInput(attrs={'class':'form-control Terms-of-trade'}), 'payment_method':forms.TextInput(attrs={'class':'form-control payment-method'}), 'price':forms.TextInput(attrs={'class':'form-control price'}), 'Location':forms.TextInput(attrs={'class':'form-control Location'}), 'Trade_limits':forms.TextInput(attrs={'class':'form-control Trade-limits'}), } fields = '__all__' exclude = ('users',) Here is my html file: <form class="form-control" method="POST"> {% csrf_token %} {{usr_buy.as_p }} <input type="submit" class="btn btn-primary" value="Submit"> </form> Any Help Will Be Appreciated Thanks! -
Django upload image to AWS is too slow
I saw this question a few times but no one got a clear answer, I hope someone can help me. The problem is: Upload images takes too long in my website. Example: 2.4mb photo took 13 seconds to load with a good network. Slow networks takes a lot more. Is is possible to speed it up somehow? I use Django 2.1 PostgreSQL Boto3 django-storages 1.7.1 Amazon AWS My code: As soon as the user selected an image from input, it calls: function UploadPicture(picture) { let formData = new FormData(); formData.append('file', $(picture)[0].files[0]); $.ajax({ type: 'POST', url: "../save_image", data: formData, cache: false, contentType: false, processData: false, success:function(data){ console.log("success"); }, error: function(data){ console.log("error"); } }); } Then it calls the django view: def upload_boat_picture(request): if "file" in request.FILES: added_img = ImagesTable.objects.create(user=request.user, image=request.FILES['file']) return HttpResponse(str(added_img.pk)) Thanks! -
Django Rest Framework using generic Class Based View is not render "Create Form" when Permission IsAuthenticated set
I pretty new I Django ReST Framework, I have created Token Authentication on my settings.py My views.py was configured using generic Class Based View. I found that when no authentication configured on settings.py, the List Class Based View will render JSON List and Create Form properly. But after I configured the Authentication, it only shows the list, but no Create Form It is same on Detail View and Update Most of authentication tutorial will bring to Function Based View using View Decorator My Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ] } My Views.py: class ProductListView(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] -
How do i solve UNIQUE constraint failed: auth_user.username problem in Django
I am brand new to Django. I made a register form. One time out of two, when i try to register a new user i have an exception "auth_user.username" it seems there is no rule, it can works many times in a row and with new user registration i have the error! Here is my form.py from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.contrib.auth.models import User from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin from django import forms class CustomUserCreationForm(PopRequestMixin, CreateUpdateAjaxMixin, UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("the given email is already registered") return self.cleaned_data['email'] ''' views.py enter code here from django.urls import reverse_lazy from bootstrap_modal_forms.generic import BSModalCreateView,BSModalLoginView from .forms import CustomUserCreationForm,CustomAuthenticationForm class SignUpView(BSModalCreateView): form_class = CustomUserCreationForm template_name = 'signup.html' success_message = 'Success: Sign up succeeded. You can now Log in.' success_url = reverse_lazy('index') signup.html enter code here {% load widget_tweaks %} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384- q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> body data-spy="scroll" data-target=".site-navbar-target" data-offset="300"> <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Register</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="{% if form.non_field_errors %}invalid{% endif %} mb-2"> {% for error in form.non_field_errors %} {{ … -
Django {% crispy %} tag vs {{ form|crispy }} what's the difference?
I'm trying to wrap my head around what crispy forms is doing in the background. When I put the tag {% crispy form %} into my HTML block, my form layouts and crispy bootstrap formatting (from crispy_forms.layout import Layout, Row, Column and from crispy_forms.bootstrap import AppendedText, InlineRadios ) is rendered properly but the submit button does not post to my model or redirect the user. When I put the tag {{ form|crispy }} into my HTML block, my form layout is not rendered but the submit button does work and posts the user input to my model. I'm trying to figure out how to get both a nice layout and have a functional HTML form. -
Django-background-tasks windows bug: process_task "hangs" after second check
I have noticed that on windows when I run process_tasks it tends to hang after it's second loop of checking for new tasks to process. I am not sure what is causing this issue. Context: I create custom tasks that will check a set amount of external urls/endpoints to see if the service/website/api is accessible and then send a message to a redis-server which then gets pulled client side for a "live" update of certain applications status. Example: @background def check_endpoint(endpoint_lst): status_data = {} for endpoint in endpoint_lst: status_data[endpoint] = check_status(endpoint) sync.async_to_sync(channel_layer.group_send)( str("notify"), # Channel Name, Should always be string { "type": "notify", # Custom Function written in the consumers.py "status_data": status_data, }, } time.sleep(60 * 10) check_endpoint(endpoint_lst) I call it's self again at the end to create a new task, I found that if I use the decorator to repeat my tasks it locks pid all the time. I am connected to a mssql server if this helps to know about too. and I have 24 tasks to process. ASYNC is set to True and thread amount set to 4 in settings.py I have been stuck with this issue for awhile now and could really use some help. -
Problem upgrading django doesn't show latest version
pip install --upgrade django==2.2.7 Collecting django==2.2.7 Could not find a version that satisfies the requirement django==2.2.7 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26) No matching distribution found for django==2.2.7 I am having problem upgrading -
How to acsess the session variable in forms.py outside of Formclass in django
I am new to django I need to create dropdown in form and the dropdown needs to update with values from the database based on some lookup . The look up will change based on the request Here is the code from django import forms from .models import Configuration from django.db.models import Q from configuration.models import Configuration def getschema(): x=[] #change the hardcoded 8 here allschema = Configuration.objects.filter(project_id = request.session['project_id]) for schema in allschema: print(schema.schema_name) x.append((schema.schema_name,schema.schema_name)) return x class TestCaseForm(forms.Form): TestcaseName = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Test Case Name", "name" : "testcasename", })) TestcaseDescription = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Test Case Description", "name" : "testcasedesc", })) SourceSchema= forms.CharField(label='Select Source Schema', widget=forms.Select(choices=getschema(),attrs={"name": "srcschema"})) TargetSchema= forms.CharField(label='Select Target Schema', widget=forms.Select(choices=getschema(),attrs={"name": "srcschema"})) SourceQuery = forms.CharField(widget=forms.Textarea( attrs={ "rows":4, "cols":50, "class": "form-control", "placeholder": "Source query", "name": "sourcequery", })) TargetQuery = forms.CharField(widget=forms.Textarea( attrs={ "rows":4, "cols":50, "class": "form-control", "placeholder": "Target query", "name": "targetquery", })) def __init__(self,*args,**kwargs): self.request = kwargs.pop('request',None) super(TestCaseForm,self).__init__(*args,**kwargs) def clean(self): print(self.request.user.id) My question is how to use the session object inside my getschema() method -
Passing html to index.html template from view in Django
This is my code in get_rand.py context = {'index': "<div> sadsadsadasd </div>"} render(request, "index.html", context) This is my code in index.html: {{index}} No text is showing up when i try loading it.... -
Django DRF: How to show filtered data
I am following a todo tutorial. I have TodoItem's and TodoList and I get them when I go to url `http://localhost:8000/api/todos/ . I want to return only completed todoItem's from api. How can I do that models.py class TodoList(models.Model): name = models.CharField(max_length=200, default="blank title") is_completed = models.BooleanField(default=False) completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) created_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) #owner = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: verbose_name = "Todo List" verbose_name_plural = "Todo Lists" ordering = ["name","created_at", "is_completed", ] def __str__(self): return self.name class TodoItem(models.Model): name = models.CharField(max_length=200, default="blank title") todo_list = models.ForeignKey(TodoList, on_delete=models.CASCADE, null=True) description = models.TextField(max_length=200, default="Blank text") is_completed = models.BooleanField(default=False) completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) created_at = models.DateTimeField(default=datetime.now(), null=True, blank=True) deadline = models.DateTimeField(default=datetime.now(), null=True, blank=True) class Meta: verbose_name = "Todo List" verbose_name_plural = "Todo Lists" ordering = ["created_at", "is_completed","deadline","name" ] def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import * class TodoItemSerializer(serializers.ModelSerializer): class Meta: model = TodoItem fields = '__all__' class TodoListSerializer(serializers.ModelSerializer): class Meta: model = TodoList fields = '__all__' views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import * from .models import * class TodoItemView(viewsets.ModelViewSet): serializer_class = TodoItemSerializer queryset = TodoItem.objects.all() class TodoListView(viewsets.ModelViewSet): serializer_class = TodoListSerializer queryset = TodoList.objects.all() And this is the … -
Use python variables in a external js file. Django
I'm working in a Django project and I would like to have it tidy. Thus I decided (among other things) don't have de css styles and js scripts inside the html templates. With the css styles I have no problems, I have created a css folder inside the static folder and I save all my css files inside, it works perfectly. My problem comes when I want to do the same with the js files that works with the python variables that comes from the views.py. Because it don't recognise they. How can I import this variables to the js external files? Now I have this, but it don't works. main.html {% load static %} <!DOCTYPE html> <html lang="es"> <head> <title> {% block title%}{% endblock%} </title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static "/css/main.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "/css/data.css" %}"> </head> <body> <h1> WELCOME HOME </h1> <p>{{Data}}</p> /* This script has to be in a external js file. HERE WORKS <script> alert('{{Data}}'); </script>*/ {% block content %}{% endblock%} <script type="text/javascript" src="{% static "/js/token.js" %}"></script> </body> </html> data.js alert('{{Data}}') //alert({{Data}}) ERROR If the alert has no python variables like alert("Hello world") it works well, but when I pass a … -
How to get django-all auth to pass data to custom user model?
I'm making a site in Django using django-allauth for authentication. I've created a custom user class in accounts.models to add a custom field, FavouriteTeam. The issue I have is that the form renders fine and submits formdata for fav_team fine (as inspected in Chrome dev tools) but the fav_team entry doesn't get stored to user.FavouriteTeam and I can't figure out why. I can go into the Django shell, import my User class from accounts.models, query for a user, add a .FavouriteTeam, and save just fine. It's just that the form doesn't seem to save the data into the new User instance for some reason. I'm guessing it's due to the way django-allauth interacts with custom user models but I can't figure it out for the life of me. I've seen some similar posts but none have a situation like this or have a solution that seems to work for me. Any ideas? accounts.models: - from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): FavouriteTeam = models.ForeignKey('predictor.Team', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.email accounts.forms: - from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import User from allauth.account.forms import SignupForm from predictor.models import Team from django.contrib.auth import … -
How to upload files onto arbitrary directories in Django?
I'm developing a file manager with Django. I'm using SFTP file server and django-storage package for managing files. Well I developed some Apis for users to create and modify directories under their-own root-directory (which is abstract to the users) so far. Now I want to able users to upload their files onto their sub-directories or move files between those sub-directories but I don't know how?! This is the model I'm using for file management: def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(format(instance.owner.id, '010d'), filename) class UploadedFile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=150) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) file = models.FileField(upload_to=user_directory_path) As you can see, currently files will be uploaded to <server-root>/user_<10digit-userid>/ directory. Thanks in advance.