Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I solve - column libman_llrguides.id does not exist
I have a model in my django app as shown below... class LLRGuides(models.Model): title = models.CharField(max_length=40) heading = models.CharField(max_length=60) body = models.TextField(default='Type the description of the guide here') I manually created the table in my databse thro' the pg_admin, manually added the columns. The problem comes in when I try to create an instance of the model, it complains of id column not being present. null value in column "id" of relation "libman_llrguides" violates not-null constraint DETAIL: Failing row contains (d, d, Type the description of the guide here, null). This is the sql that created the id field in the pg_Admin ALTER TABLE IF EXISTS public.libman_llrguides ADD COLUMN id integer NOT NULL; -
Generate file from Base64 encoded django file read
During a file upload, i decided to read the file and save as base64 until s3 becomes available to our team. I use the code below to convert the file to bs64. def upload_file_handler(file): """file -> uploaded bytestream from django""" bs4 = base64.b64encode(file.read()) return {'binary': bs4, 'name': file.name} I store the binary derived from the above in a str to a db. Now the challenge is getting the file back and uploading to s3. I attempted to run bs64.decode on the file string from the db and write to a file. But when i open the file, it seems broken, I've attempted with breakthrough. q = Report.objects.first() data = q.report_binary f = base64.b64decode(data) content_file = ContentFile(f, name="hello.docx") instance = TemporaryFile(image=content_file) instance.save() This is one of the files i am trying to recreate from the binary. https://gist.github.com/saviour123/38300b3ff2c7a0d1a01c15332c583e20 How can i generate the file from the base64 binary? -
Python, Heroku: Why isn't the file hosted?
So, I was building a Django app, I created an intro field for a post formular, I did that in my models.py file: class Post(models.Model): title = models.CharField(max_length=100) intro = models.CharField(max_length=1024) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('donut-post-detail', kwargs={'pk': self.pk}) I renamed 'description' into 'intro' so, when I did the makemigrations command it maked me a file named: 0002_rename_description_post_intro.py I deleted this file and the inital migration for recreating one, hosted it on heroku and did the python manage.py migrate command but it told me that there was no migrations to apply: I don't understand why. When I go back to the website it shows me this: -
Creating a simple password protected Django app to display Folders/Text Files
I would like to ask this question before I start going down unnecessary rabbit holes. What I want to achieve: Create a simple Django Application that only shows a login form when opening the url. After login (no user registration required, I just want to use it for myself), I want to be able to access my files. Files/Folders: I need to look at a ton of data coming from reconaissance from Bug Bounty Programs. So there are a lot of text files and folders. What would be a good way to display them with Django? Think: -ProjectFolder -Subfolder1 -file1.txt -Subfolder2 -SubSubFolder2 -file1.txt -Subfolder3 Would be great if I could get some pointers on an easy way on how to acheive this! :) -
returning user instead of True or False in Django Permission class
I have a custom permission class which I am importing in one of the views. In that permission class, I am using return user instead of True or False. But it seems to be working. But I dont really understand why. The class is as follows: class ExamplePermission(BasePermission): def has_permission(self, request, view): user = CustomUser.objects.filter(user=request.user).first() if view.action == 'list': return user elif request.method == 'POST' or 'PATCH' or view.action == 'destroy' or 'update': return user and user.user_type == ADMIN else: return False Here in above permission class , I am returning user in some places instead of boolean true or false. What is the meaning of returning user? How it is still working?? -
return empty form django
i have a form fill for register but when i try to save it it involves a none object. the problem is : The view pages.views.essai didn't return an HttpResponse object. It returned None instead. here is my code : views.py from django.shortcuts import redirect, render from django.template import RequestContext from .models import Login def essai(request): if not request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') data = Login(username,password) print(data) return render(request,'pages/essai.html') urls.py from django.urls import URLPattern, path from . import views urlpatterns = [ path('essai', views.essai, name = 'essai'), ] essai.html <form action="" method ="POST" > {% csrf_token %} <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value ="Save"> </form> admin.py from django.contrib import admin from .models import Login admin.site.register(Login) model.py from django.db import models class Login(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) PS : I tried with the forms but it's the same problem. I do not understand where is the problem is it the views or the model -
django model based forms - why isn't form valid?
I'm trying to make model based form but something went wrong. model: class Topic(models.Model): name = models.CharField(max_length=200) icon = models.ImageField(upload_to = 'images/') form: class TopicCreationForm(ModelForm): class Meta: model = Topic fields = '__all__' view: def TopicCreateView(request): form = TopicCreationForm() if request.method == 'POST': form = TopicCreationForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: print('aaa') # It displays in console context = {'form':form} return render(request, 'blog/topic_form.html', context) where did i make mistake ? -
How to cache QuerySet in Django
I am starting with my web application in Django. I tried to do some optimilization and loaak at queries and loading time. I did some refactor with select_related or prefetch_related, but I get stacked. I have some structured ratings according to object which is assigned to. I need on every level in structure (Employee, Team, Company..) do some calculations with ratings data. I have created class method in every model and filtered relevant ratings according to object which it belongs to. def get_ratings(self): employee_projects = EmployeeManagement.objects.filter(employee=self) feedbacks = Feedback.objects.filter(rate_for__in=employee_projects) ratings = Rating.objects.filter(feedback__in=feedbacks) return ratings I use data from this method in many place as input for calculations as property in model. But problem is that every time I call this method, query is created into DB. I think I would need some kind of cache, but when I tried to decorate as property, exception was thrown : 'QuerySet' object is not callable. Next issue I have is connected with number of instances of same object. Every instance has unique values and place in structure and returned ratings is different, but is not posible with large amount of instances doing query for each of that. So when I have 10 instances … -
Django Issue on Docker
I am running the Django rest framework and it is running fine but > when It goes to docker then I see this issue. Is anyone knows how to resolve the issue? I am searching on the internet but did not find any solution, anyone who encounters the same issue? Attaching to jdx_web_1 web_1 | Watching for file changes with StatReloader web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.10/threading.py", line 946, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run web_1 | autoreload.raise_last_exception() web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception web_1 | raise _exception[1] web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute web_1 | autoreload.check_errors(django.setup)() web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate web_1 | app_config.import_models() web_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models web_1 | self.models_module = import_module(models_module_name) web_1 | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module web_1 | … -
Ucenik matching query does not exist
I have a problem in views.py: def profil(request, pk): context = { 'profesor': Profesor.objects.get(id=pk), 'ucenik': Ucenik.objects.get(id=pk), } return render(request, 'profil.html', context) when i go to page i got this error: Ucenik matching query does not exist. my url.py: path('profesor/', views.profesor, name='profesor'), path('ucenik/', views.ucenik, name='ucenik'), path('profil/<str:pk>/', views.profil, name='profil'), if i delete: 'ucenik': Ucenik.objects.get(id=pk) then work, but on my profil.html page i need to display details Prfesor model and Ucenik model, i need both of them in def profil -
hey can anyone help me with this i am new to django,how can i get the user details using the token authentication when the message is created
Authenticate the user using token authentication. (NOT JWT Token) There's a quota of 10 messages per hour per user. After a successful message creation, return the message object (JSON) in the response. Example: { "id": 102, "message": "Lorem ipsum", "created_at": "created time in UTC", "updated_at": "last updated time in UTC", "created_by": { "id": 3, "username": "testuser", "email": "test@mail.com", ... } } In case of any error, return the error message. -
Need help saving a base64 image to django image field
i am working on a django project which returns a base64 encoded image and i want to save the image to the django image field.however i am missing something and would appreciate any help. Here is the model: class Catalogue(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=True) description = models.CharField(max_length=255, blank=True) image_link = models.CharField(max_length=255, blank=True) image = models.ImageField(blank=True, null=True, default=None) def save(self, *args, **kwargs): self.name = self.products.name self.description = self.products.description super(Catalogue, self).save(*args, **kwargs) def __str__(self): return str(self.products) in views.py which i am getting the image from an api cat_name = [] for e in Catalogue.objects.all(): cat_name.append(e.name) print(cat_name) for prod_id in cat_name: print(prod_id) image_url = f"API URL HERE" b64 = requests.get(image_url, headers=headers).json() b64_img_code = b64['data'] Catalogue.image = base64_to_image(b64_img_code) Catalogue.save() messages.success(request, "Product Added") return redirect('home') This is the utils file that am decoding the passed base64 string: def base64_to_image(base64_string): return ContentFile(base64.b64decode(base64_string), name=uuid4().hex + ".png") Thanks again in advance -
Django Celery Periodic task is not running on mentioned crontab
I am using the below packages. celery==5.1.2 Django==3.1 I have 2 periodic celery tasks, in which I want the first task to run every 15 mins and the second to run every 20 mins. But the problem is that the first task is running on time, while the second is not running. Although I'm getting a message on console: Scheduler: Sending due task <task_name> (<task_name>) But the logs inside that function are not coming on the console. Please find the following files, celery.py from celery import Celery, Task app = Celery('settings') ... class PeriodicTask(Task): @classmethod def on_bound(cls, app): app.conf.beat_schedule[cls.name] = { "schedule": cls.run_every, "task": cls.name, "args": cls.args if hasattr(cls, "args") else (), "kwargs": cls.kwargs if hasattr(cls, "kwargs") else {}, "options": cls.options if hasattr(cls, "options") else {} } tasks.py from celery.schedules import crontab from settings.celery import app, PeriodicTask ... @app.task( base=PeriodicTask, run_every=crontab(minute='*/15'), name='task1', options={'queue': 'queue_name'} ) def task1(): logger.info("task1 called") @app.task( base=PeriodicTask, run_every=crontab(minute='*/20'), name='task2' ) def task2(): logger.info("task2 called") Please help me to find the bug here. Thanks! -
python.exe: No module named django-admin Vscode Error
(venv) PS D:\Project> python -m django-admin startproject home . D:\Project\venv\Scripts\python.exe: No module named django-admin I have no clue what I am doing wrong. I am pretty new to this. Vscode doesn't show python in the status bar. I have already set the interpreter. Every video on Youtube shows how to create the project directly. Google gave me no results on this question. -
Django local variable 'cart' referenced before assignment
i am trying to add a product to the cart and then redirect to the 'cart' page/url but when i select the button to add to cart, i get this error UnboundLocalError at /cart/add_cart/3/ local variable 'cart' referenced before assignment this is the function to get cart id : def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart this is the function to add a product to cart and redirect to the cart page: def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) #use cart_idin session to get cart except Cart.DoesNotExist: cart = cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') -
How to upload file to Django rest framework API using Axios and react hook form?
I have created an API using Django Rest Framework. It has an image uploading option. But I can not upload the file. I am using Axios for API calls and react hook form for form handling. I am posting the code below for better understanding. Django: Model: class BlogModel(models.Model): user = models.ForeignKey(user_model.User, on_delete=models.CASCADE, related_name="user_blog") blogtitle = models.CharField(max_length=250) blogcontent = models.TextField() blogimg = models.ImageField(upload_to="blog_image", blank=True) slug = models.SlugField(max_length=250, unique=True) tags = models.ManyToManyField(BlogTagsModel, related_name='blog_tags', blank=True, null=True) published_date = models.DateTimeField(auto_now_add=True) edit_date = models.DateTimeField(auto_now=True) Serializer class BlogSerializer(serializers.ModelSerializer): class Meta: model = blog_model.BlogModel fields = '__all__' extra_kwargs = { 'user': {'read_only': True}, 'slug': {'read_only': True}, } View class BlogPostView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = blog_ser.BlogSerializer queryset = blog_model.BlogModel.objects.all() def perform_create(self, serializer): rand_num = random.randint(99, 222) blog_slug_str = f"{serializer.validated_data.get('blogtitle')}{rand_num}" sample_string_bytes = blog_slug_str.encode("ascii") base64_bytes = base64.b64encode(sample_string_bytes) slug = base64_bytes.decode("ascii") serializer.save(user=self.request.user, slug=slug) React: Form JSX <form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit(onSubmit)}> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="title" > Title </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="title" type="text" {...register('title', { required: true })} /> {errors.title && <p className="text-red-500 text-xs italic">Title is required</p>} </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="image" > Image </label> <input … -
Django html display from model
I need on my html page to display data from Profesor and Ucenik model: ime, prezime, jmbg. {{profesor.ime}} {{profesor.prezime}} {{ucenik.ime}} {{ucenik.prezime}} {{ucenik.jmbg}} my profile page id dynamic, need to display profesor data or if ucenik to display ucenik data what i need to add on my views.py models.py class Profesor(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ime = models.CharField(max_length=200, null=True) prezime = models.CharField(max_length=200, null=True) class Ucenik(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ime = models.CharField(max_length=200, null=True) prezime = models.CharField(max_length=200, null=True) jmbg = models.IntegerField(null=True) urls.py path('profesor/', views.profesor, name='profesor'), path('ucenik/', views.ucenik, name='ucenik'), path('posetioc/', views.posetioc, name='posetioc'), path('profil/<str:pk>/', views.profil, name='profil'), ] views.py def profesor(request): return render(request, 'pocetna_profesor.html') def ucenik(request): return render(request, 'pocetna_ucenik.html') def profil(request, pk): return render(request, 'profil.html') HTML: {% extends 'base.html' %} <title>profesor</title> {% block content %} <body> {% include 'navbar.html' %} <h1>Ime:</h1> {{profesor.ime}} </body> {% endblock %} -
django appending form inside form with javascript called submit button
i have multiple form inside my template and i want to appending form div with add button like this <div id="Partform" class="card-body"> <div id="netformdiv" class="netformdiv"> <div style="display: flex;flex-direction: row" id="netwindow"> {{ formnetpriod.activity|as_crispy_field }} {{ formnetpriod.material|as_crispy_field }} {{ formnetpriod.days|as_crispy_field }} </div> </div> <div id="btnnetwindow"> <button style="width: 50px;height: 50px" onclick="addnetwindow()" class="btn btn-success">+</button> <button style="width: 50px;height: 50px" onclick="removenetwindow()" class="btn btn-danger">-</button> </div> </div> the javascript in my template for add or minuse form field is like this: <script> function addnetwindow(){ var form = document.getElementById("netwindow") var formBody = document.getElementById("netformdiv") var formcpy = form.cloneNode(true); formBody.append(formcpy); } function removenetwindow(){ let form = document.querySelectorAll("#netwindow") form[form.length-1].remove(); } </script> and the template view like this :enter image description here if i click on add button the div copied and when click minuse button the div remove last form but my problem is when i clicked on add or minuse button the submit button called and my page refreshed lost the appended form i think this is for django form to refresh the form data but how can i fix the problem. thank you -
Page not loading even after 200 status
I'm trying to redirect to the invoice page but nothing changes except the refresh this is the url.py urlpatterns = [ path('', User_login_view, name='login'), path('home/', HomePageView.as_view(), name='home'), path("nglm/", NGLMView.as_view() , name="nglm"), """ other urls for the sidebar""" path("createinvoice/", NGLINVAPI.as_view(), name="createinvoice"), path("nglinvoice/", NGLInvoiceTV.as_view(), name="nglinvoice") ] After login I go to "nglm" page where I input the customer details and click the submit button which calls the api "createinvoice". the class is shown below class NGLINVAPI(APIView): def post(self,request): if 'nglinv' == request.POST['formtype'] : data = { 'name': request.data['cname'], 'civilid': request.data['civilid'], 'ph':request.data['ph'], 'disc':request.data['disc'], 'bookno':request.data['Bookno'], 'tga':request.data['LAmount'], } p,ccreated = update_customerdb(data=data) l = update_gldb(data=data) data['cid'] = p.id iq,i = update_inventory(data=data,gl=l) lici = update_LICI(cid=p,lid=l,data=data) ninv = update_invoice(licid=lici,lid=l,cid=p,data=data,il = iq,items = i) invid = ninv.id NGLItemModel.objects.all().delete() base_url = '/nglinvoice/' query_string = urlencode({'pk': ninv.pk}) url = '{}?{}'.format(base_url, query_string) return redirect(url) return HttpResponseRedirect('home') this should have redirected me to invoice page "nglinvoice". the view is show below class NGLInvoiceTV(TemplateView): template_name = "pages/nglinvoice.html" def get(self, request): p = request.GET['pk'] inv = get_object_or_404(InvoiceModel, pk=p) context = {} context['segment'] = 'api' context['pagename'] = 'New GL API' context['object'] = inv return render(request,self.template_name , context) I have no issues up to this point. the problem is it doesn't show the page "nglinvoice.html", it just … -
Django - getting dropdown values
currently i am new to django and working with forms in django. i didn't know how to get the values from the dropdown and print it in python terminal ? Can anyone konw, How to get the dropdown values in Django and print it ? -
IntegrityError at /answer/ NOT NULL constraint failed: answer_answer.post_id
I have 2 models one for Question and one for Answer when i submitted answer form its throws me an error like this: IntegrityError at /answer/ NOT NULL constraint failed: answer_answer.post_id but when i added blank=True and null=True i can sumitted the form but i need to go to the admin and select the qustion i want the answer to be able to appear and that is not what i want. please how can i solve this error ? my models class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.user) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return str(self.user) the views def viewQuestion(request, pk): question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=question) context = {'question':question, 'answers':answers} return render(request, 'viewQuestion.html', context) class My_Question(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'body', 'category'] template_name = 'question.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Question, self).form_valid(form) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Answer, self).form_valid(form) the viewQuestion template: <div class="container"> <div … -
Tips to host an online MySQL server usable with Django
I want to make a Django website, with MySQL as the database. I have two of my friends working with me in different places for the development phase. The problem is, which online resources to use for the development time for the least/free cost' ? I have been thinking to use GitHub to store the website, but can't find any good MySQL free servers online (for the development period). Can someone suggest me? -
Django form input value for current image
My html form's image part: {% for photo in date.photo_set.all %} <div class="photo-wrapper-{{ forloop.counter }}"> <input type="file" name="current-photo-{{ forloop.counter }}" value="{{ photo }} accept="image/*""> </div> {% endfor %} Okay so this is a part of my form in Django. In form I show all current photos of model. When I submit the form I want to get that current photos in self.request.POST.keys(). But their key's values are empty like so: 'current-photo-1: [''], current-photo-2: ['']. As I understand the issue is in value attribute of <input> tag in my html form. It doesn't store any object-like stuff (image). How to make it actually store current photo. Hope you got it. If any questions, don't hesitate. Thanks! Note. I am pretty sure this information is enough for you to answer this question. -
Getting user credentials by email
I'm making a small solution to restore user credentials. I decided to try to do it with my algorithm. I request the user's mail and compare it with the database of postal addresses. If the mail exists, I want to send the user his credentials (login and password). I have already done the acceptance and verification of mail, as well as configured the sending of emails to postal addresses. But how to get access to credentials with only mail and the fact that the user is not logged in, I do not understand. I know that maybe my solution based on security is not very good, but there was interest and I really want to understand how to do it. It may be possible to make a quick login and get data from there, or it can do without it? As a result, I have to send the used as a message to views.py this data. views.py def recovery(request): if request.user.is_authenticated: return redirect("/accounts/exit/") else: if request.method == 'POST': email_form = UserRecoveryForm(request.POST) if email_form.is_valid(): email = email_form.cleaned_data['email'] try: send_mail("Восстановление учетных данных.", "message", "from@gmail.com", [email], fail_silently=False) except BadHeaderError: return HttpResponse('Ошибка в теме письма.') return render(request, 'registration/recovery_done.html') else: email_form = UserRecoveryForm() return render(request, … -
Django - How do I write a queryset that's equivalent to this SQL query? - Manging duplicates with Counting and FIRST_VALUE
I have Model "A" that both relates to another model and acts as a public face to the actual data (Model "B"), users can modify the contents of A but not of B. For every B there can be many As, and they have a one to many relation. When I display this model anytime there's two or more A's related to the B I see "duplicate" records with (almost always) the same data, a bad experience. I want to return a queryset of A items that relate to the B items, and when there's more than one roll them up to the first entered item. I also want to count the related model B items and return that count to give me an indication of how much duplication is available. I wrote the following analogous SQL query which counts the related items and uses first_value to find the first A created partitioned by B. SELECT * FROM ( SELECT COUNT(*) OVER (PARTITION BY b_id) as count_related_items, FIRST_VALUE(id) OVER (PARTITION BY b_id order by created_time ASC) as first_filter, * FROM A ) AS A1 WHERE A1.first_filter = A1.id;