Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django @login_required doesn't work when login function has redirect
In login view I have: def login_signup(request): ... login(request, user) messages.success(request, 'You have successfully logged in to your account.') return redirect('user_app:profile') In some other function I have @login_required(login_url='/login/') but their redirect doesn't work and allways redirect to user_app:profile. How do I redirect a user to page he/she redirected from it to login page, and redirect to the profile page only when he/she referred directly to the login page? -
How to annotate to query with a custom function in Django ORM?
I have this model: class Brand(models.Model): name = models.CharField(max_length=32) and this function that returns a number that shows similarity between two strings (a number between 0 and 1). from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() I want to annotate a column to my query that shows similarity value between name and a string and order them by similarity. I wrote something like this but it won't work and I don't know how it works. Brand.objects.all().annotate( similarity=ExpressionWrapper(similar(F('name'), 'mercedes'), output_field=models.DecimalField()).order_by('similarity') ) If there is another way to do it please let me know. -
How to Solve template does not exist on hosting on PythonAnywhere
I made a project and I want to host this on PythonAnywhere But If I run My Application I M having Template Does Not Exist Error .. Setting.py BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_5&ew#uj!u(kjfmo7b@nxh9=o6fg4!8t3u2a9yj*@vti2u7i^u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['manojgupta143.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Blog', 'taggit', ] this is my setting file Where I Defined My setting Of Template **Folder Structure Where My Template Folder Exists ** /home/manojgupta143/Blog-project-with-django/templates/blog If I Run Web Page M Having These Type Of Error ImportError at / Module "django.template.backends.django" does not define a "Django/Templates" attribute/class Request Method: GET Request URL: http://manojgupta143.pythonanywhere.com/ Django Version: 3.2 Exception Type: ImportError Exception Value: Module "django.template.backends.django" does not define a "Django/Templates" attribute/class Exception Location: /home/manojgupta143/.virtualenvs/myproj/lib/python3.9/site-packages/django/utils/module_loading.py, line 22, in import_string Python Executable: /usr/local/bin/uwsgi Python Version: 3.9.5 Python Path: ['/home/manojgupta143/Blog-project-with-django/', '/var/www', '.', '', '/var/www', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/manojgupta143/.virtualenvs/myproj/lib/python3.9/site-packages'] Server time: Sat, 05 Feb 2022 07:59:23 +0000 web Page Configuration Source code: /home/manojgupta143/Blog-project-with-django/ Go to directory Working directory:/home/manojgupta143/ WSGI configuration file:/var/www/manojgupta143_pythonanywhere_com_wsgi.py Python … -
Python Django, how to view all the content of registration for user profile. it only shows the email
Python Django, how to view all the content of registration for user profile. it only shows the email. views.py def Unreg(request): if request.method=='POST': form = NewACCForm(request.POST) if form.is_valid(): form.save() messages.success(request,"The New User is save !") else: messages.error(request, "Duplicate Record") return render(request,'Registration.html') def loginpage(request): if request.method == "POST": try: Userdetails=acc.objects.get( Q(email=request.POST['email']) | Q(uname=request.POST['email']), pwd=request.POST['pwd'] ) print("Username=",Userdetails) request.session['email']=Userdetails.email request.session['pwd']=Userdetails.pwd return render(request,'Logout.html') except acc.DoesNotExist as e: messages.success(request,' Username / Password Invalid.') return render(request,'Login.html') def logout(request): try: del request.session['email'] uname = request.session['uname'] except: return redirect('Loginpage') return redirect('Loginpage') logout.html {{request.session.email}} <button onclick="myFunction()"><a href="{% url 'Loginpage' %}">Logout</a></button> <script> function myFunction() { if (confirm("Are you sure you want to logout?")) { } else { } } </script> -
Django DRF POST Changes not Persisting (Resets Data after Refresh)
I have been working with DRF recently , and actually have something surprising to share :- I try to post the request to an endpoint that i have created , **views.py** class SettingsAPI(APIView): @classmethod def post(self,request,pk): shop_token = request.session.get('shop_token') if request.session.get('shop_token') else "" shop_domain = request.session.get('shop_domain') if request.session.get('shop_domain') else "" store = Store.find_store_by_url(shop_domain) if not store: return JsonResponse({'status':'failed','msg':'invalid request'}) data = json.loads(json.dumps(request.data)) settings = get_object_or_404(Setting,pk=pk) serializer = SettingSerializer(settings, data = request.data) if serializer.is_valid(): serializer.save() return JsonResponse({'status':'success'}) @classmethod def get(self,request,pk): settings = get_object_or_404(Setting,pk=pk) if settings: serializer = SettingSerializer(settings) return JsonResponse({'status':'success','data':serializer.data}) return JsonResponse({'status':'failed'}) **urls.py** path('v1/page/settings/<int:pk>',SettingsAPI.as_view(),name='pagerud-settings-api'), **serializer.py** class SettingSerializer(serializers.ModelSerializer): class Meta: model = Setting fields = "__all__" And i am using vue js , to send the request like this. const settings_data = { "store": this.store.store_id, "header_background_color": `${this.settings.header_background_color}`, "header_font_color": `${this.settings.header_font_color}`, "page_background_color": `${this.settings.page_background_color}`, "card_background_color": `${this.settings.card_background_color}`, "card_font_color": `${this.settings.card_font_color}`, "header_message": `${this.settings.header_message}`, "header_message_optional": `${this.settings.header_message_optional}`, "button_background_color": `${this.settings.button_background_color}`, "button_font_color": `${this.settings.button_font_color}` } models.py class Setting(models.Model): header_background_color = models.CharField(max_length=200,null=True,blank=True,default='#212529') header_font_color = models.CharField(max_length=200,null=True,blank=True,default='white') page_background_color = models.CharField(max_length=200,null=True,blank=True,default='white') card_background_color = models.CharField(max_length=200,null=True,blank=True,default='whitesmoke') card_font_color = models.CharField(max_length=200,null=True,blank=True,default='white') button_background_color = models.CharField(max_length=200,null=True,blank=True,default='#212529') header_message = models.CharField(max_length=200,null=True,blank=True,default="""Hi, Add Your Greeting Message here""") header_message_optional = models.CharField(max_length=200,null=True,blank=True , default="Thanks for purchasing the order") button_font_color = models.CharField(max_length=200,null=True,blank=True,default='white') store = models.OneToOneField( Store, on_delete=models.CASCADE, primary_key=True, related_name='settings' ) def __str__(self) -> str: return self.store.store_name All works well, … -
Domain based email senders in app engine in a django application
I have a google app engine django application, I want to send emails through a custom domain mail. When I try to add the domain mail user@domain.com to mail senders in app engine, I get the error : The following emails could not be added because they are on a different domain. The email must be associated with a Google Apps domain or Google group. If the email is associated with a Google group, your role in the group must be Owner or Manager: The site is hosted on google domains and registered on Google Workspace. I have added the google SPF Record and the email is the owner of the domain yet still produces the error. I have added the DNS Records to the Google Domain Records, yet it cannot allow the email to be added to the email senders on app engine. Is there a way I can make it work other than using other party mail senders like sendgrid -
how to pause setInterval and resume if there is new data from database?
How to pause setInterval if all data from the database are loaded and resumes if there is new data from the database without manual page refresh? The problem with this if I will not use clearinterval(), it will keep on fetching the data repeatedly and will populate the chart with the same data. <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [{ label: '# of Votes', data: [], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); $(document).ready(function(){ var timer = setInterval(function(){ var postt = $.ajax({ type:'GET', url: "{% url 'post' %}", success: function(response){ console.log(response.post) var count = 0; var total = response.post.length for(var key in response.post) { myChart.data.labels.push(response.post[key].date); myChart.data.datasets.forEach((dataset) => { dataset.data.push(response.post[key].number); myChart.update(); }); count++; //} console.log( myChart.data.labels.length) } console.log(count) if(count == total){ // <--- stops the setInterval … -
How to stop Getting 405 error Method not allowed?
I am trying to make my django project to work but somehow I always come to get this error Method Not Allowed (POST): / I have tried using decorators like @csrf_exempt like in the django documentation as to not encounter csrf errors and yet I came to this error.Please tell me what's the problem with my code... urls.py from test.views import HomePageView,predict urlpatterns = [ path('', HomePageView.as_view(), name="homepage"), path('predict', predict, name="predict"),] views.py @csrf_exempt def predict(self, request, *args, **kwargs): text = self.request.get_json().get('message') # check if text is valid response = get_response(text) message = {'answer': response} return JsonResponse(message) app.js onSendButton(chatbox) { var textField = chatbox.querySelector('input'); let text1 = textField.value if (text1 === "") { return; } let msg1 = { name: "User", message: text1 } this.messages.push(msg1); fetch( $SCRIPT_ROOT+'/predict',{ method: 'POST', body: JSON.stringify({ message: text1 }), mode: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken':csrftoken, }, }) .then(r => r.json()) .then(r => { let msg2 = { name: "Sam", message: r.answer }; this.messages.push(msg2); this.updateChatText(chatbox) textField.value = '' }).catch((error) => { console.error('Error:', error); this.updateChatText(chatbox) textField.value = '' }); } homepage.html <div class="container"> {% csrf_token %} <div class="chatbox"> <div class="chatbox__support"> <div class="chatbox__header"> <div class="chatbox__image--header"> <img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image"> </div> <div class="chatbox__content--header"> <h4 class="chatbox__heading--header">Chat support</h4> <p class="chatbox__description--header">Hi. My name … -
AgoraRTC_N-production.js.map django video web application
DEVTOOLS FAILED TO LOAD SOURCE MAP AgoraRTC_N-production.js.map AgoraRTC_N-production.js.map is not loading to source map in Google Chrome. It is in static/assets AgoraRTC_N-production.js.map It is like zoom meeting function by AgroaRTC. -
How to get only one random element from object?
My model.py is this. class Country(models.Model): country_name = models.CharField(max_length=200) country_fact = models.CharField(max_length=1000) country_capital = models.CharField(max_length=100) country_flags = models.ImageField(upload_to='flags') View.py is this def index(request): country = Country.objects.all() return render(request,'index.html',{'country':country}) I'm retrieving those data in HTML by using this {% for count in country %} <img src="{{ count.country_flags.url }}"> This retrieves all the country images from the database(I'm using Postgresql). I want to retrieve only one random country flag from the database. How can I achieve this? Thanks for the help. -
Use PHP to handle GET requests with flask
Hello I am kind of a newbie to web development so I have a question that if I use python (flask or django) how can I use PHP to handle get requests? Thanks to any help! -
How to load data lazily in Django admin list page
I have a lot of annotations in admin page by customizing def get_queryset(self, request: HttpRequest) -> QuerySet: in ModelAdmin and using them in list_display. This has made admin page loading extremely slow. Is there a way to load the annotated fields lazily for each row in django admin list page? For example I rewrite the get_queryset and load the other data separately for each row lazily. I appreciate any help or idea:) -
Cron Scheduler in Django
I use Scheduler in Django/Windows IIS from apscheduler.schedulers.background import BackgroundScheduler to run my background script. Problem is, taks gets run multiple times. If I run same program on my PC, it only runs once, but when I upload to windows server (which hosts my Django app) it runs more times. First 2, then 14, then again 14. Code scheduler.add_job(cron_mail_overdue, "cron", hour=7, minute=14, day_of_week='mon-sun', id="task002", replace_existing=True) For test I put scheduler.add_job(cron_mail_overdue, "interval", minutes=1, id="task002",replace_existing=True) It's the same, I did this just to test. It does the same no matter the task I run. Why does it run more then once? And why not always the same number? First 2 times, then 14. Taks sends email, so I get 14 emails, all received at same time. -
How to make otp firebase with django
I am trying to make phone verification with firebase in django but i don't the func that could help me in that anyone tried firebase otp with django can help or javascript it will be okay too -
Is there a way to enable login with my-website's account on other websites?
So I want to make an app store like Epic Games(let's name it "AB"). I want that the game developers can integrate my website with their games so they can provide a "Login With AB" option on their login page. Is it possible? Thank you for reading my question! -
How can I add two different slugs on two models in two different apps in Django?
I trying to add slugs to my service page and my project page, but whenever I try to run my project page I get the Page not found (404) No service found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/project/ Raised by: pages.views.<class 'pages.views.ServiceDetail'> Here's my class-based code models.py class Service(models.Model): title = models.CharField(max_length=50) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') alt = models.CharField(max_length=60, blank=True) icon = models.CharField(max_length=20) description = RichTextField() shortdesc = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) created_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('service_detail', kwargs={'slug': self.slug}) class Project(models.Model): title = models.CharField(max_length=50) category = models.CharField(max_length=50) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') alt = models.CharField(max_length=60, blank=True) client = models.CharField(max_length=50) launched = models.CharField(max_length=50) demands = models.CharField(max_length=50) description = RichTextField() shortdesc = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) video_link = models.URLField(max_length=100) created_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project_detail', kwargs={'slug': self.slug}) urls.py path('<slug:slug>/', views.ServiceDetail.as_view(), name='service_detail'), path('project/<slug:slug>/', views.ProjectDetail.as_view(), name='project_detail'), views.py def project(request): return render(request, 'project/project.html') class ProjectDetail (generic.DetailView): model = Project template_name = 'project/project_detail.html' def service(request): return render(request, 'pages/service.html') class ServiceDetail (generic.DetailView): model = Service template_name = 'pages/service_detail.html' how can I re-route so that my project page can work out? any help would be grateful -
Get request sometimes returns "There was an error: Unexpected token e in JSON at position 0"
Sometimes it will work, it seems to work when I open a new browser window. However, I can't recreate a consistent scenario when it works This is the request i'm trying to make login(): void { // const loginFormValues = JSON.stringify(this.loginForm.getRawValue()) this.userService.login(this.loginForm.getRawValue()).subscribe({ next: (data) => { console.log(data); this.router.navigate(['/']); }, error: (error) => { this.router.navigate(['/login']); console.log('There was an error: ' + error.message); }, }); } this.loginForm.getRawValue() gives me the following object {username: 'jocelyn', password: '123456'} This is what the backend does class LoginView(APIView): def post(self, request): username = request.data['username'] password = request.data['password'] # We find the first user since username is unique user = User.objects.filter(username=username).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') # Token expires in sixty minutes payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), # Date when token is created 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = {'jwt': token} return response -
CSV to Django Models specific fields
I am trying to upload a CSV into a Django Model. The problem I am encountering is, how can I write the data from my CSV to each of the fields without using indexes? Instead, write directly the field name from my CSV. with open(obj.file_name.path, 'r', encoding="utf-8") as f: reader = csv.reader(f) review_count = 0 for i, row in enumerate(reader): review_count += 1 print(i) if i==0: pass else: OrderProcessModel.objects.create( order_id=row[0], order_date=row[1], external_id=row[2], email=row[3], first_name=row[4], last_name=row[5], quantity=row[6], product_id=row[7], owner=request.user ) print(row) obj.activated = True obj.save() For example for order_id=row[0], how can I specifically write the data in order_id without using row[0]? Like order_id=row['order_id'] is not working. Thanks! -
Show separate number with comma in django tempalte
I have an issue that when the user is typing on text field the number is not separated by a comma user is typing 500000, it shows 500000 not 500,000 in models so_tien=models.CharField(max_length=50) in forms so_tien=forms.CharField(label="Số tiền",widget=forms.TextInput(attrs={"class":"form-control", 'onclick': 'numberWithCommas()',}),required=False) template file <div class="col-md-4" id="sotien" style="display:none">{{ form.so_tien}}</div> javascript code numberWithCommas in the template file: function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } Thanks for your reading -
possible to split the model based on field in DRF admin.py
I have model named organization. I am using this same model model for 2 api's. I have a field code. one API do code auto generation another API takes user entry code. I want to separate the tables based on code. Autogeneration code starts SUB001,SUB002,.... like wise. user entry code thats userwish. models.py class Organization(models.Model): code = models.CharField(max_length=255, null=False, unique=True) name = models.CharField(max_length=255, null=False) organization_type = models.CharField(max_length=255, choices=TYPES, null=False, default=COMPANY) internal_organization = models.BooleanField(null=False, default=True) location = models.ForeignKey(Location, on_delete=models.RESTRICT) mol_number = models.CharField(max_length=255, null=True, blank=True) corporate_id = models.CharField(max_length=255, null=True, blank=True) corporate_name = models.CharField(max_length=255, null=True, blank=True) routing_code = models.CharField(max_length=255, null=True, blank=True) iban = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) total_of_visas = models.IntegerField(null=False, default=0) base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT, null=True, blank=True, default=None) logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) def __str__(self): return self.name admin.py @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): list_display = ( 'id', 'code', 'name', 'location', 'organization_type', 'internal_organization', 'mol_number', 'corporate_id', 'corporate_name', 'routing_code', 'iban', 'description', 'total_of_visas', 'base_currency', 'logo_filename', ) Is there any possible to split models based on code,.. Really Expecting help... -
'django.db.backends.posgresql_psycopg2' isn't an available database backend
I am stuck at setting up django with postgreSQL. I have installed required packages for setup provided below. asgiref==3.5.0 Django==4.0.2 djangorestframework==3.13.1 psycopg2==2.9.3 psycopg2-binary==2.9.3 pytz==2021.3 sqlparse==0.4.2 tzdata==2021.5 and have edited DATABASES in manage.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.posgresql_psycopg2', 'NAME': 'tododb', 'USER': 'postgres', 'PASSWORD': '2993', 'HOST': 'localhost', 'PORT': '5432', } } but getting error when i runserver or make migration: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.posgresql_psycopg2' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How To Use Reverse Relations in Django Class Based Views - 2
I'm creating a to-do list where I want the tasks to get displayed on its respective date, but I'm having a hard time doing so. I found another resource that kind of answered a similar question, but I'm still having a hard time implementing the query with reverse relations, and not quite sure how to put it on template. link Been spending 2 or 3 days stuck on this. Hope I could get some pointers here Desired Outcome Current Outcome My models: class Dailies(models.Model): date = models.DateField(auto_now_add=True) the_user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return str(self.date) class DailyTask(models.Model): task = models.CharField(max_length=255) dailies = models.ForeignKey( Dailies, on_delete=models.CASCADE ) def __str__(self): return self.task My ListView: class DailiesListView(LoginRequiredMixin, ListView): model = Dailies template_name = 'home.html' context_object_name = 'date' ordering = ['-date'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['date'] = context['date'].filter(the_user=self.request.user) context['todos'] = DailyTask.objects.filter( dailies__the_user=self.request.user) return context My template (home.html): {% if user.is_authenticated %} {% for each_date in date %} <h3> <li> {{each_date}}: {% for todo in date.dailies_set.all %} <br> {{todo}} {% endfor %} </li> </h3> {% endfor %} {% else %} ... {% endif %} -
How to create a django `models.Textchoices` programmatically?
How to create a django models.Textchoices programmatically? In the django doc, it shows you can define a model.TextChoices with: class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') SENIOR = 'SR', _('Senior') GRADUATE = 'GR', _('Graduate') How can I create programmatically the same choices class from a list of key, values? mapping = { 'FRESHMAN': 'FR', 'SOPHOMORE': 'SO, 'JUNIOR': 'JR', 'SENIOR': 'SR', 'GRADUATE': 'GR' } # ??? YearInSchool = build_model_text_choices(mapping) -
Returning a Unix Timestamp when querying a DateTimeField
In Django, I have the following query dates = ( Event.objects.filter(cancelled=False) .exclude(id=event.id) .aggregate( first_date=Min('start'), last_date=Max('start'), next_date=Min('start', filter=Q(date__gt=timezone.now().date())), recent_date=Max('start', filter=Q(end__lt=timezone.now())) ) ) and I would like to annotate the query so that my lesson dates are returned as unix timestamps rather than datetime objects. I recognize I can simply do something like dates.next_date.timestamp(), but this causes an error when dates.next_date is None, and I'd rather not have to repeatedly check that my object is not None before getting its timestamp. How could I go about this? I have searched through many other answers and the Django docs but haven't been able to find anything I could specifically apply here. Thanks in advance! -
Email for form wont return users email inputed and just returns mine Django
hi any help please! When the user inputs a random email on the website this case "test@gmail.com" it returns my own email some reason. The message and name part of the form works tho just wondering how i can fix so that it return there email in the form.