Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Model of Users and Posts Django
I am trying to learn Django by creating something similar to Reddit. I have models for Post and User, and now I want to create one for "Community". I have looked at this post: How to store an array of users in django? However, I am unsure if the ManyToMany relationship is right here (perhaps it is). I want the Community Model to contain Posts and Users registered with the Community. Each Community can have many posts, and each user can belong to multiple communities. When a Community is deleted, only delete the posts in that community, not the users. Similarly, when a User is deleted or a Post deleted, just remove that aspect from the Community. If anyone has done this before or knows of a resource to learn this please let me know. -
Django DRF test API with extra configuration
I have a question about app testing with django DRF. I have this url with an extra argument. url(r"^api/search/$", views.ApiSearch.as_view(parameter=True), name="search") I'm building its test but now I need to pass that argument as False. I'm trying something like this: url = reverse("search", kwargs={"parameter": False}) But this is not working, since kwargs pass parameters on url. Anyone have any idea of how that extra configuration or extra parameter is called, and how do I test it? -
ImproperlyConfigured DetailView is missing a QuerySet
I'm trying to use a generic DetailView for my model and I'm getting the error: ClassroomDetailView is missing a QuerySet. Define ClassroomDetailView.model, ClassroomDetailView.queryset, or override ClassroomDetailView.get_queryset(). I've seen other people with a similar error and the solution is typically that their url pattern didn't properly reference their view name. I can't find any typos like that for mine though. My understanding is that the generic DetailView does not require a querset. models.py class Classroom(models.Model): classroom_name = models.CharField(max_length=10) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.classroom_name views.py class ClassroomDetailView(generic.DetailView): model: Classroom urls.py app_name = 'gradebook' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('signup/', SignUpView.as_view(), name='signup'), path('courses/', views.courses, name='courses'), path('classroom/', views.classroom, name='classroom'), path('classroom/<int:pk>/', views.ClassroomDetailView.as_view(), name='classdetail'), path('addstudent/<int:classroom_id>/', views.addstudent, name='addstudent'), path('addmultistudent/<int:classroom_id>/', views.addmultistudent, name='addmultistudent'), path('objective/<int:course_id>/', views.addobjective, name='addobjective'), path('addassessment/<int:course_id>/', views.addassessment, name='addassessment'), ] -
How to use a different unique identifier of Django ForeignKey field in ModelForm
I have the following Models: class Book(models.Model): name = models.CharField(max_length=128) isbn = models.CharField(max_length=13, unique=True) available = models.BooleanField(default=True) class Borrow(models.Model): date = models.DateTimeField(auto_now_add=True) book = models.ForeignKey(Book) and the following ModelForm: class CreateBorrowForm(forms.ModelForm): class Meta: model = Borrow fields = ['book'] def clean_book(self): book = self.cleaned_data['book'] try: return Book.objects.get(id=book, available=True) except Book.DoesNotExist: raise ValidationError('Book does not exist or it is unavailable') I would like to have a form that expects the isbn field of the Book model, instead of id. As the isbn field is unique, it does make sense. In the clean_book method I would need to do a little change to have the following line: return Book.objects.get(isbn=book, available=True) The problem is that I cannot find an approach to force the form to use a different unique identifier. In my specific case, this is required to avoid brute force enumerating over numerical IDs. -
I tried to iterate a nested dictionary with another dictionary in another definition and Django does not render it
My template receives following the nested dictionary of general projects list with another dictionary of tags in another definition, together with a definition of a page view: from django.views import View class ProjectsView(Mixin, View): def get(self, request, id = None, *args, **kwargs): template = "pages/projects.html" context = { 'title': "Projetos", } return render(request, template, context) def general_projects_list(self, request, id = None, *args, **kwargs): template = "pages/projects.html" projects = { 0: { "Name": "Suru++ Pastas", "Description": "Um executável em Bash de Unix e de BSD para substituir a cor das pastas dos temas de ícones Adwaita++, Suru++ e Yaru++", "Colaboration": "Clonei o projeto o qual desenvolvi a fim de torná-lo compatível com os temas de ícones", "Link": "https://github.com/gusbemacbe/suru-plus-folders", "Tags": ["Makefile", "Shell"] }, 1: { "Name": "Icons Missing Request", "Description": "Um executável que lê o tema de ícone utilizado e os arquivos de desktop de Linux para localizar se os ícones dos arquivos de desktop não existem no tema de ícone e gera uma lista de solicitação de ícones perdidos", "Colaboration": "Colaborei com o projeto, traduzindo o executável em diversas línguas estrangeiras para facilitar os usuários não familiares com a língua inglesa no terminal", "Link": "https://github.com/gusbemacbe/icons-missing-script", "Tags": ["Shell", "Vala"] }, 2: { … -
How to add a functional contact form at my home page in django by using {% include %} or any other method?
I am fairly new at django and i'm trying to make a blog website. I want the blogsite to have a contact page in it so users can send email to the author. I created a contact.html and made a contact function in views and added the path in urls.py (/contact.html). If I go to (/contact.html) and fill the form it works as intended and sends the email. But when I use the {%include %} tag and add it to my homepage it stops working from home and submitting the form doesn't do anything. contact.html: {% if message_name %} <h1>{{ message_name }} Your message has been submitted. We will get back to you soon..</h1> {% else %} <form action="#" method="POST"> {% csrf_token %} <input type="text" name='message-name' placeholder="Your Name"><br><br> <input type="text" name='message-lname' placeholder="Your Name"><br><br> <input type="email" name='message-email' placeholder="Your Email"><br><br> <textarea name='message' placeholder="Your Message"></textarea> <br/><br/><br/> <button type="submit">Send Message</button> <br><br><br> </form> {% endif %} views.py: def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_lname = request.POST['message-lname'] message_email = request.POST['message-email'] message = request.POST['message'] #send mail send_mail( 'message from ' + message_name + ' ' + message_lname + ' their email ' + message_email , message, message_email, ['myemail@gmail.com'], ) return render(request, 'blog/contact.html', {'message_name':message_name}) else: … -
How to make follow-following system in django for different three different models?
I have started learning Django about a month ago and I am trying to add a follow-following system for three models: Student, Teacher, and School but I am a little stuck. I have very little idea on how to a user A to the follower's list of user B when user B starts following user A because the user can be from any of the three mentioned models. How can I solve this or what would be the best way to go around this? Here are my Django models: student/models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) father_name = models.CharField(max_length=30) mother_name = models.CharField(max_length=30) dob = models.DateField() address = models.TextField() contact = models.CharField(max_length=10) roll_no = models.IntegerField() about = models.TextField() following = models.ManyToManyField(User, related_name='student_following', blank=True) followers = models.ManyToManyField(User, related_name='student_followers', blank=True) class_name = models.ForeignKey(Classes, null=True, on_delete=models.SET_NULL) school_id = models.ForeignKey(School, on_delete=models.CASCADE) teacher/models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) dob = models.DateField() started_teaching = models.IntegerField() joining_date = models.DateTimeField() qualification = models.CharField(max_length=10) about = models.TextField() contact = models.CharField(max_length=10) following = models.ManyToManyField(User, related_name='teacher_following', blank=True) followers = models.ManyToManyField(User, related_name='teacher_followers', blank=True) school_id = models.ForeignKey(School, on_delete=models.CASCADE) school/models.py class School(models.Model): school_id = models.OneToOneField(User, on_delete=models.CASCADE) principal = models.CharField(max_length=50) name = models.CharField(max_length=50) address = models.CharField(max_length=50) contact = models.CharField(max_length=10) … -
How to add a try except blocks in this django-import-exportview?
I can't get it right on how to appropriately add a try except block here. My aim is to capture and display the particular errors that might be experienced during import i.e the particular invalid rows etc. I believe a try except block can help but I don't know how to implement it in this view. class upload(LoginRequiredMixin,View): context = {} def post(self, request): form = UploadForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportResource() result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,result.invalid_rows) self.context['result'] = result return redirect('/') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Successfully.') else: self.context['form'] = UploadForm() return render(request, 'home.html', self.context) -
Passing perameters into model formset
I'm trying to pass some variables into a model formset. I've looked at the official django documentation and they talk about doing this with a regular, non-model formset. I can't get this to work for a modelformset though. views.py EmployeeTeamFormset = modelformset_factory(EmployeeTeamMembership, form=EmployeeTeamForm(), extra=0, max_num=10, can_delete=True) formset = EmployeeTeamFormset(request.POST or None, queryset=EmployeeTeamMembership.objects.filter(employee__user=user, team=team), kwargs={'user': user, 'team': team}) forms.py class EmployeeTeamForm(forms.ModelForm): class Meta: model = EmployeeTeamMembership fields = ('employee', 'team_lead',) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) self.team = kwargs.pop('team', None) I get the following error: name 'user' is not defined Thanks for your help! -
unable to get the drop down menu in same row and it write once only when form is submitted
can't make a code that functions on the same line as others. want below line to third if statement where contact.save() line appear. please refer original block. appreciated your help if request.POST.get('program'): savevalue = Contact() savevalue.program=request.POST.get('program') savevalue.save() original block def index(request): if request.method == 'POST': name = request.POST.get('name', '') contact = request.POST.get('contact', '') address = request.POST.get('address', '') # program2 = request.POST.get('program2', '') # bba = request.POST.get('bba', '') # bhm = request.POST.get('bhm', '') email = request.POST.get('email', '') w3review = request.POST.get('w3review', '') if request.POST.get('program'): savevalue = Contact() savevalue.program=request.POST.get('program') savevalue.save() if name and contact and address and email and w3review: contact = Contact(name=name, contact=contact, address=address, email=email, w3review=w3review) contact.save() else: return HttpResponse("Enter all details") return render(request, 'index.html') -
How to upload files using FTP server and django rest api....How to do that?
am new to django...please be patient if it is basic thing..till i could't acheive this.. I am developing one django rest api for uploading files(ex.image,videos)using FTP server. I thought of use django ftp server library..but am not sure how to connect the FTP server(am using winscp)with django server.. -
Django 3.1.7 model custom constraint
class Connection(models.Model): source = models.OneToOneField(Interface, related_name="source", on_delete=models.CASCADE) destination = models.OneToOneField(Interface, related_name="destination", on_delete=models.CASCADE) notes = models.TextField(blank=True, null=True, help_text="Add any additional information about this connection here.") def __str__(self): return f"{self.source} : {self.destination}" With the model above, it is possible to create a "connection" in the Django admin from A-B and from B-A. I am trying to find a way to only allow one or the other. I've looked at Meta constraints, but I'm either not getting my mind around it, or it's not possible. 'm sure there is something simple that I'm just not aware of yet. Any advice? -
How to create a pick up email field in django
I am creating a Mails System Management Application. So I would like, based on the attachment figure, in the field A when the customer's email address to whom I want to send an email exists already in the system, to display their emails from this field. Otherwise, we will type the email address entirely, and then submit the form. Here is the models.py. class Contacts(models.Model): type_Contact_choice=( ('Agent','Agent'), ('Association','Association'), ('Autre','Autre'), ('Collectivité','Collectivité'), ('Conseil minicipal','Conseil minicipal'), ('Elu','Elu'), ('Particulier','Particulier'), ('Précture','Précture'), ('Société','Société'), ) civilite_choice=( ('Monsieur','Monsieur'), ('Madame','Madame'), ('M. et Mme','M. et Mme'), ('Monsieurs','Monsieurs'), ('Mesdames','Mesdames'), ) category_choice=( ('Personnel','Personnel'), ('Externe','Externe'), ) nom = models.CharField(max_length=200, null=False) type_contact = models.CharField(_('Type'), choices=type_Contact_choice, max_length=200, null=True, ) category = models.CharField(_('Catégorie du contact'), choices=category_choice, max_length=50, null=True, blank=True) prenom = models.CharField(_('Prénom'), max_length=200, null=False) civilite = models.CharField(_('Civilité'), choices=civilite_choice,max_length=200,null=True, blank=True) fonction = models.CharField(max_length=200, null=True, blank=True) telephone = models.CharField(blank=True, null=True, max_length=16) adresse = models.TextField() mobile = models.CharField(blank=True, null=True, max_length=16) email = models.EmailField(blank=True, null=True) divers = models.TextField(blank=True, null=True) service = models.CharField(max_length=300, blank=False, null=False) def __str__(self): return self.nom + ' '+self.prenom class Actions(models.Model): statut_action_choice=( ('Encours','Encours'), ('En attente','En attente'), ('Terminée','Terminée'), ('Annulé','Annulé') ) action_date =models.DateTimeField(auto_now_add=True) action_modification = models.DateTimeField(auto_now=True) de = models.ForeignKey(User, on_delete=models.CASCADE, null=True) a = models.ForeignKey(Contacts, on_delete=models.CASCADE, null=False) cc = models.EmailField(max_length=254,null=True,blank=True) file = models.FileField(_('Document joint'),upload_to='action/%Y/%m/%d', blank=True) statut = models.CharField(max_length=30, choices=statut_action_choice, default='Encours') action … -
Signal to add ManyToMany Field objects onto a signal-created model instance
CONCEPT: I am trying to create a goals-type app that will work as follows: The user creates a goal week (prompted to multi-select from list of pre-established goals) and hits 'Create goal week'. When the goal week is created by the user, a django signal auto-generates model instances for the following models: GoalDayOne, GoalDayTwo, GoalDayThree, GoalDayFour, GoalDayFive and each of these instances have a OneToOne association with the GoalWeek, like your typical User/Profile signal relationship. I have this part working. Now here is the tricky part: When the user establishes a GoalWeek instance --and the signal creates the GoalDayOne, GoalDayTwo...etc-- instances with it, I want to pass those pre-chosen goals to each day as well. I know handling items from the M2M field in a signal is not easy but there has to be a way to do it, correct? I have tried switching from a signals.py file to handling it all on models.py with no luck. I also fiddled around with the m2m_changed signal instead with no luck. I am assuming I can prob do this on the traditional post_save signal but I have to establish the GoalItems as an independent list first and then add them to the … -
Trigger action from button in odoo qweb
I'm trying to run a view from stock.picking view and it's ok when I call it using menuitem, but when i'm trying to replace menuitem by button, it's not triggered. In my .xml <menuitem name="My Element" id="menu_elem" action="my_action_name"/> this was working well. But that one is wrong. For example,I don't want to call the myMethod from my model,but it's required to have name="". So when I click on my button, it calls the method and I hadn't my action triggered like in menuitem <record id="myId1" model="ir.ui.view"> <field name="name">stock.picking.form.inherit</field> <field name="model">stock.picking</field> <field name="inherit_id" ref="stock.view_picking_form"/> <field name="arch" type="xml"> <field name="state" position="before"> <button name="myMethod" string="My Element" action="my_action_name" type="object" class="oe_highlight"/> </field> </field> </record> So is there a way to have only triggered action without the use of model method, like in menuitem? -
How to specify timeout for a query using Django
We have a session timeout for all queries using this: 'default': { 'ENGINE': 'django.db.backends.postgresql', ... 'OPTIONS': { 'options': '-c statement_timeout=5000', ... } } } However there is a query that takes much longer to run. I want to override the 5 second constraint for this specific query. How would I do this? We have a Postgres DB. Thanks! -
ModuleNotFoundError in django when including urls.py
I am trying to implement a simple chat API using django/drf, but when I tried adding my chat_app.urls to src.urls its throwing an error stating chat_app.serilizers.py module not found. here is my serializers.py file - from rest_framework import serializer from chat_app.models import ChatGroup class ChatGroupSerializer(serializers.ModelSerializer): class Meta: model = ChatGroup fields = '__all__' here is my view - from django.shortcuts import render from rest_framework import permissions from rest_framework.generics import (ListCreateAPIView, RetrieveUpdateDestroyAPIView) from chat_app.models import ChatGroup from chat_app.serializers.py import ChatGroupSerializer class ChatGroupListCreateView(ListCreateAPIView): permission_classes = [permissions.IsAuthenticated] serilizer_class = ChatGroupSerilizer queryset = ChatGroup.objects.all() class ChatGroupRetriveUpdateDestroyView(RetrieveUpdateDestroyAPIView): permission_classes = [permissions.IsAuthenticated] serilizer_class = ChatGroupSerilizer queryset = ChatGroup.objects.all() here is my chat_app.urls.py from django.urls import path from chat_app.views import ChatGroupListCreateView urlpatterns = [ path("", ChatGroupListCreateView.as_view(), name='chat-list-create-api') ] here is src.urls.py - urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('chat/', include('chat_app.urls')) ] this is the error Django is throwing -> traceback -
Django - Class based view - Meta tags from model don't get passed to template
I am having an issue with my meta tags not being passed to my category.html template. Here is my models.py class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) image = models.ImageField(null=True, blank=True, upload_to='images/') meta_title = models.CharField(max_length=255) meta_keywords = models.CharField(max_length=255) meta_description = models.CharField(max_length=255) def __str__(self): return self.name Here is my views.py class CategoryView(ListView): model = Post template_name = 'category.html' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.filter(category=self.category) # def get_context_data(self, **kwargs): # context = super(CategoryView, self).get_context_data(**kwargs) # context['category'] = self.category # return context def get_context_data(self, *args, **kwargs): category_menu = Category.objects.values_list('slug', flat=True) context = super(CategoryView, self).get_context_data(*args, **kwargs) context['category_menu'] = category_menu return context The commented-out code works, however, I need the second one so that I can also display categories (name from Category model) on that page. Here is my url.py urlpatterns = [ path('', HomeView.as_view(), name="home"), path('article/<slug:slug>', ArticleDetailView.as_view(), name="article-detail"), path('category/<slug:slug>', CategoryView.as_view(), name="categories"), and finally here is my category.html {% extends 'base.html' %} {% block title %} {{ category.meta_title }} {% endblock %} {% block meta_extend %} <meta name="description" content="{{ category.meta_description }}"> <meta name="keywords" content="{{ category.meta_keywords }}"> <meta property="og:description" content="{{ category.meta_description }}"> {% endblock %} {% block content %} -
Bulk Lock Objects in Django
I have concurrent workers that bulk update objects in my Django application, and I'm running into deadlocks. I've tried to make the transaction atomic with the following code: with transaction.atomic(): users = User.objects.select_for_update().filter(id__in=list(list_of_users_to_update.keys())) for user in users: user.checked_date = list_of_users_to_update[user.id]["checked_date"] user.changed_date = list_of_users_to_update[user.id]["changed_date"] user.save() My deadlock is getting thrown on the line for user in users: How can I acquire a lock on the rows prior to initiating the transaction to avoid deadlocks? -
Url getting duplicated in django: sign/sign/
The sign/ url is getting duplicated on itself, as shown in the below image. How can I stop this url duplication? It was working fine before taking input from the user. When the user clicks on the submit button it duplicated itself in the url. This is View.py from django.http import HttpResponse # Create your views here. def Home(response): return render(response, "main/index.html",{}) def sign_up_in(reponse): if reponse.method == 'POST': email = reponse.POST.get('eemail') print(email) return render(reponse, "main/sign_up_in.html",{}) This is urls.py from . import views urlpatterns = [ path("", views.Home, name = "Homes"), path("sign/", views.sign_up_in, name = "sign_up_in") ] This is urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), path('sign/', include("main.urls")), ] This is my sign_up_in.html code <form method="POST" class="form" id="a-form" action="{% url 'sign_up_in' %}"> {% csrf_token %} <h2 class="form_title title">Create Account</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"></div><span class="form__span">or use email for registration</span> <input class="form__input" type="text" placeholder="Name" name="eemail"> <input class="form__input" type="text" placeholder="Email"> <input class="form__input" type="password" placeholder="Password"> <button class="button" type="submit">SIGN UP</button> </form> <form method="POST" class="form" id="b-form" action=""> {% csrf_token %} <h2 class="form_title title">Sign in to Website</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"form__span">or use your email account</span> <input class="form__input" type="text" … -
How to get data between date range in django rest_framework?
I want to fetch some data between two dates, but got an error that is "AttributeError: 'str' object has no attribute 'values'". How I solve this issue? views.py class TestView(APIView): def get(self, request): user_obj = Payload.objects.all() usr = self.request.user print(usr) user_data = TestSerializer(user_obj, many=True) return Response({'status':'success'}) def post(self, request): serializers = TestSerializer(data=request.data) if serializers.is_valid(raise_exception=True): start_date = serializers.validated_data['start_date'] end_date = serializers.validated_data['end_date'] user_id = serializers.validated_data['user_id'] user_obj = Payload.objects.filter(user=user_id, timestamp__gte=start_date,timestamp__lte=end_date) sr = TestModelSerializer(user_obj, many=True) return Response({'status':sr.data}, status = status.HTTP_200_OK) else: print(serializers.errors,"errors") serializers.py class TestSerializer(serializers.Serializer): user_id = serializers.IntegerField() start_date = serializers.DateTimeField() end_date = serializers.DateTimeField() class TestModelSerializer(serializers.ModelSerializer): model = Payload fields = '__all__' models.py class Payload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=False) input_values = models.CharField(max_length=20) def __str__(self): return self.input_values -
Logging the output of a management command run by a cron job
I have a cron job scheduled that runs a custom management command in Django. I would like to output all information on a success as well as a fail. How would I structure this? CRONJOBS = [ ('* * * * *', 'django.core.management.call_command', ['my_custom_command']) ] I've tried setting up a relative path in settings like this log_file_path = os.path.join(BASE_DIR, "log_files/cronjob.log") and then added '>> log_file_path' next to 'call_command' as well as 'my_custom_command' but neither work. I could also be structuring my relative path incorrectly. -
Django & Ajax : data get lost between the view and the template
Using Ajax and Django, my data get lost when sent back to my template and I can't retrieve them. Here is my code and the logic : Following the dependent dropdown lists tutorial offered by ["Simple is Better Than Complex"][1] I have implemented an Ajax request. Here is the html code: <p class="multiple-choice" id="mandate-city" data-url="{% url 'officials:ajax_load_mandate_city' %}">Local Mandate: {{ form.mandate_city }}</p> The ajax request is fired from this script: <script> $("#id_departments").change(function (){ var url = $("#mandate-city").attr("data-url"); var departmentId = $(this).val(); $.ajax({ url: url, data: { 'department': departmentId }, success: function (data){ $("#id_mandate_city").html(data); console.log(data); } }); }); </script> After check with console.log, the data are collected by the script. Then, they reach the view. Here is my view: def load_mandate_city(request): department_id = request.GET.get('department') mandate_city = MandateCity.objects.filter(department_id=department_id).order_by("department") return render(request, "officials/mandate_city_list.html", {mandate_city: mandate_city}) With a print, I have checked, and the data are treated as planned. Then the data are sent back through the url: path('ajax/load_mandate_city/', views.load_mandate_city, name="ajax_load_mandate_city") They seem not to reach the template: {% for mandate in mandate_city %} <option value="{{ mandate.pk}}">{{ mandate.get_mandate_display }}</option> {% endfor %} And I could not track them in my script. :-/ Can somebody let me know where the bug is ? Thanks. [1]: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html -
Django, i would like to sent data from drop down menu to database when once the hit submit button but error occure
I am trying to send data to the database from the dropdown menu from index.html that is why I have created models.py as the initial class named as Program and later on used it to Contact class using ForeignKey. registered Contact at admin.py and later on i have used class name programs to in index.html and it is rendering the name of the programs which is entered by me at admin panel of django. but the issue is {{program2}} does display at the index page but when user go the form and selects and submits this program2 data is not going to the database. How could i use the dropdown to sent value to the database. Help appreciated, accepting to resolve it from my way. models.py class Program(models.Model): program1 = models.CharField(max_length=50, default='') class Contact(models.Model): name = models.CharField(max_length=50, primary_key=True) contact = models.CharField(max_length=50, default='') address = models.TextField(max_length=1000, default='') program2 = models.ForeignKey(Program, on_delete=models.CASCADE, null=True, blank=True) # program = models.CharField(max_length=50, default='') # bba = models.CharField(max_length=50, default="") # bhm = models.CharField(max_length=50, default="") email = models.CharField(max_length=50, default="") w3review = models.TextField(max_length=1000, default="") def __str__(self): return self.name views.py def index(request): if request.method == 'POST': name = request.POST.get('name', '') contact = request.POST.get('contact', '') address = request.POST.get('address', '') program2 = … -
pinax django URL -- The current path, account/signup/, didn’t match any of these Error
im new to django and python and i'm trying to implement pinax/django-user-account to my project. I followed all the instructions on pinax-documents and i suppose i controleld all the dynamics from original django documentation. But still i cant reach the sign-up and login pages using href link. Also i cant reach those pages via http://127.0.0.1:8000/account/signup/... im getting the error below: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/account/signup/ Using the URLconf defined in zetamedweb.urls, Django tried these URL patterns, in this order: i think i'm missing something really basic but what am i missing? main.url from django.contrib import admin from django.urls import path from django.conf.urls import url,include from zetamedweb import views from django.conf.urls.static import static app_name = 'Index' urlpatterns = [ url(r"^$", views.IndexView.as_view(),name='ındex'), url('admin/', admin.site.urls), url(r"^ Treatments/", include('Treatments.urls')), url(r"^ AboutUs /", include('About_Us.urls')), url(r"^ Contact /", include('Contact.urls')), url(r"^ Travel_Tips /", include('Travel_Tips.urls')), url(r"^ Destinations/", include('Destinations.urls')), url(r"^ FAQ/", include('FAQ.urls')), url(r"^ TailorMade/", include('TailorMade.urls')), url(r"^ APP/",include('APP.urls')), url(r"^account/", include("account.urls")), ] app.urls(pip installed, i only added app_name) from django.urls import path from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) app_name = 'Account' urlpatterns = [ path("signup/$", SignupView.as_view(), name="account_signup"), path("login/$", LoginView.as_view(), name="account_login"), path("logout/$", LogoutView.as_view(), name="account_logout"), path("confirm_email/<str:key>/$", ConfirmEmailView.as_view(), name="account_confirm_email"), path("password/$", ChangePasswordView.as_view(), …