Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add reverse in django user login system
I Want to add this if statement! if request.user.is_authenticated: return redirect(reverse('index')) for example: if user is login when i check user can easily go to django login page by typing url i need that if he go to that url django need to redirect to index page because when user is login he don't want to go on login page is there any solution to redirect user to homepage if he is already login i'm using django login system Here is my urls.py from django.urls import path from django.contrib.auth.models import User from todo import views from django.contrib.auth.views import LoginView, LogoutView urlpatterns = [ path('',views.index,name='index'), path('accounts/logout/', LogoutView.as_view(), name='logout'), path('',views.index,name='index'), path('accounts/register',views.signup,name='register'), path('accounts/login/', LoginView.as_view(), {'template_name': 'registration/login.html'}, name='login'), ] Here is my login.html: {% extends 'base.html' %} {% block content_block %} <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <center> <div class="col-sm-4 "> <form class="text-center border border-light p-5 mt-auto mb-auto" method="POST"> <p class="h4 mb-4">Sign In</p> <!-- Email --> {% csrf_token %} {{form}} <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha mt-4" data-sitekey="6LehyMUUAAAAALWRtQz8-T2othAvdtQLsFIjhhYS"></div> <!-- Sign in button --> <input class="btn btn-dark btn-block my-4" type="submit" value="SignIn"></input> </form> </div> </center> {% endblock %} Thanks! Any Help Appreciated! -
How to dynamically filter with field name, condition and values in Django
I have a requirement, that is from the client side I will get an array of objects which will have field names, filtering conditions and the filtering values like this. Sample array of objects: [ {field_name: "book_name", filter_condition: "contains", filter_value: "some book name"}, {field_name: "book_category", filter_condition: "not_equal", filter_value: "category value"}, {field_name: "book_author", filter_condition: "starts_with", filter_value: "authoer name"}, {field_name: "book_price", filter_condition: "equal_to", filter_value: 100} ] and I've to filter based on all of the above conditions. Consider I have a model with name Book and the fields which are there in the array of objects (i.e. book_name, book_category, book_author, book_price). I'm really not understanding how to write the logic for this. can anyone please help with the logic. Thank you in advance. -
ModuleNotFound error in Django. Not able to resolve error
I don't understand the error. I made a same project earlier but was facing some problems with virtualenv so I made another directory with virtualenv and just copy pasted all the codes in the all the files including manage.py settings.py and urls.py. I started app with command line in virtualenv and copy pasted all codes from previous app. manage.py file #!/usr/bin/env python Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quicktt.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Output(error) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 8, in main os.environ.setdefault('DJANGO_SETTINGS_MODULE') TypeError: setdefault() missing 1 required positional argument: 'value' (quicktt) udaykhalsa@warmachine:~/Projects/quick_timetable_main$ python manage.py runserver Traceback (most recent call last): File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/conf/__init__.py", line … -
django.db.utils.IntegrityError: duplicate key value violates unique constraint error while uploading a backup of psql from previous server
I recently changed my server hence I created a backup of psql database. In the new server is I used the psql dbname < dbname.bak to backup my database. Even though the django files (including migrations)(it was identical) were exactly the same, the backup process showed some errors, but somehow the backup succeeded. Every thing is working fine but the problem is when I am creating a new Model (example): class StudentRoutineInformation(models.Model): student = models.OneToOneField(Student,on_delete=models.DO_NOTHING) wakeTime = models.TimeField(blank=True,null=True) sleepTime = models.TimeField(blank=True,null=True) hoursaStudy = models.FloatField(blank=True,null=True) favoriteSubject = models.CharField(blank=True,null=True,max_length = 255) examDate = models.CharField(blank=True,null=True,max_length = 255) examType = models.CharField(blank=True,null=True,max_length = 255) location = models.CharField(blank=True,null=True,max_length = 255) def __str__(self): return self.student.name When I do makemigrations it succeeds but during migration it shows this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(121) already exists. Using other answers from stackoverflow I tried this: python manage.py sqlsequencereset MyApp | python manage.py dbshell but this also shows an error: ERROR: relation "basicinformation_studentroutineinformation" does not exist LINE 1: ...alesce(max("id"), 1), max("id") IS NOT null) FROM "basicinfo... The problem is now I can't make any models in any app. Same error in all the apps. What might be the solution? And what could have gone … -
How do we dynamically add id's in onclick function taken in django?
I am new to django and I am having 8 cards. Every card having id,content,and image path which i had dynamically rendered from the database. Now when user clicks on one card the cards information should store in javascript object and should print on console.The code I had done upto now is <div class="row"> {% for i in room %} <div class="col-4"> <div class="card6 mt-3" id="main_{{i.id}}" style ="width: 12rem;" onclick="getdata({{i.id}})"> <img src="{{i.image.url}}" id = "img_{{i.id}}" alt="..." width="185" height="100"> <div class="card-body"> <p class="card-text" id="cont_{{i.id}}"><b>{{i.content}}</b></p> </div> </div> </div> {% endfor %} </div> IN JAVASCRIPT I had written the onclick get data function var object= []; function getData(id,image,content) { var id = id; var image= $("#img_"+id).attr('src'); var content = $("#cont_"+id).text(); console.log('id', id) console.log('image', image) console.log('content', content) } }); Still I am getting error like project1:77 Uncaught ReferenceError: getdata is not defined at HTMLDivElement.onclick ( Please see if any errors in the code and help me out -
How to fix NoReverseMatch at / in django
I Want To Fix This Error: NoReverseMatch at / Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Exception Location: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 660 Python Executable: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['D:\\Learning\\Work\\Djngo\\todo_app', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Wed, 4 Dec 2019 05:07:28 +0000 In This Line I'm Getting Error: <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Signup</a> </li> When i see if user is login and if he type this url http://127.0.0.1:8000/accounts/register he can also go to register page so i don't need that so that's why i add if statement to my urls.py: from django.urls import path from django.contrib.auth.models import User from todo import views from django.contrib.auth.views import LoginView, LogoutView if User.is_authenticated: urlpatterns = [ path('',views.index,name='index'), path('accounts/logout/', LogoutView.as_view(), name='logout'), ] else: urlpatterns = [ path('',views.index,name='index'), path('accounts/register',views.signup,name='register'), path('accounts/login/', LoginView.as_view(), {'template_name': 'registration/login.html'}, name='login'), ] But When i add this i'm getting that error please help me! Error Screenshot: Here is my views.py def login_user(request, template_name='registration/login.html', extra_context=None): cap = None reg2 = None … -
Getting error while i run command docker-compose up in django python
When i run the command, docker-compose up in my django python project i am getting this error, can anyone please help me to resolve this issue, any help will be really appreciated, thanks in advance Starting trialriskincident-backend_app_1 ... Starting trialriskincident-backend_db_1 ... error ERROR: for trialriskincident-backend_db_1 Cannot start service db: driver failed programming external connectivity on endpoint trialriskincident-backStarting trialriskincident-backend_app_1 ... error eady in use ERROR: for trialriskincident-backend_app_1 Cannot start service app: error while creating mount source path '/var/www/trialriskincident-backend': mkdir /var/www: read-only file system ERROR: for db Cannot start service db: driver failed programming external connectivity on endpoint trialriskincident-backend_db_1 (8966683c6b381483c0513fef57b5d3c3e3f0e8331cb4153d37ac5302d5c9f837): Error starting userland proxy: listen tcp 0.0.0.0:3306: bind: address already in use ERROR: for app Cannot start service app: error while creating mount source path '/var/www/trialriskincident-backend': mkdir /var/www: read-only file system -
Places you can reference self in Python classes (Django model)?
I have a model that looks like something like the following: class Location: related_q: Q def whatever(self): return SomeModel.objects.filter(related_q) class Place(models.Model, Location): attr1 = models.CharField… … related_q = Q(some_field__something_else=self) Is there some way to make code like this that actually works? This exact code won't run because self is not actually defined when related_q is declared. The options I'm thinking of are just making whatever abstract in Location and defining it in the subclasses or making related_q a string and altering the code to be along the lines of the following: class Location: related_q: Q def whatever(self): return SomeModel.objects.filter(related_q=self) class Place(models.Model, Location): attr1 = models.CharField… … related_q = "some_field__something_else" However, this doesn't work because related_q here is treated as the literal name of the kwarg and not as the name of the string containing the kwarg. -
Ho to export Django Template to pdf
I'm trying to convert django template to pdf using pdfkit, wkhtmltopdf was installed but I'm getting error like OSError: wkhtmltopdf exited with non-zero code 1. error:QXcbConnection: Could not connect to display How to solve this issue or suggest me any other better way to export django template to pdf....even in this scenario styles are not in proper from django.http import HttpResponse from django.template.loader import get_template import pdfkit def generatepdf(request): data={} template = get_template('template_name.html') html = template.render(data) pdf = pdfkit.from_string(html, False) filename = "sample_pdf.pdf" response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="' + filename +'"' return response Thanks in advance -
Django template Sorting search results on dropdown select
I have a search result django template called search_result.html In the template, I have a list of products based on my filter criteria. I also have a dropdown to sort the result. I would like to sort my result, everytime an option is selected. I did a bit of research and it seems like I need to use ajax and dictsort, but currently unable to figure out the implementation. My code returning the search result page. def select(request): q1 = request.GET.get('brand') q2 = request.GET.get('model') q3 = request.GET.get('bodyStyle') q4 = request.GET.get('budget') q5 = request.GET.get('transmission') print(q1) cars = product_details.objects.all() variables = {'brand_name__icontains':q1,'model_name__icontains':q2,'bodystyle__icontains':q3, 'budget__icontains':q4 , 'transmission__icontains': q5} for key, value in variables.items(): if value is not None: cars = cars.filter(Q(**{key: value})) _brands = products.objects.all() _models= product_models.objects.all() _bodystyles = product_bodystyle.objects.all() carsdetails={ "cars" : cars, "brandFilter" : q1, "modelFilter" : q2, "bodyFilter" : q3, "budgetFilter" : q4, "transmissionFilter" : q5, "brands" : _brands, "models" : _models, "bodystyles" : _bodystyles } return render(request, 'search/search_results.html', carsdetails) Any help in this regard would be awesome. -
Send array of objects attach files in POST request to Django
I'm a newbie Front-End developer. I should build a API to send an array of object, and each object contains many files, structure like below: { files: [ file: (binary), name: "file name", description: "description", attachments: [ attachment(binary), ... ] ... ], infor: { name: "Name", address: "address" } } And our back-end server is wrote by Django. My JS Code: generateFormData() { const originData = store.getState().quotation; let formData = new FormData(); let user = originData.user; Object.keys(originData.files).forEach((key, index) => { const file = originData.files[key]; const surfare_option = (file.surface_otpion && file.surface_otpion.id) ? file.surface_otpion.id : null; const color_option = (file.color_option && file.color_option.id) ? file.color_option.id : null; formData.append(`files[${index}]`, file.file); formData.append(`files[${index}][quantity]`, file.quantity); formData.append(`files[${index}][material]`, (file.material.id) ? (file.material.id) : null); formData.append(`files[${index}][material_type]`, (file.materialType.id) ? (file.materialType.id) : null); formData.append(`files[${index}][surface_option]`, surfare_option); formData.append(`files[${index}][color_option]`, color_option); formData.append(`files[${index}][tolerance]`, file.tolerances); formData.append(`files[${index}][contain_thread]`, file.containThreads); formData.append(`files[${index}][description]`, file.description) if (file.attachments.length > 0) { file.attachments.forEach((attactment, att_index) => { formData.append(`files[${index}][attachments][${att_index}]`, attactment); }); } else { formData.append(`files[${index}][attachments]`, []); } }); formData.append(`g_captcha`, originData.captcha); formData.append('user[first_name]', user.first_name); formData.append('user[last_name]', user.last_name); formData.append('user[phone]', user.phone); formData.append('user[address]', user.address); formData.append('user[email]', user.email); return formData; } sendData() { return new Promise((resolve, reject) => { const formData = this.generateData(); let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = () => { if (xhttp.readyState === 4 && xhttp.status === 200) { resolve(JSON.parse(xhttp.responseText)); } if (xhttp.readyState === … -
setting DJANGO_SETTINGS_MODULE environment variable
I have a Django project which I got from the previous developer and I am in the process of setting up my local test environment. I can successfully get manage.py run server working without any errors, but unable to access 127.0.0.1:8000 or localhost:8000. I am getting error 'This 127.0.0.1 page can’t be found'. In my research about the issue I doubt the issue is with my manage.py or settings. How to fix this. Please help. The below is my manage.py file. import os import sys import django if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) -
NoReverseMatch at /Reverse for 'newsdesc' with keyword arguments '{'slug': ''}' not found
I am running a django project to display a website. Here is my views.py : def news_desc(request,slug): # request.session.flush() news=NewsPort.objects.get(news_title_slug=str(slug)) return render(request,'accounts/newsdesc.html',{'news':news, 'slug':slug}) urls.py : urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.user_login, name='user_login'), path('logout/', views.user_logout, name='user_logout'), # path('', views.index, name='index'), path('<int:pk>/',views.index_with_pk, name='index_with_pk'), path('profile/<int:pk>/',views.profile_detail,name='profile_detail'), path('profile/<int:pk>/edit/',views.profile_edit,name='profile_edit'), path('profile/<int:pk>/wallet/',views.wallet_view,name='wallet_view'), path('profile/<int:pk>/wallet/transac',views.history_transac,name='history_transac'), path('news/all/', views.news_all, name='news_all'), path('profile/<int:pk>/maps/',views.map_view,name='map_view'), path('news/<slug:slug>/',views.news_desc,name='newsdesc'), ] when i run, i am getting a error like this NoReverseMatch at / Reverse for 'newsdesc' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['accounts/news/(?P<slug>[-a-zA-Z0-9_]+)/$'] I dont know what exactly my error is. Any help would be appreciated. -
Django equivalence with datetime
I need that every day the voted_today field is reset to 0. from django.db import models from datetime import datetime, time from django.conf import settings from places.models import Place class Subscription(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) place = models.ForeignKey(Place, on_delete=models.DO_NOTHING) last_vote_date = models.DateTimeField(default=datetime.now) voted_today = models.IntegerField(default=0, editable=True) def __str__(self): return self.user I think something like this: def reset_votes_day(user, current_stade): subscription = get_object_or_404(Subscription, user=user, place=current_stade.place) if (subscription.last_vote_date != today()): subscription.voted_today = 0 subscription.save() But I don't know How can I do this correct: subscription.last_vote_date != today() -
Django ValueError at / The view todolist.views.index didn't return an > HttpResponse object. It returned None instead
I got this error message when I try to create my todo. Error message is: ValueError at / The view todolist.views.index didn't return an HttpResponse object. It returned None instead. def index(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_tasks = List.objects.all messages.success(request, ('Task Has Been successfuly Added to Your List!')) return render(request, 'index.html', {'all_tasks': all_tasks}) else: all_tasks = List.objects.all return render(request, 'index.html', {'all_tasks': all_tasks}) -
Error 'AnonymousUser' object has no attribute '_meta' when updateprofile
so i try to make a page to update profile , so when i try to update -> the database is success updated , but the frontend keep showing this error 'AnonymousUser' object has no attribute '_meta', i dont know why it occured , but here's the code profile.html {% load staticfiles %} {% block body_block %} <div class="container"> <div class="jumbotron"> {% if registered %} <h1>Thank you for updating!</h1> {% else %} <h1>Update Here</h1> <h3>Just fill out the form.</h3> <form class="cmxform form-horizontal style-form" id="commentForm" enctype="multipart/form-data" method="POST" action=""> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit" name="" value="Update"> </form> {% endif %} </div> </div> {% endblock %} views.py(include register + update) def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = UserProfileInfoForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('/profile/') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = UserProfileInfoForm(instance=request.user.profile) return render(request, 'profile.html', { 'user_form': user_form, 'profile_form': profile_form }) def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' … -
How to apply specific css to Django login form
Here is the code of that form: <div> <h2>Login here</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </div> This form comes from django.contrib.auth -
Django: listing many-to-many intermediate model instances gives 404 error
I have a similar set up as that illustrated in the documentation Extra fields on many-to-many relationships with some changes. class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) And in serializers.js, I have class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ("name") class MembershipSerializer(serializers.ModelSerializer): person = PersonSerializer() class Meta: model = Membership fields = ("person", "date_joined", "invite_reason") And in view.js, I have class GroupMembershipViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = MembershipSerializer(many=True) lookup_field = "group_name" def get_queryset(self): queryset = Group.objects.get(name=self.kwargs["group_name"].membership_set.all() return queryset I have checked that the queryset in get_queryset is not empty. However, when I actually try e.g. localhost:3000/group-membership/group123, I am getting HTTP 404 Not Found. Any thoughts? -
How do I dynamically change link tags in header based on region in Django CMS
I'm looking for a way to change link tags with hreflang depends on region or language used on a site. For example: I have one blog site written in english and on this site I would like to have: <link rel="alternate" hreflang="en" href="https://example.com" /> <link rel="alternate" hreflang="de" href="https://example.com/de" /> And for German version: <link rel="alternate" hreflang="de" href="https://example.com/de" /> <link rel="alternate" hreflang="en" href="https://example.com" /> I could do that with statements like this: {% if request.build_absolute_uri == "https://example.com" %} {% if request.build_absolute_uri == "https://example.com/de" %} but what if I will have more then these two paths and my if statement will grow. Is there a better solution? -
With drf-yasg, how to use statics schemas and manage custom permissions?
I am a little confused how to develop the documentation using the drf-yasg library. So I would like to ask exactly: How can I use a static swagger.json file created by swagger editor online with drf-yasg? (There are endpoints in my project that don't have serializers and models, so i created the schema manually!) My project use a permissions control with custom management. Is there any way to manage the endpoints urls in the schema if the user is not allowed permission to view specific endpoint? -
Django - Am I in the right direction for creating the models of my travel collaboration application?
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. So, it will have the following features: Main traveler will be able to manage (add, delete and share) trip details and add co-traveler (collaborative planning). Traveler will be able to login, view and update profile. Trip will contain travel schedule and each schedule may have associated travel items. Any changes made to the schedule will be logged. For collaborative planning, each traveler will be notified of the changes. Here is one of the wireframes of my project: I have built the data model of the app. Here are my codes in models.py: from django.db import models # Create your models here. from django.template.defaultfilters import slugify class Coplanner(models.Model): coplanner_name = models.CharField(max_length=20) def __str__(self): return self.coplanner_name class Trip(models.Model): trip_name = models.CharField(max_length=100) planner_name … -
Django, 2 forms on one page, one form uses data from the other
Here are my models: from django.db import models ATTACK_TYPES = ('EXA','Example') class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images') source_url = models.URLField(blank=True,null=True) class AttackItem(models.Model): attack_image = models.ForeignKey(AttackImage, on_delete=models.CASCADE) attack_used = models.CharField(max_length=55, choices=ATTACK_TYPES) hidden_data_found = models.BooleanField(blank=True) I want a user to be able to create an attackitem and an attackimage at the same time, with the attackitem having a foreignkey relation to the attackimage, as you can see. How can I do this? Thanks in advance. -
Creating signup process using a bootstrap theme
I am trying to create a signup process, allowing a user to signup. I have an existing signup theme that I am using. This is what I have in settings.py INSTALLED_APPS = [ 'sendemail.apps.SendemailConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] and urls.py from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about/', views.about, name='about'), path('courses/', views.courses, name='courses'), path('course-details/', views.coursedetails, name='course-details'), path('login/', views.login, name='login'), path('', LoginView.as_view()) and signup.html {% load static %} <!DOCTYPE html> <html lang="en"> ..... -
django: how to get the current url that the user is visiting on my site
I have a django project with two different apps: market and forum. All market related urls starts with /market/ and all forum related urls starts with /forum/. I want to have a search box which can search globally, but will prioritize search results based on the current url that the visitor is on. For example, if a user is currently visiting forum-related sites and searched something, I would show search results from forum posts first. Below is my search form <form class='search-form' action="{% url 'search_forum_market' %}" method="GET"> <input id='search-bar' name="searchterm" type="text"> <button class="searchbutton" type="submit">Go</button> </form> It will be great if I can pass a variable in the action, something like "{% url 'search_forum_market' option='' %}". -
DJ-Stripe Subcriptions
Can anyone clearly explain how the process (workflow) for a new subscription is while using the DJ-Stripe app? I'm very noobish to this, and want to make sure I'm thinking correctly. Using the latest stripe with payment intents. My idea of the workflow is this dj-stripe creates a stripe customer ID during registration for the app after the customer selects a 'plan' that creates a 'payment intent' for the user payment intent gets passed to the checkout phase, along with plan ids and price which completes the purchase via stripe elements Is that correct? Can anyone simply this anymore for me? Thanks!