Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CreateView Model Form not uploading File
the problem that I have is that my Model Form is not uploading a file, I had it working and after adding more code now is not working. It uploads all the other fields except for the file, the strange thing is that if I do it from the admin site it does work. models.py class Polizas(models.Model): nombre = models.CharField(max_length=30, blank=True, null=True) numero = models.CharField(max_length=30, unique=True) aseguradora = models.CharField(max_length=20, blank=True, null=True) carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=True, null=True) inicio_poliza = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) fin_poliza = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) documento = models.FileField(upload_to='polizas/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Polizas" ordering = ['nombre'] def __str__(self): return self.nombre def get_absolute_url(self): return reverse('polizas') forms.py class PostPolizas(forms.ModelForm): class Meta: model = Polizas fields = ('nombre', 'numero', 'aseguradora', 'carro', 'inicio_poliza', 'fin_poliza', 'documento') widgets = {'inicio_poliza': forms.DateInput(attrs={'type': 'date'}), 'fin_poliza': forms.DateInput(attrs={'type': 'date'}) } views.py class PolizaCreate(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'redirect_to' form_class = PostPolizas template_name = "add_insurance.html" Terminal [06/May/2020 22:32:17] "POST /insurance/add/ HTTP/1.1" 200 4557 [06/May/2020 22:32:25] "POST /insurance/add/ HTTP/1.1" 302 0 I have tried to validate the form and it is not working, this is error is happening in my other model forms that upload … -
django local variable 't' referenced before assignment
I saw this was a common error and I did look through other post, but they did not help me. I am getting the error Exception Value: local variable 't' referenced before assignment But my t variable is declared 3 lines above where it is saying it is not, inside my if validation. Scope should be fine for my return. function in question: def create(response): #response.user if response.method == "POST": form = CreateNewTrade(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = AssetList(name=n) t.save() response.user.assetlist.add(t) return HttpResponseRedirect("/userdash/%i" %t.id) #we fail at this t variable complete code: $ cat userdash/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import AssetList, Items from .forms import CreateNewTrade # Create your views here. #def index(response): # return HttpResponse("<h1>Hello Dark World!</h1>") def userdash(response, id): ls = AssetList.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("save"): for item in ls.items_set.all(): if response.POST.get("c" + str(item.id)) == "clicked": item.sell_asset = True else: item.sell_asset = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: #this validation is retarded and needs to be fixed ls.items_set.create(user_asset=txt, sell_asset=False) else: print("invalid") #items = ls.items_set.get(id=1) #return HttpResponse("<h1>User Dashboard!</h1><h2>%s</h2><br></br><p>%s</p>" %(ls.name, str(items.user_asset))) return render(response, "userdash/list.html", {"ls":ls}) def home(response): #pass return render(response, "userdash/home.html", {}) def … -
How to add data in table dynamically in django?
I have following two models in my models.py. class Book(models.Model): book_id = models.AutoField book_name = models.CharField(max_length=50) book_author = models.CharField(max_length=50) book_category = models.CharField(max_length=50) class Author(models.Model): author_id = models.AutoField author_name = models.CharField(max_length=50) author_description = models.CharField(max_length=500) So whenever I add new row in Book table, it automatically do entry in Author table ( Only author_id and author_name, author_description i will add manually ). How to do it? -
Django Rest Framework API POST receiving status code 200 instead 201
I am new to Django and python. I have a website that already in production using docker. And the API URL is on: http://gmlews.com/api/data. When I want to test the API using postman, the GET method working fine, but for the POST method is returned response 200 OK not 201 created. Because of that, my data can't be saved in the API. Here is my code for the API : restapi/serializers.py: from .models import Data,Node from rest_framework import serializers class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class NodeSerializer(serializers.ModelSerializer): class Meta : model = Node fields = '__all__' restapi/views.py: import json from django.views.generic import View from django.shortcuts import render from rest_framework import routers, serializers, viewsets from rest_framework.response import Response from restapi.serializers import DataSerializer, NodeSerializer from restapi.models import Data, Node from django_filters.rest_framework import DjangoFilterBackend from django.http import HttpResponse from rest_framework.views import APIView # Create your views here. class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = DataSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['node_id'] class MapViewSet(viewsets.ModelViewSet): queryset = Data.objects.filter(node_id=1).order_by('-id')[:1] serializer_class = DataSerializer class NodeViewSet(viewsets.ModelViewSet): queryset = Node.objects.all() serializer_class = NodeSerializer Can someone help me with this issue? I really don't have an idea why the POST method received status 200. I want … -
I want to show some news in my index page
I am working in a Django project in which a user would need to create an account and register to get some functionality of the web app, so for each user when they log in i would like to show some news of the day or something like so, i would like to know which way would you recommend to use, web scrapping or use any API like cnn or something related to news? Or if there is a better way to do this task which one would you recommend? -
NoReverseMatch at / Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<article_id>[0-9]+)$']
for some reason I cannot seem to solve this bug. I am using Django 3.0.5 The actual error I get is NoReverseMatch at / Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<article_id>[0-9]+)$'] In my project dir I have this urls.py from django.urls import path from . import views urlpatterns = [ path('', views.presse, name='listings'), path('<int:article_id>', views.article, name='article'), ] My view looks like this def article(request, article_id): article = get_object_or_404(Article, pk=article_id) context = { 'article': article } return render(request, 'article/article.html', context) and my html is <h4 class="uk-margin-small-bottom"><a href="{% url 'article' article.id %}"> -
What is the most efficient way to store images feature vector?
I'm working on project that needs to deal with images, I extract their feature vector instantly when any image uploaded then I store the feature vectors in MySQL database as text per each image. Also I'm using django framework. def search_images_by_features(query_image: ImageFieldFile, images): featured_images = [ (calculate_similarity(load_features_from_str(image.features), get_image_feature(query_image)), image.item) for image in images if image.features is not None] ... But looping on each image isn't a big deal as it takes more time as images increase. Also my feature vector in database stored like that: 0.0010601664,0.0003533888,0.8969008,0.0014135552,... Also is there a way to make MySQL database engine calculate similarity from feature vectors? -
DJANGO : How can i use fieldsets in forms.py
How can i use fieldsets in form.py i need to use like this in forms.py fieldsets = [ ( '', { 'fields': ['paysPartenaires', 'instrumentJuridique',('partenaire','gouvernement','paysP','etat','adefinir'),'objet', 'axeCooperation'] }), ('Autres élements à rajouter ?', { 'fields': ['infoPlus', ] }), ('', { 'fields': [ 'acteJuridique',('dateSignature','dateEntreeVigueur' ),('duree','dureeplus5ans', 'renouvellement'), ('pays', 'villeSignature')] }), ('Base Documentaire', { 'fields': [], 'description': 'Joindre le(s) fichier(s) '}), ] ``` -
Why is the "on_update" option not present in Django Relationship fields?
I'm using Django 3.0 + MariaDB. I've created a models.py from an existent database with the "python manage.py inspectdb > models.py" command. I need now to set the options for the Foreign Keys. As you know in a database you can have multiple options for the Foreign Keys: the first classic is "ON_DELETE" and the second is 'ON_UPDATE' (You can even have more options in PostgreSQL). In Django, there is just an "on_delete", but no "on_update" option, what I found very surprising. I found nothing on the official documentation about this. Neither on some old posts with the same question, the responses were not conclusive and focused on the "on_delete". I'm asking about the "ON_UPDATE' option, nothing else. So, where is this option, or why is it not present in Django's ORM ? -
moving Django Project from windows to Mac migration
I moved my project from my windows machine to Mac using GitHub when I run python manage.py runserver it worked fine showing my login page and since I didn't do any migration the app crashed, so I executed python manage.py makemigrations I thought this will solve the problem but after that when I am trying to runserver I am getting the dejango home page also all my clasess are Undefined undefined class issue Django Home Page and my database which is postgresql not showing any of my models in the table and make migrations showing below error every time after that and ython manage.py migrate showing below Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. No changes detected setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'xadmin', 'django_filters', 'crispy_forms', ] database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'crashDB', 'USER': 'postgres' , 'PASSWORD': '1234', 'HOST': 'localhost', } } what is the issue in here ?? and what is the best way to move my project from windows to Mac ? -
Django DateTimeField Doesn't Translate Time While Saving To Db
I have a Django model named "Event". class Event(models.Model): screen_name=models.CharField(max_length=256) description=models.TextField(max_length=512) date_time=models.DateTimeField() Everyhing looks nice, and I see the datetime picker on the Admin interface. My settings.py has the following: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True My question is: My browser time is 2 hours ahead of the server time. When I pick a date and time (e.g 05:00:00), it is saved in the Db as 05:00:00. The Db record does not keep record of the timezone. As far as I know, Django considers DB records as UTC strings. I want it to be translated from my timezone (GMT +2) to (UTC) before saving it to the Db. (e.g 03:00:00) What am I doing wrong? I would be glad if you help me solve this. Thanks! -
Login Authentication - Django
I am having a really hard time trying to understand the following: I am new to web development and i use django for my project, i already added the @login_required decorator to the views that need an authenticated user to show up, everyhting works fine until there, but when i hit the logout button which redirects me to the index page of the webapp and i hit the back arrow of the navigator again, everything that must need to show up only if there is a user authenticated shows up again, i don't think that is the correct behavior of django or what am i doing wrong? Is there any other decorator or function call i must do so that this doesnt happen anymore? -
Django Select2 not working on all fields in form
MODEL class VeriEnvanteri(models.Model): Departman = models.ForeignKey(Departman, on_delete=models.CASCADE,verbose_name="Departman") Faaliyet = models.ForeignKey(Faaliyet, on_delete=models.CASCADE,verbose_name="Faaliyet") VeriKategorileri = models.ForeignKey(VeriKategorileri, on_delete=models.CASCADE,verbose_name="Veri Kategorileri") KisiselVeri = models.ForeignKey(KisiselVeri,null=True,blank=True, on_delete=models.CASCADE,verbose_name="Kişisel Veri") OKisiselVeri = models.ForeignKey(OKisiselVeri, null=True,blank=True,on_delete=models.CASCADE,verbose_name="Özel Nitelikli Kişisel Veri") VeriIslemeAmaci = models.ForeignKey(VeriIslemeAmaci, on_delete=models.CASCADE,verbose_name="Veri İşleme Amacı") VeriKonusuKisiGruplari = models.ForeignKey(VeriKonusuKisiGruplari, on_delete=models.CASCADE,verbose_name="Veri Konusu Kişi Grupları") HukukiSebebi = models.ForeignKey(HukukiSebebi, on_delete=models.CASCADE,verbose_name="Hukuki Sebebi") VeriSaklamaSuresi = models.ForeignKey(VeriSaklamaSuresi, on_delete=models.CASCADE,verbose_name="Veri Saklama Süresi") Deger = models.CharField(max_length=1000,verbose_name="Değer", default='') VeriAktarimAlicilari = models.ForeignKey(VeriAktarimAlicilari, on_delete=models.CASCADE,verbose_name="Veri Aktarım Alıcı Grupları") YabanciUlke = models.ForeignKey(YabanciUlke, on_delete=models.CASCADE,verbose_name="Yabancı Ülkelere Aktarılma Durumu") IdariTedbirler = models.ForeignKey(IdariTedbirler, on_delete=models.CASCADE,verbose_name="Idari Tedbirler") TeknikTedbirler = models.ForeignKey(TeknikTedbirler, on_delete=models.CASCADE,verbose_name="Teknik Tedbirler") Kurum = models.ForeignKey(KurumBilgileri, on_delete=models.CASCADE,verbose_name="Kurum Adı",default=1) IslemTarihi = models.DateTimeField(auto_now_add=True,verbose_name="İşlem Tarihi") FORM class VeriEnvanterForm(forms.ModelForm): class Meta: model = VeriEnvanteri fields = ['Departman','Faaliyet','VeriKategorileri','KisiselVeri','OKisiselVeri','VeriIslemeAmaci','VeriKonusuKisiGruplari','HukukiSebebi','VeriSaklamaSuresi','Deger', 'VeriAktarimAlicilari','YabanciUlke','IdariTedbirler','TeknikTedbirler'] widgets = { 'Departman' : s2forms.Select2Widget , 'Faaliyet' : s2forms.Select2Widget , 'VeriKategorileri' : s2forms.Select2Widget , 'KisiselVeri' : s2forms.Select2Widget , 'OKisiselVeri' : s2forms.Select2Widget , 'VeriIslemeAmaci' : s2forms.Select2Widget , 'VeriKonusuKisiGruplari' : s2forms.Select2Widget , 'HukukiSebebi' : s2forms.Select2Widget , 'VeriAktarimAlicilari' : s2forms.Select2Widget , 'IdariTedbirler' : s2forms.Select2Widget , 'TeknikTedbirler' : s2forms.Select2Widget } Select2 widget only work for KisiselVeri and OKisiselVeri. I cant figure out. -
Writing an efficient node.all_siblings_leaf() method for django-mptt
I have a tagging system, where the tags exist in a hierarchy. I've used django-mptt to build the Tag model. I want to display a group of tags differently if every sibling in the group is a leaf node. To do this, I want a model method called all_siblings_leaf(). Here's my first take on that method: def all_siblings_leaf(self): """Return True if all siblings, including self, are leaf nodes.""" siblings = self.get_siblings() return all([sibling.is_leaf_node() for sibling in siblings]) This works, but it's one trip to the db for the get_siblings() call. When I want to call all_siblings_leaf(), I've already queried for all the tags I want to use. Using this method repeatedly with a set of several hundred tags means several hundred new db calls. Since I already have all the tags, I feel like I should be able to get the information about leaf nodes without any additional trips to the db. Here's what I've come up with: def all_siblings_leaf(self, all_tags): """Return True if all siblings including self are leaf nodes. all_tags should be a queryset that used select_related('parent') """ if self.level == 0: siblings = [t for t in all_tags if t.level == 0] else: siblings = [t for … -
Django OneToOneField is causing IntegrityError at /submissions/submit/ NOT NULL constraint failed: submissions_submissiondata.submission_code_id
I'm trying to implement a model in such a way that a User can have multiple submissions, and a Submission has only one object of type SubmissionData. On the template, user will upload a PDF file, this PDF will be parsed, some info associated with that submission will be stored in the SubmissionData, and the file and some main information will be associated with the SubmissionData here is the models.py: class Submission(models.Model): submission_user = models.ForeignKey('auth.User', related_name='submissions', on_delete=models.CASCADE) submission_file = models.FileField(upload_to='media/') created_at = models.DateTimeField(auto_now=True) def __str__(self): user_submission = str(self.submission_user.username).lower() user_submission = user_submission + '/' + str(timezone.now()) return user_submission class Meta: ordering = ['-created_at'] class SubmissionData(models.Model): submission_code = models.OneToOneField(Submission, related_name='data', on_delete=models.CASCADE) uuid = models.CharField(max_length=250, null=True) patiente_name = models.CharField(max_length=250, null=True) patiente_age = models.PositiveIntegerField(null=True) patient_gender = models.CharField(max_length=20, null=True) and on my views.py: class SubmissionCreateView(CreateView, LoginRequiredMixin): form_class = SubmissionForm template_name = 'submissions/submission_create.html' success_url = reverse_lazy('submissions:list') def proccess_submission_data(self): parser = PDFParser('path-to-pdf').parse() data_obj = parser.get_result() submission_data = self.enconde(data_obj) self.object.save() submission_data.save() def enconde(self, data_obj): submission_data = SubmissionData(submission_code=self.object, uuid=data_obj.uuid, patiente_name=data_obj.patiente_name, patiente_age=data_obj.patiente_age, patient_gender=data_obj.patient_gender) return submission_data def form_valid(self, form): self.object = form.save(commit=False) self.object.submission_user = self.request.user self.proccess_submission_data() return super().form_valid(form) For some reason I'm getting the following error: And the error is triggered on those lines: Does anyone know what could be causing … -
how to show variations Sizes of Products in Django Admin
I have finally added variations to my order items so now I add items with different sizes S,M and L When I add the variations to the admin to be displayed it comes back with ERRORS: <class 'core.admin.OrderItemAdmin'>: (admin.E109) The value of 'list_display[3]' must not be a ManyToManyField. So how show i show the Size variation in the admin: here is the models: class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size',), ('color', 'color',), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) objects = VariationManager() updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) def __str__(self): return f"{self.quantity} of {self.item.title}" and here is the admin.py class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'billing_address', 'out_for_delivery', 'received', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'billing_address', 'payment', 'coupon' ] -
<bound method class.method of <Class: >>
This is my models.py: Class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return "%s %s" % (self.first_name, self.surname) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}'s profile" def full_name(self): return f"{self.first_name} {self.surname}" class Composition(models.Model): title = models.CharField(max_length=120) composer = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f"{self.title} {self.composer.full_name}" I can't understand why I'm getting Title <bound method Profile.full_name of <Profile: MyName's profile>> in the Django admin site, in the list of compositions' titles. Calling self.composer.full_name() only gets me two <bound method...> items. Can someone please help me? I've been battling with this for a while now and I'm stuck. -
Unable to set custom Django user model to is_active
I recently created a custom user model in a Django 1.11 project. It's tied into Django Registration and overall is working well. However, I get an error when trying to set a user as 'active' in the admin panel. The error I get is: normalize() argument 2 must be str, not None With the error generated due to this function: class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super(UsernameField, self).to_python(value)) Here is my customer user model: from django.conf import settings from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField('email address', unique=True) first_name = models.CharField('first name', max_length=30, blank=True, null=True) last_name = models.CharField('last name', max_length=150, blank=True, null=True) username = models.CharField('username', max_length=150, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = 'user' verbose_name_plural = 'users' Here is the form I use when saving new users: from django import forms from django_registration.forms import RegistrationForm from users.models import User class CustomRegistrationForm(RegistrationForm): # remove password confirmation def __init__(self, *args, **kwargs): super(CustomRegistrationForm, self).__init__(*args, **kwargs) self.fields.pop('password2') first_name = … -
How to write image source in javascript with image name obtained from Django AJAX call
I have an image name "not the complete file path" obtained from Django AJAX call. The object has so many values. I return json object. Then, I purse it to process it in javascript. I have some errors in the following: $(document).on('click', '#post-det', function(e) { e.preventDefault(); var post_id = $(this).children(':first-child').text(); var post_id = parseInt(post_id); $.ajax({ type: "GET", url: "{% url 'get_post_details' %}", dataType: "json", data: { "post_id": post_id }, success: function(data) { alert(data); post_details(data); } }); }); function post_details(details) { var json = JSON.parse(details); var userusername= $('#user-username').text(json.user_username); alert(json.title); var post_images = $('#post-imgs').html(''); // RESET THE images div alert(json.images[0].image); for( var i = 0; i < json.images.length; i++) { post_images.html('<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">'+ '<ol class="carousel-indicators">'+ '<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>'+ '<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>'+ '<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>'+ '</ol>'+ '<div class="carousel-inner">'+ '<div class="carousel-item active">'+ '<img src='".."+"/"+".."+"/"+".."+"/"+".."+"/"+"media"+"/"+json.images[0].image+' class="d-block w-100" alt="...">'+ '</div>'+ '</div>'+ '<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">'+ '<span class="carousel-control-prev-icon" aria-hidden="true"></span>'+ '<span class="sr-only">Previous</span>'+ '</a>'+ '<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">'+ '<span class="carousel-control-next-icon" aria-hidden="true"></span>'+ '<span class="sr-only">Next</span>'+ '</a>'+ '</div>'); } } I have error in the following line '<img src='".."+"/"+".."+"/"+".."+"/"+".."+"/"+"media"+"/"+json.images[0].image+' class="d-block w-100" alt="...">'+ Any help or suggestion will be highly appreciated. I prefer the solution to be in the javascript side NOT in Django. I could alert the … -
Django CSRF protection, gives 200 ok response even though I didn't provide csrf token
didn't provide {% csrf_token %} in template, yet the http response is 200 ok, shouldn't be 403 forbidden ?! setting.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] url.py urlpatterns = [ path('admin/', admin.site.urls), path("formtest", view.formPostTest), ] template formPostTest.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <form class="" action="/formtest" method="post"> <label for="username">username: </label><input type="text" name="username" value=""> <label for="password">password: </label><input type="password" name="password" value=""> <input type="submit" name="submit" value="submit"> </form> </body> </html> view.py def formPostTest(request): if request.method == "GET": cont = {} return render(request, "formPostTest.html", cont) elif request.method == "POST": return HttpResponse("done") not only that I tired to do every thing to miss it up, I tampered with the csrftoken cookie network monitor screen shot it alaways give 200 ok resopnse no matter what the only problem it give in console console Forbidden (CSRF cookie not set.): /formtest Forbidden (CSRF cookie not set.): /formtest [07/May/2020 02:21:07] "POST /formtest HTTP/1.1" 200 4 and some times this instead Forbidden (CSRF token missing or incorrect.): /formtest [07/May/2020 02:28:44] "POST /formtest HTTP/1.1" 200 4 django version 2.0.5, python version 3.6.5 -
Delete posts on profile django
I have been working on a project and one of the functions that it has it to delete posts, when in the imagelist view, I am able to delete those posts but when I am in the profile view which shows the user's posts when I try to delete it, a 404 error page not found shows up. I dont know where the error is but I think it is on the profile view. views.py def profile(request, pk=None): if pk: post_owner = get_object_or_404(User, pk=pk) user_posts=Post.objects.filter(user_id=pk) else: post_owner = request.user user_posts=Post.objects.filter(user_id=pk) return render(request, 'profile.html', {'post_owner': post_owner, 'user_posts': user_posts,}) profile.html <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ post_owner.username }}</h2> <p class="text-secondary">{{ post_owner.email }}</p> </div> </div> <div> {% for Post in user_posts %} <li class="list-group-item">{{ Post.text }} <a href="{% url 'profile_pk' pk=Post.user.pk %}">{{ Post.user }}</a> {% if Post.posti %} <img src="{{ Post.posti.url }}" alt="image here" style="max-width: 300px; max-height: 300px"> {% endif %} {% if Post.user == user %} <div class="float-right"> <form action="delete_image/{{ Post.id }}/" action="post"> <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button> </form> </div> {% endif %} </li> {% endfor %} </div> </div> urls.py urlpatterns = [ path('profile/<int:pk>/', views.profile, name='profile_pk'), path('imagepost', views.uimage, name='image'), path('imagelist', views.imagelist, name='imagelist'), path('delete_image/<int:image_id>/', views.delete_image, … -
Django doesn't recognize CSS import variables
I have two CSS files in my static folder. One is called typography.css. This CSS file has @import url("variable.css") where multiple variables are stored. How do I get Django to recognize the variable.css file? -
Django Database Structure for Users in Teams
This is probably a very easy question. I want to create the following functionality in django. Someone can create a team and add people to the team. So, at any point, there could be several teams with several users in them. The team data structure has CRUD capabilities. Kind of like github teams. What would be the best database structure for this? I know there are many ways - so what are the advantages and disadvantages of each way?! New to this so really appreciate any questions. -
Django how to not change address while changing the results
I am designing calendar application using Django. It has calendar, and next/prev month button to move between months. But if I connect a views to the buttons, URL changes each time I click on it : If I click prev month button, the url will be something like this : http://my.site/prev_month But I want to just refresh the calendar not changing the address, after clicking the buttons. Is there way I can solve my problem? thanks. -
Django - OneToOneField keeps returning None
My OneToOneField Keeps returning None. I try to go to my site so a form can automatically put the author of the post as the current logged in person. I looked around and saw OneToOneField could do this. It keeps returning None when I in fact have Users in the User model. What on Earth is going on? Models.py: - This is where the main problem is happening from django.db import models from datetime import datetime from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.conf import settings from django.contrib.auth import get_user_model class MainPost(models.Model): post_author = models.OneToOneField(User, on_delete=models.CASCADE) post_title = models.CharField(max_length=200) post_content = models.TextField() post_published = models.DateTimeField("date published", default=datetime.now()) def __str__(self): return self.post_title class MainPostForm(ModelForm): class Meta: model = MainPost fields = ["post_title", "post_content", "post_author"] readonly_fields = "post_published" Views.py - The Important thing is create_request() at the bottom from django.shortcuts import render, redirect from django.shortcuts import render, redirect from django import forms from django.http import HttpResponse from django.views.generic import CreateView from django.contrib.auth.forms import AuthenticationForm from .models import MainPost, MainPostForm from .forms import NewUserForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from datetime import datetime def homepage(request): return render(request, template_name="trymysite/home.html", …