Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Optional URL for taggit Django
I'am using django-taggit in my project, to put tags on items. So i watched this tutorial to use the tags in class based views. I want to show all tags on top, and on click on the tags I want to show all items with the tag, and i've been using parameters in the url, to search for the items. But i want this parameter to be optional, so the user doesn't need to give a tag in the url. Is this possible? This is my URL so far: path('items/', views.ItemsView.as_view(), name='items'), -
Convert raw sql to django query
How can I convert this raw sql to django query?? knowledges.raw( ''' SELECT KnowledgeManagement_tblknowledge.KnowledgeCode,KnowledgeManagement_tblknowledge.KnowledgeTitle,KnowledgeManagement_tblknowledge.CreateDate,KnowledgeManagement_tblknowledge.CreatorUserID_id FROM KnowledgeManagement_tblknowledge LEFT JOIN KnowledgeManagement_tblusedknowledge ON KnowledgeManagement_tblknowledge.KnowledgeCode = KnowledgeManagement_tblusedknowledge.knowledge_id where register_status = 7 or register_status = 9 and Status = 1 Group by KnowledgeManagement_tblknowledge.KnowledgeCode order by count( KnowledgeManagement_tblusedknowledge.id) desc; ''' ) -
How to regroup entries in Django by model field (More complex query)?
First i'm not an exeperienced developer in Django, i use Django 4.0.6 on windows 10 and python 3.8.9 in a virtual environment. I need help with my query in Django: first here's my model: from django.db import models class MyWords(models.Model): WordText=models.CharField(max_length=1000, unique=True) WordStatus=models.IntegerField() WordType=models.CharField(max_length=30) and i have this sqllite database table with the following entries as example: db.sqlite3 MyWords Table: WordText WordStatus WordType Dog 0 Animal Cat 1 Animal Car 4 Object Lion 1 Animal Computer 4 Inanimate Object Stone 5 Inanimate Object Child 4 Human What i want to do is to get this info back this way: data == [ {'WordType':'Object', 'WordStatus':4,'WordText':'Car'}, {'WordType':'Animal', 'WordStatus':[0,1,1], 'WordText':'Dog','Cat','Lion'}, {'WordType':'Inanimate Object', 'WordStatus':[4,5], 'WordText':'Computer','Stone'}, {'WordType':'Human', 'WordStatus':4, 'WordText':'Human'} ] Essentially i want to regroup/categorize the entries by WordType so i can access them more easily. Is this possible in Django ORM? If yes, how? I first thought using something like a values_list with WordType as argument followed by a distinct and annotate, but i'm stucked. Something like this: data =MyWords.objects.all().values_list('WordType').distinct().annotate(WordStatus=?).annotate(WordText=?) I don't know if it's correct because i don't know what to replace the question marks with. I don't know if i'm on the correct path. So can anyone guide me please? N.B: I … -
Django Kubernetes Ingress CSRF Cookie not sent
Asking this question here because It's been a couple of days and I can't find anything useful. Problem: I have an app deployed to a Kubernetes cluster running on AWS EKS with a custom docker image on AWS ECR. The app works fine with GET requests but not with POST ones. The error given is Errore 403 forbidden CSRF Token not sent. Django version is 2.2.24 on DRF 3.11.2. I already added CSRF_TRUSTED_ORIGINS in settings.py, nothing changed. The ingress I'm using is AWS's Application Load Balancer set like this: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django labels: name: django annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip alb.ingress.kubernetes.io/backend-protocol: HTTP alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80}]' alb.ingress.kubernetes.io/group.name: "alta" alb.ingress.kubernetes.io/group.order: "2" alb.ingress.kubernetes.io/healthcheck-protocol: HTTP alb.ingress.kubernetes.io/healthcheck-port: traffic-port alb.ingress.kubernetes.io/healthcheck-path: /v1/app alb.ingress.kubernetes.io/healthcheck-interval-seconds: "15" alb.ingress.kubernetes.io/healthcheck-timeout-seconds: "5" alb.ingress.kubernetes.io/success-codes: "200" alb.ingress.kubernetes.io/healthy-threshold-count: "2" alb.ingress.kubernetes.io/unhealthy-threshold-count: "2" spec: ingressClassName: alb rules: - http: paths: - pathType: Prefix path: / backend: service: name: djangoapp-cluster-ip port: number: 80 Any help is much appreciated. -
Django - remove/hide labels for checkboxes
I would have thought this would be pretty simple but I have plugged away at this for some time and I can't figure it out. I have a multiple choice checkbox in a model form which is in a formset. All I want to do is remove the labels from the checkboxes. I can easily remove the label from the field but I can't figure out how to remove the labels from the checkboxes. I am trying to convert the display of the form to a grid. From this: To this: Here's my form code: class ResourceEditAddForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.portfolio = kwargs.pop('portfolio') super(ResourceEditAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields["portfolio"].initial = self.portfolio self.fields["portfolio"].required = False self.fields["skills"].queryset = self.portfolio.getSkills() class Meta: model = Resource fields = ['portfolio', 'name', 'skills', 'pct_availability', 'cost_per_day', 'email', 'timezone', 'update_request_time', 'calendar', 'start_date', 'end_date'] widgets = { 'portfolio': forms.HiddenInput(), 'start_date': DateInput(), 'end_date': DateInput(), 'update_request_time': TimeInput(), 'skills': forms.CheckboxSelectMultiple(), } ResourceEditAddFormSet = modelformset_factory( Resource, form=ResourceEditAddForm, extra=0 ) I could build a manual form to achieve this but I want to keep using model forms as there's a few fields other than skills which are managed fine by the form. If anyone can tell me how to … -
Serialize nested JSON to Django models
how can I create a nested structure from a nested JSON? I want my Hobby to have a ForeignKey to the Profile. It cant be that hard, but I really dont understand the error. It even creates the objects and saves them in my database but still says it does not find the field. I Get the following error with my code: AttributeError: Got AttributeError when attempting to get a value for field `description` on serializer `HobbySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py: class HobbySerializer(serializers.ModelSerializer): class Meta: model = Hobby fields = ["name", "description"] class ProfileSerializer(serializers.ModelSerializer): user_hobby23 = HobbySerializer(many=False) class Meta: model = Profile fields = ["testfield1", "display_name", "mobile", "address", "email", "dob", "user_hobby23"] def create(self, validated_data): user_hobby_data = validated_data.pop('user_hobby23') profile_instance = Profile.objects.create(**validated_data) Hobby.objects.create(user=profile_instance, **user_hobby_data) return profile_instance models.py: class Profile(models.Model): display_name = models.CharField(max_length=30) mobile = models.IntegerField() address = models.TextField() email = models.EmailField() dob = models.DateField() photo=models.FileField(upload_to='profile/',null=True,blank=True) status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) testfield1 = models.TextField(null=True) class Hobby(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='user_hobby23',null=True) name = models.CharField(max_length=30) description = models.TextField() status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class … -
How to call model method in ajax through views_api and assign the value to table data in DRF?
I am trying to understand the Django Rest Framework. As a beginner here, what I am trying is to call a method from a Model and update the value in the template. I am trying it from views_api.py with an ajax call. I was able to get other values, but I couldn't get three values. Here is what I have so far. reviews/models.py class Review(TimeStampedModel): project = models.ForeignKey('projects.Project', on_delete=models.CASCADE, related_name='reviews') fiscal_year = models.PositiveIntegerField(null=True, blank=True, db_index=True) fiscal_month = models.PositiveIntegerField(null=True, blank=True, db_index=True) has_validation = models.BooleanField('Has PFK', default=False) review_date = models.DateField(help_text='Date of the PFK', db_index=True) wp_validation_deadline = models.DateTimeField(blank=True, null=True, help_text='Deadline to validate WP') cutoff_date = models.DateTimeField(db_index=True, help_text='Up to when actuals are considered (date after accruals were entered)') fct_n_amount = models.DecimalField('FCT n amount', decimal_places=2, max_digits=12, null=True, blank=True) actuals_amount = models.DecimalField('Actual revenue traded', decimal_places=2, max_digits=12, null=True, blank=True, help_text='Cost to date (from monthly projectsales.xlsx)') events_amount = models.DecimalField('Total Events', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_real_amount = models.DecimalField('Total Risks - Most Likely', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_max_amount = models.DecimalField('Total Risks - Maximum', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') opportunities_amount = models.DecimalField('Total Opportunities', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In … -
Signature drawing for the form
For my application with Django, I want to make a signature drawing field after entering the necessary information in the form field. When I want to save and edit this form later, the signature drawn in that signature drawing place needs to be displayed again. I'm new to this and I have no idea how to do it, can you help with this? -
How to generate auto generate unique serial number by date and also It will be generate serial vise after delete in django
I have to generate serial number like TES-0922-1,TES-0922-2 and so on.... here TES is (company_lable) 0922 is (month and year) 1,2 is (serial number) I wish to generate unique number by date . If today is month 9 and year 22 and I am generating new data of this month then my serial number will be TES-0922-01. Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03 and If I am deleting TES-0922-01 from them. afterwards when I creating new data my serial number will be TES-0922-04 Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03,TES-0922-04 and If I am deleting TES-0922-01, TES-0922-04 from them. afterwards when I creating new data my serial number will be TES-0922-04 Note : I am saving that data in the database and handling them by django queryset. What I did is mentioned below but Its not working properly. Because I am counting my data by django queryset. views.py def sales_invoice(request): current_time = datetime.datetime.now() latest_year = current_time.year year=str(latest_year)[-2:] latest_month = current_time.month month="%02d" % (latest_month) company_label= Company_Setup.objects.get(id=request.session['company_id']) existing_label=Sales_Invoice.objects.filter(company=company_label).all() if not existing_label: gen_invoice_number=f"{company_label}-{month}{year}-1" else: total_sales = Sales_Invoice.objects.filter(company=company_label).all().count() + 1 gen_invoice_number=f"{company_label}-{month}{year}-{total_sales}" -
Difference between request.user vs. get_user(request) in Django?
I noticed there are two ways to get a user object from request (assuming user is already logged in and the session is valid): user = request.user user = get_user(request) where get_user() is imported from django.contrib.auth. What's the difference? get_user() seems to do a lot of validation for request session. Which is better? -
Several properties with the same type Django
I have two models class Manager(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) #executer = models.ManyToManyField(Manager) deadline = models.DateTimeField(null=True, blank=True) So there is logic I want Model Project to has several managers as executers but not all of them how can i do it? so for example: Project "N" can include two managers for execution i know that this way is not correct class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) executer1 = models.ForeignKey(Manager) executer2 = models.ForeignKey(Manager) deadline = models.DateTimeField(null=True, blank=True) -
Is celery-beats can only trigger a celery task or normal task (Django)?
I am workign on a django project with celery and celery-beats. My main use case is use celery-beats to set up a periodical task as a background task, instead of using a front-end request to trigger. I would save the results and put it inside model, then pull the model to front-end view as a view to user. My current problem is, not matter how I change the way I am calling my task, it always throwing the task is not registered in the task list inside celery. I am trying to trigger a non-celery task(inside, it will call a celery taskthe , using celery beats module, Below is the pesudo-code. tasks.py: @app.shared_task def longrunningtask(): res = APIcall.delay() return res caller.py: from .task import foo def dosomething(input_list): for ele in input_list: res.append(longrunningtask()) return res Periodical Task : schedule, created = CrontabSchedule.objects.get_or_create(hour = 1, minute = 34) task = PeriodicTask.objects.create(crontab=schedule, name="XXX_task_", task='app.caller.dosomething')) return HttpResponse("Done") Nothing special about the periodical task, but This never works for me. It errored that not detected tasks or not registered tasks if I do not make the dosomething() as celery task. Problem is I do not want to make the caller function a celery task, the … -
In Django how to add login required for entire app?
Suppose I have 3 apps in my Django website app_1, app_2, app_3. app_1 and app_2 can access any user, but for app_3 I want the user should log in. Using login_required I can achieve this. But I have more than 30 views and urls. I don't want to write login_required decorator on every view function. Is there any other shortcut? -
How can I "copy" some dependencies to my project
I'm following a great course (Django/react ecommerce on udemy), however the bootstrap version that they're using is really old and a lot of stuff doesn't work on newer versions, I saw they dependencies on Github but all are conflicting when I'm trying to install by npm, I can try and force some but it'll probably make things worse. There's a way I "copy/paste" their package.json and run npm install or something to get the same dependencies on my project? I can refactor everything to newer versions of course but that'll take triple the time to finish the course. -
Django "ProgrammingError at /create-post" usnig heroku postgres as database host
I am trying to create a blog website in django using postgres with heroku in the cloud. When trying to submit the post using forms from django I get this error "ProgrammingError at /create-post column "title" of relation "main_post" does not exist LINE 1: INSERT INTO "main_post" ("author_id", "title", "description"... " This is my view for creating posts from django.shortcuts import render, redirect from .forms import RegisterForm, PostForm from django.contrib.auth.decorators import login_required from django.contrib.auth import login, logout, authenticate @login_required(login_url="/login") def home(request): return render(request, 'main/home.html') @login_required(login_url="/login") def create_post(request): if request.method =='POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect("/home") else: form = PostForm() return render(request, 'main/create_post.html', {"form": form}) This is my forms.py file from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Post class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "description"] This is my Post model from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + "\n" + self.description … -
TemplateSyntaxError when tried to manage page on Django admin backend
I am new on Django CMS and i have experience with error when try to add a page or page type trough backend site. Below is the error i got. I am using Django 4.1.1 version, Django-cms 3.11.0. Any help or suggestion will be appreciated. TemplateSyntaxError at /admin/cms/pagetype/add/ Invalid block tag on line 101: 'page_submit_row', expected 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://localhost:8000/admin/cms/pagetype/add/ Django Version: 4.1.1 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 101: 'page_submit_row', expected 'endif'. Did you forget to register or load this tag? Exception Location: C:\project_data\python\myblog\env\lib\site-packages\django\template\base.py, line 557, in invalid_block_tag Raised during: cms.admin.pageadmin.add_view Python Executable: C:\project_data\python\myblog\env\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\project_data\\python\\myblog\\myblog', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\python310.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\Rosidin\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0', 'C:\\project_data\\python\\myblog\\env', 'C:\\project_data\\python\\myblog\\ and here is my settings.py SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-rt-cu)&d604(@1pmfi!@z^_etwo(jvm!k#&z3&yxb62ll+gz1#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] X_FRAME_OPTIONS = 'SAMEORIGIN' SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'simpleblog', 'sekizai', 'django.contrib.sites', 'cms', 'menus', 'treebeard', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
ElastiCache(redis) cluster mode enabled with django
I configured ElastiCache redis with cluster mode enabled. I want to connect ElastiCache with local Django. So I configured bastion host. I connected ElastiCache(non-cluster mode) with local Django. I tried cache.set(), cache.get(). It's OK. I installed 'Django-redis-cache' and 'settings.py' is like that. CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', } } But I have problem when I connect ElastiCache(cluster mode) with django. I tried tunneling with ElastiCache configuration endpoint. When I use the same 'settings.py', error message is like that. 'SELECT is not allowed in cluster mode' So, I changed 'settings.py'. CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', 'OPTIONS': { 'DB': 0 }, } } And then, error message is like that. 'MOVED 4205 xx.xx.xx.xxx:6379' What I have to do? There are no example which connect ElastiCache(cluster mode) with Django. -
django how to update item
I have postgres function DECLARE office_lastnumber TEXT; BEGIN UPDATE curriculum.clearance_item SET resolve=TRUE,resolve_date=now() where cl_itemid=f_cl_itemid; INSERT INTO curriculum.transaction_log (cl_itemid,trans_desc,trans_recorded) VALUES (f_cl_itemid,'Resolved Clearance Item',now()); RETURN f_cl_itemid; END; I have this list of items, cut some rows so it's easier to read <table style="width:100%"> <tr> <th>cl_itemid</th> <th colspan="2">Actions:</th> </tr> {%for data in data%} <tr> <td>{{data.cl_itemid}}</td> <td><a href="{% url 'update' data.cl_itemid %}">Update</a></td> </tr> {%endfor%} </table> And views.py def update(request): if request.method == "POST": cursor = connection.cursor() resolve_item = # what to put here cursor.execute("select resolve_clearance_item('"+resolve_item+"')") return render(request, 'clearance/index.html') else: return render(request, 'clearance/index.html') cl_itemid OSA2022-2023 | update DORM2022-2023| update How can def update knows if I click update (ex.OSA2022-2023) then it puts in resolve_item and run the function -
reverse_lazy not redirecting to the correct link (adding a suffix)
so this is my class based function class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'app/add_comment.html' def form_valid(self, form): list_obj = List.objects.get(slug = self.kwargs['slug']) form.instance.list = list_obj return super().form_valid(form) success_url = reverse_lazy("app:list_detail", kwargs={'slug': List.slug}) once the comment is submitted I wanna go back to detailview page which is http://127.0.0.1:8000/home/list/best-bangla-art-films2022-09-09-0505595309260000/ but its taking me to http://127.0.0.1:8000/home/list/best-bangla-art-films2022-09-09-0505595309260000/comment/ any way i can solve this? in my urls (I have excluded irrelevant paths) app_name = "app" urlpatterns = [ path('', views.HomeView.as_view(),name='home'), path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'), path('list/<slug:slug>/comment/',AddCommentView.as_view(),name="add_comment"), ] -
Viewing or Editing their own Profile who is currently login
I am editing profile using Django framework. The problem lies where the user login can see the profile of other user when they change the id in the web address. Could someone help me so that I can only view the user's profile who is login and if they change the id they will receive an error. Thanks Edit User Profile @login_required(login_url = 'signin') @user_passes_test(check_role_super) def sa_profile_edit(request, user_id=None): user = get_object_or_404(User, pk=user_id) user_profile = get_object_or_404(userMember, pk=user_id) if request.method == 'POST': form = UserFormAdmin(request.POST or None, instance=user) form_profile = MemberForm(request.POST or None, instance=user_profile) else: form = UserFormAdmin(instance=user) form_profile = MemberForm(instance=user_profile) context = { 'form': form, 'user': user, 'form_profile': form_profile, 'user_profile': user_profile } return render(request, 'pages/sa_editProfile.html', context) If role is super def check_role_super(user): if user.role == 3: return True else: raise PermissionDenied Model class User(AbstractBaseUser): MEMBER = 1 ADMIN = 2 SUPERADMIN = 3 ROLE_CHOICE = ( (MEMBER, 'Member'), (ADMIN, 'Admin'), (SUPERADMIN, 'Super Admin') ) ACTIVE = 1 DELETED = 2 DEACTIVATED = 3 STATUS = ( (ACTIVE, 'Active'), (DELETED, 'Deleted'), (DEACTIVATED, 'Deactivated') ) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, default="Some String") last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) mobile_number = models.CharField(max_length = 100, db_index=True, null = True, … -
Return newly created object after creation with ModelViewSet
We have a modelViewset: class ObjectViewSet(viewsets.ModelViewSet): serializer_class = MyObjectSerializer def perform_create(self, serializer): ... def perform_update(self, serializer): ... def perform_destroy(self, instance): ... But perform_create doesn't return the newly created object which means the 201 response only contains a few random fields that were specified during creation and not the whole new object. Is there some special way to get the object without overriding the .create() call? It seems like returning the new object is expected behavior, so I'm worried I'm doing something wrong here. -
Django. Infinite Scroll on Scrollable Table is not working
I have an scrollable table in one of my templates defined like this: <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], }); </script> ... more template ... <div id="table-div" style="overflow: scroll; height: 500px;"> <table class="table" id="sale_orders" style="margin-top: 10px; font-size: 10px;"> <form class="container py-3" method="GET"> <thead> <tr> <th scope="col" class="order_header">Header 1</th> <th scope="col" class="order_header">Header 2</th> <th scope="col" class="order_header">Header 3</th> <th scope="col" class="order_header">Header 4</th> <th scope="col" class="order_header">Header 5</th> <th scope="col" class="order_header">Header 6</th> <th scope="col" class="order_header">Header 7</th> <th scope="col" class="order_header">Header 8</th> <th scope="col" class="order_header">Header 9</th> <th scope="col" class="order_header">Header 10</th> <th scope="col" class="order_header">Header 11</th> <th scope="col" class="order_header">Header 12</th> </tr> </thead> <tbody class="infinite-container"> {% for s in sales %} <tr class="infinite-item"> <td scope="row"><span class="badge badge-info">{{s.number}}</span></td> <td scope="row">{{s.client_name}}</td> <td scope="row">{{s.comuna}}</td> <td scope="row">{{s.get_total_weigth}}</td> <td scope="row">{{s.get_total_cubic_cm}}</td> <td scope="row">{{s.get_total_area}}</td> <td scope="row">{{s.get_total_amount}}</td> <td scope="row">{{s.get_total_items}}</td> <td scope="row">{{s.product_fam}}</td> <td scope="row">{{s.deliver_date|date:"d/m/Y"}}</td> <td scope="row"> {% if s in loadedOrders %} <a class="btn btn-danger update-cart" data-load="{{initLoad.id}}" data-order="{{s.id}}" data-action="remove"> <i class="fa fa-download" aria-hidden="true"></i> </a> {% else %} <a class="btn btn-success update-cart" data-load="{{initLoad.id}}" data-order="{{s.id}}" data-action="add"> <i class="fa fa-upload" aria-hidden="true"></i> </a> {% endif %} </td> <td scope="row"> {% if s in loadedOrders %} <a data-toggle="modal" data-target="#lines_info_{{s.id}}"> <input type="button" name="partial_selection" value="Selección parcial" id="button{{s.id}}" class="btn btn-warning"> </a> {% else %} … -
Django allauth No Reverse Match
Django allauth fails when using a custom user model with the email as the primary key, I learnt about this when I tried to test the password change functionality. Reverse for 'account_reset_password_from_key' with keyword arguments '{'uidb36': 'mgodhrawala402@gmail.com', 'key': 'bbz25w-9c6941d5cb69a49883f15bc8e076f504'}' not found. 1 pattern(s) tried: ['accounts/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$'] I don't mind going into the code to fix this issue, since my application is still under development, I can still change authentication incase anyone has any suggestions. -
Django Form-Model issue;
I am having trouble working with models and forms in Django. A little clarification and help will be highly appreciated! I am really confused because I do not see the form in my html url page. I see everything else but not the form. I assume, I'm missing something. This is my forms.py from django import forms from .models import TwitterContainer class TwitterUpdateForm(forms.ModelForm): class Meta: model = TwitterContainer fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"] This is my models.py from django.db import models from django.contrib.auth.models import User class TwitterContainer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Twitter_API_key = models.fields.CharField(max_length=100) Twitter_API_key_secret = models.fields.CharField(max_length=100) Twitter_API_token = models.fields.CharField(max_length=100) Twitter_API_token_secret = models.fields.CharField(max_length=100) def __str__(self): return f'{self.user.username} Twitter Container' This is my views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import TwitterUpdateForm @login_required def twitter(request): tw = TwitterUpdateForm(request.POST, instance=request.user) if tw.is_valid(): tw.save() messages.success(request, f'NICE!') return redirect ('home') else: tw = TwitterUpdateForm(request.POST, instance=request.user) context = {'tw': tw} return render(request, 'twitter_container/twitter_container.html', context=context) And last but not least, this is my html file. {% extends 'home/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset="form-group"> <legend class="border-bottom mb-4">Profile Information</legend> {{ u_form|crispy }} {{ p_form|crispy … -
Not able to run local server for postgresql db on Django on a M1 Max Chip Mac after successfully installed psycopg2 and psycopg2-binary
I have a M1 Max Mac(released in October 2021), and installed Django 4.1.1. I was trying to have my Django app connected to a PostgreSql database I created under DATABASES in settings.py. Successfully installed psycopg2-binary using pip3 install psycopg2-binary. In ENGINE I have django.db.backends.postgresql_psycopg2. When I run python3 manage.py runserver, I kept getting this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/hahaha/codingProjects/django/env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database File "/Users/hahaha/codingProjects/django/env/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/hahaha/codingProjects/django/env/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): symbol not found in flat namespace (_PQbackendPID) I was following the step from here to tackle the issue and then got You are using macOS 12. We do not provide support for this pre-release version. You will encounter build failures with some formulae. and since then no success. Some guidance needed