Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loggin django based in class view no working,
I'm new to django, I'm doing a login based on a udemy course, but it does not work for me. My error is that the credentials are not correct, if I start session with admin it does not work either. This is my code, I hope you can help me thanks, If there is any way to debug to find the error, please tell me url.py ############################################################################## from django.conf import settings from django.urls import include, path from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views from tienda.users.views import ( Indice, ListarProductos, DetalleProducto, ComentarioProducto, Ingresar, Salir, CambiarPerfil ) urlpatterns = [ path('', Indice.as_view(), name="indice"), path("listado_productos", ListarProductos.as_view(), name="listado_productos"), path("detalle_producto/<int:pk>/", DetalleProducto.as_view(), name="detalle_producto"), path("crear_comentario/", ComentarioProducto.as_view(), name="crear_comentario"), path("ingresar/", Ingresar.as_view(), name="ingresar"), path("salir/", Salir.as_view(), name="salir"), path("editar_perfil/", CambiarPerfil.as_view(), name="editar_perfil"), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ######################################################################## views.py from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.views.generic import DetailView, RedirectView, UpdateView, TemplateView , CreateView, ListView from django.db.models import Q, Max, Min from tienda.productos.models import Producto, Comentario from django.contrib.auth.views import LoginView, LogoutView from django.http import HttpResponseRedirect from django.urls import reverse_lazy, … -
Paginate comments to Posts
I have a comment form for my posts. It looks like this view.py def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user #comment.author.photo = object.author.profile.image.url comment.save() return redirect('Post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) models.py class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=20) text = models.TextField(max_length=200, verbose_name='内容') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('text',) widgets = { #size of textbox 'text': forms.Textarea(attrs={'rows':4}), } Where should I add pagination function to my comments to make it works? I have a pagination for my posts, but posts are using a DetailView class and I dont know how to make it work for comment function -
Error when trying to access uploaded files in Django application
I have a Django application where I'm uploading some json files. When trying to access these files got 404 (not found) error. The files are to load in a OpenLayers layer. If I use a json in project static files it works fine. The files are uploading correctly to "uploaded_files" directory in project folder. But when trying to access these files in html page by object.file.url I always get error. If I change MEDIA_URL to "/uploaded_files/" got error because it expects to find core/ or admin/ url. Example: http://127.0.0.1:8000/uploaded_files/file.json settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/core/uploaded_files/' # core is the application in django project. I have admin and core applications. MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_files') urls.py file: from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py file: def get_upload_file_name(instance, filename): return "%s_%s" % (str(time()).replace('.', '_'), filename) class Estado(models.Model): estado = models.CharField(max_length=2) def __str__(self): return self.estado class TipoFile(models.Model): tipo = models.CharField(max_length=50) def __str__(self): return self.tipo class FileEstadoMunicipio(models.Model): estado = models.ForeignKey(Estado, on_delete=models.CASCADE, null=False) municipio = models.CharField(max_length=100, null=False) tipo = models.ForeignKey(TipoFile, on_delete=models.CASCADE, null=False) dat_criacao = models.TimeField(default=datetime.datetime.now(), null=False) file = models.FileField(upload_to=get_upload_file_name, null=False) html file: {% load static … -
Is there a way to save the current time + 1 hour or 1day or 1week to a DatetimeField using django view orm?
Is there a way to save the current time + 1 hour or 1day or 1week to a DatetimeField using django view orm? for example models.py dead_line = models.DateTimeField(blank=True, default=utc_tomorrow) def add_todo_by_ajax(request): title = request.POST['title'] dead_line_option = request.POST['dead_line_option'] # print("dead_line_option : " , dead_line_option) if dead_line_option == "1h": print ("1h") # deadline = elif (dead_line_option == "4h"): print ("4h") elif (dead_line_option == "8h"): print ("8h") elif (dead_line_option == "1d"): print ("1d") elif (dead_line_option == "8h"): print ("1w") todo = Todo.objects.create(title=title, author=request.user, director = request.user) print("todo(insert result) : " , todo) user_update = Profile.objects.filter(user=request.user.id).update(uncompletecount = F('uncompletecount')+1) return HttpResponse(redirect('/todo/')) -
How to use href in a loop in Django?
I want to create a side bar in which I want to add different links. My query is that the IDs if the hrefs are same but the names are different. Like 127.0.0.1:8000/1/Austria 127.0.0.1:8000/1/America I want to refer every href to a different link. Is it possible using a loop?If yes, Please tell me how? Here is the code views.py def details(request,item_id): item=get_object_or_404(Item,pk=item_id) clients=Client.objects.all() return render(request,'details.html',{'item':item,'clients':clients}) template.html <div> <h1 style="text-align: center">Products</h1> <div class="container-fluid d-none d-xl-block" style="width: 17%;height: 1400px;float: left;background-color: lavender"> <ul style="list-style: none;" class="form-control" id="client"> {% for client in clients %} <li class="btn btn-block btn-responsive" style="background-color: #daad86;color: white;width: 250px;height:50px;margin-top: 10px"><a href="{{ client.place }}">{{ client.place }}</a></li> {% endfor %} </ul> </div> url.py path('<int:item_id>/',views.details,name='details'), Thanks in advance -
Upgrade to django2.2.2 produces TypeError: render() got an unexpected keyword argument 'renderer'
I have an application that seemed to work fine under django 2.0 using postgresql. I decided to rebuild it using sqlite3 and took the opportunity to upgrade to django 2.2.2. I am moving my code in from the old application on an as-needed basis, hoping to leave some mistakes behind. When I use a Generic View (CreateView) with a form that uses crispy forms and auto-complete-light, I get the error cited in my title. Other, similar questions lead me to believe that auto-complete-light has been updated for this problem. I am running django 2.2.2 in a virtual environment on MacOS 10.14.5. Here is the result of pip freeze: backports.csv==1.0.7 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20181111 Django==2.2.2 django-autocomplete-light==3.3.5 django-bootstrap3-datetimepicker==2.2.3 django-bootstrap4==0.0.6 django-crispy-forms==1.7.2 django-crontab==0.7.1 django-csvimport==2.12 django-datetime-widget==0.9.3 django-debug-toolbar==2.0 django-extra-views==0.12.0 django-filter==2.1.0 django-guardian==2.0.0 django-import-export==1.2.0 django-pdb==0.6.2 django-pivot==1.8.0 django-querysetsequence==0.11 django-tables2==2.0.6 djangorestframework==3.9.4 et-xmlfile==1.0.1 jdcal==1.4.1 odfpy==1.4.0 openpyxl==2.6.2 pytz==2019.1 PyYAML==5.1.1 six==1.12.0 sqlparse==0.3.0 tablib==0.13.0 Unipath==1.1 xlrd==1.2.0 xlwt==1.3.0 Here is the view that produces the error: views.py from .forms import BankTransactionInputForm from .models import BankTransaction from django.views.generic import CreateView class BankTransactionCreate(CreateView): model = BankTransaction form_class = BankTransactionInputForm success_url = 'http://localhost:8000/mny/home/' Here is the form referred to: forms.py from django.forms import ModelForm from django import forms from django.db import models from crispy_forms.helper import FormHelper from crispy_forms.layout import … -
Updated via form OnetoOneField - Duplicate key value violates unique constraint
I am creating an app in which a user can create a project and each project has one-and-just-one set of questions (i.e. a form - I called it Firstquestions). I want the user to be able to edit/update this set of questions via a form. However, I get the error: duplicate key value violates unique constraint projects/models.py class Project(models.Model): title = models.CharField(max_length=255) content = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) projects/urls.py urlpatterns = [ #Regarding the projects path('allprojects', views.allprojects, name='allprojects'), path('createproject', views.createproject, name='createproject'), path('<int:project_id>', views.projectdetail, name='projectdetail'), path('<int:project_id>/editproject', views.editproject, name='editproject'), path('<int:project_id>/deleteproject', views.deleteproject, name='deleteproject'), #Regarding the set of questions path('<int:project_id>/', include('firstquestions.urls')), ] firstquestions/urls.py class Firstquestion(models.Model): first_one = models.TextField() first_two = models.TextField() first_three = models.TextField() first_four = models.TextField() first_five = models.TextField() first_six = models.TextField() first_seven = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) firstquestions/urls.py urlpatterns = [ path('questionstoanswer', views.questionstoanswer, name='questionstoanswer'), path('firstquestionsdetail', views.firstquestionsdetail, name='firstquestionsdetail'), path('firstquestionsedit', views.firstquestionsedit, name='firstquestionsedit'), ] MY EDIT FUNCTION firstquestions/views.py @login_required def firstquestionsedit(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': if request.POST['first_one'] and request.POST['first_two'] and request.POST['first_three'] and request.POST['first_four'] and request.POST['first_five'] and request.POST['first_seven']: question = Firstquestion() question.first_one = request.POST['first_one'] question.first_two = request.POST['first_two'] question.first_three = request.POST['first_three'] question.first_four = request.POST['first_four'] question.first_five = request.POST['first_five'] # question.first_six = request.POST['first_six'] question.first_seven = request.POST['first_seven'] question.developer = … -
query filter with namespace and path from url parameters
I have a django rest framework app. I want to pass in two paramters through the url and if they are passed in, I want to then use each of the parameters as a filter in the queryset. So basically. if not parameter is passed, then grab all data for user. if namespace is passed in I want to filter by user and namespace. if path is pased in, I want to filter by user, namespace, and path. RIght now it is not doing that. I have it setup as 3 different urls that go to 3 different viewsets because whne I try to make it a single url it bugs out and does not work at all. I also want namespace and path to be optionally included in the url so the url would work without namepsace and path assigned to it. When i tried a single url it would require both parameters to work.... Urls: router.register(r'preferences', PreferenceUserViewSet, basename='Preference') router.register(r'preferences/(?P<namespace>.+)', PreferenceNamespaceViewSet, basename='Preference-namespace') router.register(r'preferences/(?P<namespace>.+)/(?P<path>.+)', PreferencePathViewSet, basename='Preference-path') viewset: class PreferenceUserViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def … -
Solving NoReverseMatch at /projects/19 in nested urls
I created Django app. The user can create a new project. Once created, each project has a set of 10 macroquestions. Each macroquestion contains a form. The relationship project-macroquestion is OneToOneFiled. The User is showed all the macroquestions for that specific project in projectdetails. Here, the user can: 1) Click on "Answer the macroquestion" so he is redirect to the form (see above) 2) Click on "Edit the macroquestion" which is not working Basically, if the "Edit the macroquestion" is clicked, I want to: {% url 'firstquestionsedit' project.id question.id %} BUT it gives me the error: Solving NoReverseMatch at /projects/19 in nested urls. The project.idis succesfully passed, in fact is 19, but this is not the case for question.id, which is empty. Reverse for 'firstquestionsedit' with arguments '(19,)' not found I think the problem is that question.id is created after. projects/urls.py urlpatterns = [ #Regarding the projects path('allprojects', views.allprojects, name='allprojects'), path('createproject', views.createproject, name='createproject'), path('<int:project_id>', views.projectdetail, name='projectdetail'), path('<int:project_id>/editproject', views.editproject, name='editproject'), path('<int:project_id>/deleteproject', views.deleteproject, name='deleteproject'), #Regarding the set of macro-questions path('<int:project_id>/firstquestions/', include('firstquestions.urls')), ] projects/models.py class Project(models.Model): title = models.CharField(max_length=255) content = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) firstquestions/urls.py urlpatterns = [ path('questionstoanswer', views.questionstoanswer, name='questionstoanswer'), path('<int:question_id>/firstquestionsdetail', views.firstquestionsdetail, name='firstquestionsdetail'), path('<int:question_id>/firstquestionsedit', views.firstquestionsedit, name='firstquestionsedit'), ] firstquestions/model.py class Firstquestion(models.Model): … -
How to calculate total price of a product in models in Django?
I want to calculate total price of products.I am calculating the price in models.py using @property. But the problem I m facing is that the product table is in Product app (models.py) which contains price however the quantity is in the Cart app (models.py). And for total I want to multiply price*quantity. Cart/models.py class CartItem(models.Model): cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True) product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True) accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True) quantity=models.IntegerField(default=1) updated = models.DateTimeField(auto_now_add=True,auto_now=False) line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True,on_delete=models.SET_NULL) product = models.ManyToManyField(Product, blank=True) accessory = models.ManyToManyField(Accessories, blank=True) subtotal = models.DecimalField( default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField( default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True,) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) Product/models.py class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=20, default=0.00) In my Cart/models.py def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) Cart/template.html <tr class="total"> <td>Total</td> <td colspan="4"></td> <td class="num">{{cart.get_total_price|floatformat:"2"}}</td> </tr> But it's displaying the total as 0.00. I have also tried it as: def get_total_price(self): return self.product.price* self.cartitem.quantity But all in vain nothing worked. Please help me in this regard? Note: I have made a function in cart/views.py fro calculating the total. Can i call use that calculation somehow in cart/models.py. Thanks in advance -
Django oauth toolkit is it possible to log in using only client id and secret id?
I have to communicate through REST two internal applications, I don't need to use user credentials. Is it possible to authenticate using only cliend_id and client_secret keys? If this is not possible with OAuth Thanks in advance to all -
question about where self.kwargs come from if it is not defined? specifically in the SingleObjectMixin class in the django code base
I am following a Django tutorial and I am creating a CBV that inherits from (SelectRelatedMixin, DetailView) and I was taking a look at the code base when I reached SingleObjectMixin which has a function called get_object. It sets pk=self.kwargs.get(self.pk_url_kwarg) Where does kwargs attribute come from here? because SingleObjectMixin is only instantiating from one class "ContextMixin" and this does not have that attribute This is a part of the function: def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) -
Dynamically display django form multiple times
I am using django formset to get display django form few times to get information from user. But here the number of times I can display form is fixed. Is there any good way to get display form dynamically, once the user enter the details then display same form again to get more information without refreshing the page. Below is the code currently I'm using. in models.py class Tiers(models.Model): user = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,) tier_name = models.CharField(max_length=128, blank = True) #name of the tier tier_value = models.IntegerField() #Can only be in exact dollar amount tier_benefits = models.CharField(max_length = 5000, blank = True) #creators explain what the donor benefits for each tier in forms.py class TierForm(forms.ModelForm): class Meta: exclude = ['user'] model = models.Tiers TierFormset = modelformset_factory(models.Tiers,form=TierForm, extra=2) in HTML page <!-- {% extends "base.html" %} --> {% load bootstrap3 %} <!-- {% block content%} --> <div class="container"> <h1>Update Your Profile</h1> <form method="post"> {% csrf_token %} {% bootstrap_formset formset %} <input type="submit" class='btn btn-default' value="Update Profile"> </form> </div> <!-- {% endblock%} --> Currently I'm displaying form 2 times but I want to display several depends how tiers user want to use. Thanks! -
Gson ruturns code instead of null in android
I am working on an android project and Django as its backend. The endpoint works fine and it returns an empty array for a certain field "[ ]". When the gson serialize it to kotlin class (in which the field is defined as integer array) it returns this code: [Ljava.lang.Integer;@39da238. I need to perform a null check on this field. -
Context from 'views.py' not showing on 'base.html' - Django
I can't find where is the problem, so I want to create li element for each of my categories. Here are my codes: views.py: def categories(request): context = { 'category_list': Category.objects.all(), } return render(request, 'base.html', context) base.html: <nav id="header-nav"> <ul id="nav-ul" class="menu font-reg clearfix"> <li class="menu-item menu-item-has-children"> <a href="">Blog<span class="sub-drop-icon fa fa-angle-down"></span></a> <ul class="sub-menu sub-menu-first"> {% for category in category_list %} <li><a href="#">{{ category.name }}</a></li> {% endfor %} </ul> </li> <li class="menu-item menu-item-has-children"> <a href="about-1.html">About</a> </li> <li class="menu-item menu-item-has-children"> <a href="contact-1.html">Contact</a> </li> </ul> </nav> -
Problems with the response in API REST django
I try to link django API-REST with a form that has an associated model. Everything works well until I do the: return response.Response (serializer.data, status = status.HTTP_201_CREATED) JavaScript // To Save the Suggestion let ajax_suggestion_save = function (type, url, data, context) { let name_dm = $('#name-db-saved').val(); $.ajax({ type: type, url: url, data: data, context: context, beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, success: function (response) { $.niftyNoty({ type: "success", container: 'floating', title: 'Your information was saved successfully.', message: 'We much appreciate your interest of contact us, part of the growth of this platform it is base on your collaboration through your ideas.', closeBtn: true, timer: 4000 }); }, error: function (response) { if (Object.keys(response.responseJSON).length >= 1) { $.each(response.responseJSON, function (key, value) { $.niftyNoty({ type: 'danger', container: 'floating', title: 'Ups, apparently we have problems saving your information.', message: 'Please check the following ' + 'Error in <strong> ' + key + ' </strong>, with the following error <strong> ' + value + ' </strong>.', closeBtn: true, timer: 4000 }); }); } else { $.niftyNoty({ type: 'danger', container: 'floating', title: 'Ups, apparently we have problems saving your information.', message: 'Ups, apparently we have problems saving … -
How can I get data between for instance 14:00 and 18:00 in Django filter?
> AvailableDate.objects.filter(start_time__gte=start_time, end_time__lte=end_time, status='1') That is the filter method. But it doesn't work -
Django model select players to play
i have Match and Game table, i want to choose players who will play in this match (bacause a team include more than 5 players. However a match play 5vs5) class Match(models.Model): name=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) team1=models.ForeignKey('Team',related_name='team1',on_delete=models.PROTECT) team2=models.ForeignKey('Team',related_name='team2',on_delete=models.PROTECT) class Game(models.Model): name = models.CharField(max_length=255) match = models.ForeignKey(Match, on_delete=models.CASCADE) team1players=models.ManyToManyField(match.team1.player.all()) team2players=models.ManyToManyField(match.team1.player.all()) Error: 'ForeignKey' object has no attribute 'team1' -
'0' In Routing path is causing NoReverseMatch error
I have the following URL route defined: url( regex=r'^edit_meal/(?P<menu_item_id>\d+)/(?P<parent_item_id>\d+)/$', view=EditMealView.as_view(), name='edit_meal', ) When I pass the following URL, it gets the error posted just below it: http://localhost:8000/menu_manager/edit_meal/0/5/ Reverse for 'edit_meal' with arguments '(0,)' not found. 1 pattern(s) tried: ['menu_manager/edit_meal/(?P<menu_item_id>\\d+)/(?P<parent_item_id>\\d+)/$'] However, if I change the '/0/5/' to '/1/5/' (or any number other than '0'), it works fine. Also, if I use '/1/0/', there is no issue. How can I get the router to accept '0' in the first argument? Tag in template: {% url 'menu_manager:edit_meal' 0 menu.id %} -
django Static files in production server
my problem is with static files (img , styles)...my code working fine with no error with static files and the images appears when i run the server , but when i make the (debug = False) the images and styles disappear i ran my code on linux server ubntu.... how i make the static files appear with the (debug=false) ...thanx in settings.py that is my code STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'music/templates/'), ) in my html file the image tage is just like this <img src="{% static 'music/login.jpg' %}" width="300" height="300"> -
How to send a email from a form django
As the title says i am trying to send a email from a form, but is not working: As you can see: <form method="POST" action=''> {% csrf_token %} <div class="control-group form-group"> <div class="controls"> <label>Nombre completo:</label> <input type="text" class="form-control" id="nombre" required data-validation-required-message="Introduzca su nombre."> <p class="help-block"></p> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Asunto:</label> <input type="text" class="form-control" id="asunto" required data-validation-required-message="Introduzca el asunto del correo."> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Correo Electrónico:</label> <input type="email" class="form-control" id="email" required data-validation-required-message="Introduzca su correo electrónico."> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Mensaje:</label> <textarea rows="10" cols="100" class="form-control" id="contenido" required data-validation-required-message="Escriba su mensaje" maxlength="999" style="resize:none"></textarea> </div> </div> <button type="submit" class="btn btn-primary">Enviar mensaje</button> </form> This is my view: def contact(request): contactdata = contactData.objects.get() members = teamMembers.objects.filter(existencia=True) templates = Templates.objects.get(isSelected=True) categoria = Clasificacion.objects.filter(existencia=True) enterprise = enterprisedata.objects.get() content = request.POST.get('contenido', '') name = request.POST.get('nombre', '') email = request.POST.get('email', '') subject = request.POST.get('asunto', '') if request.method == 'POST' and email and name: send_mail(subject, content, email, ['kike1996@hotmail.com'], fail_silently=False) contexto = {'categoria':categoria,'templates':templates,'members':members, 'contactdata':contactdata,'enterprise':enterprise} return render(request, 'contact/contact.html', contexto) I am calling the form with the POST request, but is not sending anything!. Hope you can help me, thank you!. -
How to create a follow-system in Django 2
I am trying to create a following system, where users can see each others posts on their timeline. But i'm stuck on the follow system. I've tried to use a ManyToManyField class Friends(models.Model): users = models.ManyToManyField(User) I expect it to let me follow other people. -
id of my user table is increased unnaturally
I am using graphene-django library and I have a User model that is inherited from AbstractUser. The username attribute is unique and it's ok for me. But The problem is that when I try to add a user with duplicated username id of user table in database increases. What's your idea? -
Django Custom Management: trouble in writing command to pupulate data
I am new to django management commands! I am trying to write a commands to populate author... My models.py is: from django.db import models class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField(unique=True, blank=False, null=False) class Book(models.Model): book_name = models.CharField(max_length=10) summery = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) and i am tried to write a command but i failed.. this is my blog/management/commands/populate_author.py below: from django.core.management.base import BaseCommand, CommandError from blog.models import Author, Book class Command(BaseCommand): help = 'Populate author' def add_arguments(self, parser): def handle(self, *args, **options): Can anyone please help me to make it happen? -
Unusual behavior of form during the creation of a blog post and during the update of itself
I'm developing the backend of my personal blog and, using this tutorial for the date and time, I've created a form for the creation of a blog post. I notice two things: Even if I select one or more tags, they aren't added to the post. The post after the pubblication using this form doesen't have tags. But if I do the same thing via django admin I can't create a post without the tags. If I try to update an existing post the publishing date field is blank into the form but I can see the publication date in the details of the post. create_post.html <form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %} <div class="form-group"> <div class="row"> <div class="col-sm-9"> <div class="form-group mb-4"> <div>{{ form.title }}</div> <label for="id_title"> <span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.title.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.description }}</div> <label for="id_description"> <span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.description.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.contents }}</div> <label for="id_contents"> <span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.contents.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.header_image_link }}</div> <label …