Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get query from queryset. Returning invalid params
When I try to get the query from django queryset, it returns parameters without quotes which makes it an invalid query to run I have a django code as follows: qs = SignalAssetWeightTs.objects.filter(data_date__range=[start_date, end_date]) When I try to get the query so that I can query it using pyodbc (I found django's query taking 5 seconds vs pyodbc taking <1 for 50k+ rows), I try to get the query like this: str(qs.query) However, for the parameters it returns without quotes for example the query returned is SELECT * FROM [mm_signal_asset_weight_ts] WHERE [mm_signal_asset_weight_ts].[data_date] BETWEEN 2019-01-01 00:00:00 AND 2022-01-01 00:00:00 As is evident, the quotes are missing from the 2 datetime variables so when I try to run the query using pd.read_sql_query(query, conn) then I get an error pointing to these parameters. And it's not just date param, if I try to filter using anything else, I get the same issue. I was wondering whether there's any other way to generate the query from django queryset so that I can run it using pyodbc or anything else to get a faster result. I'm using Django 3.2 and sql-server -
Django Do I need to take any step for secure my user password?
I setup an password reset system in my django website. Where user first to need submit his email address then my website sending an password rest code to his email. He need to be enter his verification code and new password in password reset page. If he entered right verification code then his password will be change and redirect to login page. I have few question: is there any security risk in my password reset system? How .set_password() working for save user password? does it using any encryption method? Most important question: can user change his user_id during changing password? if yes then how to stop him to change password password if user_id changed? here is my code: the first function sending verification code to user email: def ForgetPasswordSendCode(request): if request.method == "POST": email = request.POST["email"] User = get_user_model() if not User.objects.filter(email=email).first(): messages.success(request, "Invalid mail") return redirect('members:reset-password') user_obj = User.objects.get(email=email) reset_code = str(rand_number_mail()) profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.forget_password_token = reset_code profile_obj.save() current_site = get_current_site(request) subject = 'Password Reset Code' context = { 'user_first_name': user_obj.first_name , 'user_last_name': user_obj.last_name , 'domain': current_site.domain, 'reset_code': reset_code } html_body = render_to_string('mail/resetpassword-mail.html', context) to_email = request.POST["email"] email = EmailMultiAlternatives(subject=subject,from_email='noreply@farhyn.com',to=[to_email]) email.attach_alternative(html_body, "text/html") email.send(fail_silently=False) messages.success(request, "password reset code sent … -
convert FBV to CBV
I am trying to change all my Function Based View to Class based view, i’ve been fairly successful except for this view, it’s a detail view that contains paystack payment gateway. Any help will be hugely appreciated. def car_rent_detail_view(request, pk): object = get_object_or_404(CarRent, id=pk) paystack = PaystackAccount( settings.PAYSTACK_EMAIL, settings.PAYSTACK_PUBLIC_KEY, object.total_cost ) context = {'object': object, 'pk_public': settings.PAYSTACK_PUBLIC_KEY, 'currency': 'NGN', 'paystack': paystack, } if request.method == 'POST': if paystack.verify_transaction(request.POST['reference']): messages.success(request, "payment successfull") … car_rented.save() … rent_activation.save() messages.success(request, "Rent successfully updated") return render(request, 'app/CarRent_detail.html', context=context) -
Can not add ManyToManyFields using froms.py in django
I am trying to add data in a model using django forms but getting Direct assignment to the forward side of a many-to-many set is prohibited. Use tag.set() instead. Please help me solve this. I am using multiselect field to send data to views.py. models.py class Tags(models.Model): tag = models.CharField(max_length=100) def __str__(self): return self.tag class Meta: verbose_name_plural = 'Tags' class Post(models.Model): ... author = models.ForeignKey(User, verbose_name='Author', on_delete=models.CASCADE) feature_image = models.ImageField(upload_to='blog/', verbose_name='Add Feature Image') tag = models.ManyToManyField(Tags, related_name='post_tags', verbose_name='Add Tags') def __str__(self): return self.title forms.py class PostForm(forms.ModelForm): ... class Meta: model = models.Post fields = [...] views def adminNewPostView(request): form = forms.PostForm() if request.method == 'POST': ... tags = request.POST.getlist('tagName') form = forms.PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.category = cat if subcat: post.sub_categories = subcat if subfil: post.filter_option = subfil add_tags = models.Tags.objects.filter(tag__in=tags) for tl in add_tags: post.tag = tl # Getting Error here post.save() return HttpResponseRedirect(reverse('blog_app:index')) Error Direct assignment to the forward side of a many-to-many set is prohibited. Use tag.set() instead. -
Show captcha after 5 incorrect login attempts with django-axes
I'm a beginner with Django and have a login page and with captcha which works fine, however I would like to only show the captcha within my login page template after a user has entered the incorrect login details after 5 attempts. My template has an include tag for my captcha which I prefer to to display with this method but not sure if it was possible but thought I may be able to implement via creating 2 seperate views/templates as I felt I may be able to pull it off but guess not. Urls from django.urls import path, include from django.contrib.auth import views as auth_views from . import views from .views import RequestPasswordResetEmail, CompletePasswordReset #from .forms import EmailValidationOnForgotPassword urlpatterns = [ path('login/', views.loginpage, name="login"), path('login-captcha/', views.logincaptcha, name="logincaptcha"), path('logout/', views.logoutuser, name="logout"), path('register/', views.registerpage, name="register"), path('verify-email/<uidb64>/<token>', views.verify_email, name="verify_email"), path('activate-account/<uidb64>/<token>', views.activate_account, name="activate_account"), path('set-new-password/<uidb64>/<token>', CompletePasswordReset.as_view(), name="reset-user-password"), path("request-reset-link/", RequestPasswordResetEmail.as_view(), name="request-password"), ] Views from django.conf import settings from .decorators import check_recaptcha from axes.decorators import axes_dispatch from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth import authenticate, login, logout from django.views import View @axes_dispatch def loginpage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user … -
IntegrityError: null value in column "column_id" of relation "table_model" violates not-null constraint DETAIL: Failing row contains
could some one help me i cant find where i did the mistake, my application name is firstapp and i am trying to make an interacting website where people post topics and reply to each other. When i go to a topic and try to reply to a topic after writing my relpy and pressing Post reply this error is shown to me: IntegrityError at /boards/2/topics/19/reply/ null value in column "Topic_id" of relation "firstapp_post" violates not-null constraint DETAIL: Failing row contains (29, my reply, 2021-10-07 07:04:44.068326+00, null, 2, null, null). i am using postgresql urls.py path('boards/<int:board_id>/topics/<int:topic_id>/reply/',views.reply_topic,name='reply_topic'), views.py @login_required def reply_topic(request, board_id,topic_id): topic = get_object_or_404(Topic,board__pk=board_id,pk=topic_id) if request.method == "POST": form =PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.topic = topic post.created_by = request.user post.save() topic.updated_by = request.user topic.updated_dt = timezone.now() topic.save() return redirect('topic_posts',board_id=board_id, topic_id = topic_id) else: form = PostForm() return render(request,'reply_topic.html',{'topic':topic,'form':form}) models.py class Board(models.Model): name = models.CharField(max_length=50,unique=True) description = models.CharField(max_length=150) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(Topic__board=self).count() def get_last_post(self): return Post.objects.filter(Topic__board=self).order_by('-created_dt').first() class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board,related_name='topics',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) updated_by = models.ForeignKey(User,null=True,related_name='+',on_delete=models.CASCADE) updated_dt = models.DateTimeField(null=True) def __str__(self): return self.subject class Post(models.Model): message = models.TextField(max_length=4000) Topic = models.ForeignKey(Topic,related_name='posts',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_dt … -
Triggering Django thread as a background task
I have a Django app that needs to hit an API call towards an external endpoint on every 5 seconds for a check. Since I do not want to use any external tools like django-background-task, Redis, Celery, RQ or anything I built my own solution where I separated a thread for the task. This is the decorator I found here: def start_new_thread(function): def decorator(*args, **kwargs): t = Thread(target = function, args=args, kwargs=kwargs) t.daemon = True t.start() return decorator And this is how I call the function: JOB_IN_THE_QUEUE = False @start_new_thread def check_if_job_in_the_queue_and_enqueue(): """Checks if the job is already in the queue and enqueues it if needed.""" global JOB_IN_THE_QUEUE if JOB_IN_THE_QUEUE: return JOB_IN_THE_QUEUE = True success = print_something() # print_something() is just a dummy function And here is how I print indefinitely (that will later become an API call towards a 3rd party API): def print_something(): a = print_it() if not a: time.sleep(20) print_something() # print_something() is another dummy function with while True loop replacing the actual API calling Now the way I am currently calling the check_if_job_in_the_queue_and_enqueue() is at an endpoint. I am waiting for a get request that I am sending once Django is up to trigger the job … -
why Django filter giving me this error 'QuerySet' object has no attribute 'user_id'?
When I am using this queryset I am not getting any error and it's returning the user id UserProfile.objects.get(forget_password_token=forget_password_token) print(user.user_id) >>>19 But when I am using this queryset UserProfile.objects.filter(forget_password_token=forget_password_token) why I am getting this error QuerySet' object has no attribute 'user_id' what is difference between get and filter in Django ? why not working filter method here? -
Django slug No News matches the given query
I have a django program: Model: from django.db import models from autoslug import AutoSlugField #I installed third party package autoslug class News(models.Model): title = models.CharField(max_length=100, verbose_name='title') slug = AutoSlugField(populate_from='title',null=True, blank=True) def __str__(self): return self.title View: def newsDetailView(request, slug): news = get_object_or_404(News, slug=slug) def newsListView(request): news_list = News.objects.all() #some logic and return news# return render(request, 'news/index.html', { 'news':news }) url: path('<slug:slug>/', views.newsDetailView, name='detail'), template index.html: <a class="news-list text-dark" href="/{{news.slug}}/"> Error: Page not found (404) No News matches the given query. -
Whenever one model is created or updated, I want it to insert/modify its corresponding foreign key
Whenever "Note" is created OR modified, I want it to analyze its content and decide if it needs to either create, update, or delete its corresponding entry in "Review". I'm kind of stumped on how to do this. Should I be overriding the save() function to put that logic in there? Which save() should I be overriding - Models or Serializer or Views? Can someone please show me an example of how to link changes to Note create/modify an entry in Review? Models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class Note(models.Model): title = models.CharField(max_length=1000, blank=True) content = models.TextField() date_created = models.DateTimeField(auto_now=False,auto_now_add=True) date_updated = models.DateTimeField(auto_now=True,auto_now_add=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Review(models.Model): note = models.OneToOneField(Note, on_delete=models.CASCADE, primary_key=True) easiness = models.DecimalField(decimal_places=3,max_digits=6) interval = models.IntegerField() repetitions = models.IntegerField() due_date = models.DateField(auto_now=False,auto_now_add=False) last_reviewed = models.DateField(auto_now=True,auto_now_add=False) class User(AbstractUser): pass # Create your models here. Serializers.py class NoteSerializer(serializers.ModelSerializer): #title = serializers.CharField(max_length=1000, required=False) class Meta: model = models.Note fields = ('id','title','content','date_created','date_updated','author') class ReviewSerializer(serializers.ModelSerializer): note = NoteSerializer(read_only=True) class Meta: model = models.Review fields = ('easiness', 'repetitions', 'interval', 'due_date', 'last_reviewed', 'note') views.py class NoteViewSet(viewsets.ModelViewSet): queryset = models.Note.objects.all() serializer_class = NoteSerializer permission_classes = (IsAuthenticated,) def list(self, request): queryset = self.queryset.filter(author=request.user.id) serial = NoteSerializer(queryset, many=True) return … -
Django: Accessing Custom User Model(created according to Django Docs) to create a new user using new template(signup.html)
Here, I am placing what I have done following others post... I can create user from default admin site logging in and also by logging in using custom user model "MyUser". I want to use 'default' user model to create Admin users and want to use 'MyUser' user model to create all others users. From 3 days, I am trying but nothing works. Advance thanks for helping me. I am new in Django. As, I have found that the problems are in forms.py and views.py signup.html <div class="signup"> <div class="account-login"> <h1><a href="/login">CSP SignUp</a></h1> <form action="" class="login-form" name="signup_form" method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <input type="text" placeholder="Full Name" class="form-control username"> </div> <div class="form-group"> <input type="password" placeholder="Password" class="form-control username"> </div> <div class="form-group"> <input type="password" placeholder="Re-type Password" class="form-control username"> </div> <div class="form-group"> <input type="email" placeholder="e-Mail Address" class="form-control username"> </div> <div class="form-group"> <input list="gender" placeholder="Gender" class="form-control username"> <datalist id="gender"> <option value="Male"> <option value="Female"> <option value="Common"> </datalist> <input list="country" placeholder="Country" class="form-control username"> <datalist id="country"> <option value="Afghanistan"> <option value="Albania"> <option value="Algeria"> <option value="Andorra"> <option value="Angola"> <option value="Antigua and Barbuda"> <option value="Argentina"> <option value="Armenia"> <option value="Australia"> <option value="Austria"> <option value="Azerbaijan"> <option value="Bahamas"> <option value="Bahrain"> <option value="Bangladesh"> <option value="Barbados"> <option value="Belarus"> <option value="Belgium"> <option value="Belize"> <option value="Benin"> <option … -
Heroku can't import settings, but my computer can do it normally?
I'm deploying a Django application with Heroku. I have to import settings.py to wsgi.py. However, whenever I run WSGI.py on my computer, it runs normally. But heroku can't import this file and I have no idea what's happening. This is what shows up when I run heroku logs --tail: 2021-10-07T03:57:47.989483+00:00 app[web.1]: ModuleNotFoundError: No module named 'settings' This is the folder strucute: This is WSGI.py: import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') application = get_wsgi_application() As I've said before, if I run WSGI.py alone on my computer, it works and it finds settings.py normally. But Heroku can't find it. -
Django Table Data Overlay
I am not sure if this is even possible in Django. I would like to "overlay" the data on one table with data from another based on permissions. Table 1: pk col1 col2 isEditable 0 10 4 True 1 42 1 False 2 12 2 False Table 2 would have exactly the same structure minus the isEditable column. Any attempt to write data to a row where isEditable=False will be redirected to Table 2. I am calling this data overlay, but is there a proper term for doing this and is it possible to do in Django? If so what are the best practices for doing this? I am thinking of something involving signals, but I am very new to this part of Django. If it helps the back end database is MySQL V8.0. -
Problem with installing and integrating LDAp with django
i am having issues with integrating ldap with django and if there is a possibility if you could help. Below is what i get back when i put pip install . and whether there is any alternative way of integrating ldap with django. Thanks in advance. By the way im trying to do this in the virtual enviroment i have created. ERROR: Command errored out with exit status 1: command: 'C:\Users\farza\AppData\Local\Programs\Python\Python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\farza\AppData\Local\Temp\pip-install-9_s78z_y\python-ldap_543b61fd07204c1bae7f83e89bdfea54\setup.py'"'"'; file='"'"'C:\Users\farza\AppData\Local\Temp\pip-install-9_s78z_y\python-ldap_543b61fd07204c1bae7f83e89bdfea54\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\farza\AppData\Local\Temp\pip-record-p6gh3zcu\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\farza\AppData\Local\Programs\Python\Python39\Include\python-ldap' cwd: C:\Users\farza\AppData\Local\Temp\pip-install-9_s78z_y\python-ldap_543b61fd07204c1bae7f83e89bdfea54 Complete output (80 lines): running install running build running build_py creating build\lib.win-amd64-3.9 copying Lib\ldapurl.py -> build\lib.win-amd64-3.9 copying Lib\ldif.py -> build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\ldap copying Lib\ldap\async.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\asyncsearch.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\cidict.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\compat.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\constants.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\dn.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\filter.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\functions.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\ldapobject.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\logger.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\modlist.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\pkginfo.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\resiter.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\sasl.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\syncrepl.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap_init_.py -> build\lib.win-amd64-3.9\ldap creating build\lib.win-amd64-3.9\ldap\controls copying Lib\ldap\controls\deref.py -> … -
Django -- Checking input type, display error message if wrong
I'm new to learning Django/Python and hoping for some assistance. This is for an assignment and I'm stumped on the last part. We need to take input from the user (name as string; weight, height inches, and height feet as ints) and calculate the bmi, displaying {{name}}'s bmi is {{bmi}} I have that part working fine, but the second part of what I have to do is check that the input is valid, that is not a string where it should be an int, and not a negative number. I am supposed to put this into the class. I was reading about is_valid() but I haven't used that yet and am not entirely sure how to do it. I am guessing it will have to be an if else statement. views.py class Home(View): def get(self, request): return render(request, 'home.html') def post(self, request): n = str(request.POST["name"]) w = int(request.POST["weight"]) hi = int(request.POST["heightinches"]) hf = int(request.POST["heightfeet"]) h = (hf*12) + hi bmi = (703*w) / (h*h) return render(request, 'response.html',{"name":n,"heightinches":hi,"heightfeet":hf,"weight":w,"height":h,"bmi":bmi} home.html {% load static %} <html> <head><title>Home</title></head> <body> <h1>Hello Repl.it</h1> <form action="" method="post"> {% csrf_token %} name: <input type="text" name="name" id="name"/> <br> weight: <input type="text" name="weight" id="weight"/> pounds<br> height: <input type="text" name="heightinches" id="heightinches"/> … -
Django API Framework for POST not working?
I have the following code: models.py class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname serializers.py class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] views.py @api_view(['PUT']) def update_device(request, pk=None): if pk != None: devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk) devdserializer = DeviceDetailSerializers(devicedetail, data = request.data) if devdserializer.is_valid(): devdserializer.save() results = { "device_details" : devdserializer.data, } return Response(results, status=status.HTTP_201_CREATED) return Response(devdserializer.errors, status=status.HTTP_400_BAD_REQUEST) The code seems correct to me but whenever i tried to use Postman to do the PUT, i get error of 500. I dont understand why is this happening. For the code, I am using https://www.youtube.com/watch?v=B65zbFro2pU to guide me on how to code as I am new to this framework. Can anyone advise me on what to do to solve this error? Thank you … -
Django Paypal Integration createOrder curl
I'm trying to implement paypal in Django without any SDK or package. https://developer.paypal.com/docs/business/checkout/server-side-api-calls/create-order/ Want to rewrite this cURL curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders \ -H "Content-Type: application/json" \ -H "Authorization: Bearer Access-Token" \ -d '{ "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "USD", "value": "100.00" } } ] }' in pyhton: my current code: t = gettoken() d = {"intent": "CAPTURE","purchase_units": [{"amount": {"currency_code": "USD","value": "100.00"}}]} h = {"Content-Type: application/json", "Authorization: Bearer "+t} r = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=h, data=d).json() My Error: Internal Server Error: /createOrder ..... AttributeError: 'set' object has no attribute 'items' The Bearer Token is fine. Any idea? What i'm missing. -
What to include for Djoser to accept my requests?
I used DRF and Djoser for my authentication in React SPA. My question is why does it says forbidden and CSRF verification failed. what should I include to my request to grant access to my django server. export const addDummy = (data) => apiCallBegan({ url: '/product/dummy/', method: 'post', data: data, onSuccess: dummyAddedSuccess.type, onError: dummyAddedFailed.type, }); Is there a header that I should put or something? Please I'm new to djoser, django and drf. -
Filter the number of pages not working django
I have a page where it will display the details that is in my database in a form of a table, I am doing a filtering so when the list gets very long at least it can split up into different pages instead of user scrolling through, but I tried and nothing came out, not sure if I am doing correctly or not. This is what I wanted as shown in the picture below but it is not displaying. ViewMCO.html {% extends "customerbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <script> // Function to download table data into csv file function download_table_as_csv(table_id, separator = ',') { var rows = document.querySelectorAll('table#' + table_id + ' tr'); var csv = []; for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll('td, th'); for (var j = 0; j < cols.length; j++) { var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ') data = data.replace(/"/g, '""'); row.push('"' + data + '"'); } csv.push(row.join(separator)); } var csv_string = csv.join('\n'); … -
postgres gives me the error "message the m.deveui column does not exist" even though this column does exist
I generated the tables from django migrations. My elec_meter_machine table exists with the devEUI column Here is my request. SELECT AVG(r.voltage),AVG(r.current),m.devEUI FROM elec_meter_reporting r INNER JOIN elec_meter_infosignal AS s ON s.id=r.infos_signal_id INNER JOIN elec_meter_machine AS m ON m.devEUI = s.machine_id WHERE m.devEUI="8cf9572000023509" ERROR: ERROR: the m.deveui column does not exist LINE 5: ON m.devEUI = s.machine_id HINT: Maybe you want to reference the column "m.devEUI" What am I not doing right? -
In Django how to initialize a form with the current detailview object?
I'm a Django beginner building a blog Website. The models are: Blog, Threads, Comments. The Blog has Threads, each Thread has Comments. From the Thread detailview the logged user can create a comment with a form. The created Comment should have its 'thread' value initialized with the current detailview thread object, as thread is a foreignkey to the Thread model in the Comment model. In the Comment create view, I tried to use form.instance.thread = self.kwargs['pk'] but it brings this error: KeyError at /blogs/comment/create/ 'pk'. Can you please help me to pass the thread to the form? models.py: class Comment(models.Model): comment_date = models.DateField(default=datetime.date.today, blank=True) comment_text = models.TextField(max_length=1000, help_text='Enter your comment') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) thread = models.ForeignKey('Thread', on_delete=models.SET_NULL, null=True) class Meta: verbose_name = 'comment' verbose_name_plural = 'comments' def __str__(self): return f'{self.id} ({self.thread.thread_name})' def get_absolute_url(self): return reverse('comment-detail', args=[str(self.id)]) class Thread(models.Model): thread_name = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) summary = models.TextField(max_length=1000,) post_date = models.DateField(null=True, blank=True) blog = models.ForeignKey('Blog', on_delete=models.CASCADE, null=True) class Meta: ordering = ['-post_date'] def __str__(self): return self.thread_name def get_absolute_url(self): return reverse('thread-detail', args=[str(self.id)]) urls.py: path('thread/<int:pk>/', views.ThreadDetailView.as_view(), name='thread-detail') path('comment/create/', views.CommentCreate.as_view(), name='comment_create') views.py: class ThreadDetailView(generic.DetailView): model = Thread class CommentCreate(LoginRequiredMixin, CreateView): model = Comment fields = ['comment_text', 'thread'] def form_valid(self, form): … -
How to authenticate django user in my custom password reset system?
I building an password reset system for my users. An password reset code sending to user mail and now I want to authenticate user by this code. If user enter the right code then password will be change otherwise not. I am also storing the verification code in my models fields. models.py: class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") forget_password_token = models.CharField(max_length=100,blank=True,null=True) views.py I am sending the code to user mail and also storing the same code in my models fields def ForgetPasswordSendCode(request): if request.method == "POST": email = request.POST["email"] User = get_user_model() if not User.objects.filter(email=email).first(): messages.success(request, "Invalid mail") return redirect('members:reset-password') user_obj = User.objects.get(email=email) reset_code = str(rand_number_mail()) #generating random code profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.forget_password_token = reset_code profile_obj.save() current_site = get_current_site(request) subject = 'FARHYN.COM Account Verified sucessfully' context = { 'user_first_name': user_obj.first_name , 'user_last_name': user_obj.last_name , 'domain': current_site.domain, 'reset_code': reset_code } html_body = render_to_string('mail/resetpassword-mail.html', context) to_email = request.POST["email"] email = EmailMultiAlternatives(subject=subject,from_email='noreply@farhyn.com',to=[to_email]) email.attach_alternative(html_body, "text/html") email.send(fail_silently=False) messages.success(request, "An password reset code sent to your email") return redirect('members:change-password') #redirecting user to password reset page after submitting mail. return render(request, 'members/password_reset_form.html') Now I am stuck in password reset view where user insert the code and change his password. I am not undersealing how to authenticate user by … -
How to get data from a formset that was rendered in template by looping over and displaying each form
I have the following view: formset = ItemFormSet(instance = menu) if request.method == 'POST': formset = ItemFormSet(request.POST, instance = menu) if formset.is_valid(): return HttpResponse(formset.cleaned_data) else: print(formset.errors) return render(request, 'food_truck/test.html', { 'formset': formset, }) By just displaying {{formset}} in a template, this works fine and the formset.cleaned_data is returned and displayed when I hit submit: <form class="" action="{% url 'food_truck:test_url' %}" method="post"> {% csrf_token %} {{formset}} <input type="submit" name="" value="submit"> </form> But, I would like to loop through each form in the formset to style each one individually: <form class="" action="{% url 'food_truck:test_url' %}" method="post"> {% csrf_token %} {% for form in formset %} {{form}} {% endfor %} <input type="submit" name="" value="submit"> </form> The forms are still displayed, but when I hit 'submit', formset.is_valid() fails and the call to print(formset.errors) just prints an empty list. How can I retrieve the forms' data when looping through them in a template? Thanks for any help with this. -
App engine+Postgresql getting "Connection refused" error
I am a newbie trying to deploy a toy django app on the standard App engine and I am getting the following error. Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/asim800:us-central1:django-app1/.s.PGSQL.5432"? My app runs properly locally with the cloud SQL. My settings.py looks like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloudsql/asim800:us-central1:django-app1', 'NAME': 'myproject', 'USER': 'pblogsu', 'PASSWORD': '****', } } I can see them correctly in the following log: {'database': 'myproject', 'host': '/cloudsql/asim800:us-central1:django-app1', 'password': 'pblogsu', 'user': 'hidden'} I have enabled Google Cloud SQL API. I have seen similar problem reported like here (https://github.com/GoogleCloudPlatform/python-docs-samples/issues/870) but none of the suggestions have helped me. Any help would be greatly appreciated. -
Is there a way to get an enumeration type text choice field to accept an incoming post request with the human readable value?
It was my understanding (maybe incorrect) that using enumeration type text choices for CharFields is useful because your database stores less characters on the database but you can still work with a human readable values. However it seems counter-productive when you are posting data from the frontend to the backend because the frontend has to post the value that will be stored in the database, not the human readable one. For example: class MyModel(models.Model): class Animals(models.TextChoices): ALLIGATOR = 'a', 'Alligator' BEAR = 'b', 'Bear' COYOTE = 'c', 'Coyote' animal = models.CharField(max_length=20, choices=Animals.choices) If i post {animal: 'Coyote'} to the endpoint, it will say 'animal is not a valid choice'. I have to post {animal: 'c'} instead. Is there a way I can get the MyModelSerializer to accept human readable values instead of having to setup frontend select element options to have differing labels and values?