Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create wordpress blog with subdomain using cloudflare
I have one Django web application hosted on AWS EC2 and I am using Cloudflare CDN. So I am using Cloudflare Name servers in my Domain provider. I want to create a Worpress blog with a subdomain for my web application like blog.mywebsite.com. I am having another shared hosting that will host a WordPress website. My question is how can I create a WordPress website with a subdomain? But my main domain is using Cloudflare CDN. Thanks -
Add custom file upload icon in tinymce
I have a ready custom file manager with ajax and html, I want to integrate file manager into Tinymce editor I can view the list of images that have been uploaded to the server Now I need is to add image uploader icon and when i click, appear the list and insert image in url input when click on image. This is a illustration image with photoshop -
Django ManyToMany field has automatically all the Users in admin panel
class Course(models.Model): students = models.ManyToManyField(User, verbose_name='Students', null=True, blank=True) I want to add course enrollment to model Course but my manytomanyfield already has all the users and I can't even remove any of them. What should I do? I want "Students" to be a list of users who takes the course. -
I will create a token using know,how delete a token when I logout in Django rest framework
Delete the login token using Knox when logout Knox have built in logout function so I don't know how to delete the login token -
Django 4.0.8 Error, No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
I am making a Blog website, but when I click on save button this error appears. No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. url.py from django.urls import path from .views import BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView urlpatterns = [ path('', BlogListView.as_view(), name='home'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), ] models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey( "auth.User", on_delete=models.CASCADE, ) def __str__(self): return self.title def getAbsoluteUrl(self): return reverse("post_detail", kwargs={"pk": self.pk}) base.html {% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=\ Source+Sans+Pro:400" rel="stylesheet"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> <body> <div> <header> <div class="nav-left"> <h1><a href="{% url 'home' %}">Django blog</a></h1> </div> <div class="nav-right"> <a href="{% url 'post_new' %}">+ New Blog Post</a> </div> </header> {% block content %} {% endblock content %} </div> </body> </html> views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Post from django.urls import reverse_lazy # Create your views here. class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post … -
How to create django project
What commands should I write in cmd. When I write: django-admin startproject myproject, it does not create a config folder in my project. What do I miss? -
How to filter objects by many to many attribute
Please help me to solve the following problem: I have two models, for example: class Student(model.Model): first_name = models.Charfield() last_name = models.Charfield() class Teacher(model.Model): first_name = models.Charfield() last_name = models.Charfield() subject = models.Charfield() students = models.ManyToManyField('Student') A teacher object can have many students. When adding a new teacher, his students are immediately indicated, but a check must be performed for each student that this student is not tied to another teacher with the same subject. Please help me how to organize this check (I suppose using a filter). Thanks a lot in advance! I tried to use filter like Teacher.objects.filter(subject=self.subject), but don't know how to check every student here -
Got AttributeError when attempting to get a value for field `transformerNamePlate` on serializer `MainDataSerializer`
i am trying to get a list of Main Objects with all of its nested Objects. but i got this error here is my codes views.py ` @api_view(['GET']) def getSelectedDevice(request): try: device_id=request.GET.get('dID', None) device=Main.objects.filter(device_id) print("device obg:\n",device) serializer=MainDataSerializer(device) return Response(serializer.data,many=True) except Main.DoesNotExist: return Response(status=404) ` models.py ` class TransformerNamePlate(models.Model): power=models.FloatField() uk=models.PositiveIntegerField() z0nom=models.FloatField() vectorGroup=models.CharField(max_length=10) vectorGroupLabel=models.CharField(max_length=10) uside1=models.FloatField() uside2=models.PositiveIntegerField() class Main(models.Model): dID=models.CharField(max_length=10) tID=models.CharField(max_length=12) user=models.CharField(max_length=40) deviceAliasName=models.CharField(max_length=60) dateTime=models.DateTimeField() #did and Tid (search) -> charfield transformerNamePlate=models.OneToOneField(TransformerNamePlate,on_delete=models.PROTECT) transformerInfo=models.OneToOneField(TransformerInfo,on_delete=models.PROTECT) detcTapChanger=models.OneToOneField(DETCTapChanger,on_delete=models.PROTECT,null=True) temperatureCorrectionHV=models.OneToOneField(TemperatureCorrectionHV,on_delete=models.PROTECT) temperatureCorrectionLV=models.OneToOneField(TemperatureCorrectionLV,on_delete=models.PROTECT) uk=models.OneToOneField(UK,on_delete=models.PROTECT) turnRatioTolerance=models.OneToOneField(TurnRatioTolerance,on_delete=models.PROTECT) tests=models.ForeignKey(Test,null=True,on_delete=models.PROTECT) ` serializer.py ` class TransformerNamePlateSerializer(serializers.ModelSerializer): class Meta: model=TransformerNamePlate fields="__all__" class MainDataSerializer(serializers.ModelSerializer): transformerNamePlate=TransformerNamePlateSerializer(many=False,read_only=False) transformerInfo=TransformerInfoSerializer(many=False, read_only=False) detcTapChanger=DETCTapChangerSerializer(many=False, read_only=False) temperatureCorrectionHV=TemperatureCorrectionHVSerializer(many=False, read_only=False) temperatureCorrectionLV=TemperatureCorrectionLVSerializer(many=False, read_only=False) uk=UKSerializer(many=False, read_only=False) turnRatioTolerance=TurnRatioToleranceSerializer(many=False, read_only=False) #tests=Test ->(many=False, read_only=True) class Meta: model=Main fields="__all__" def create(self, validated_data): transformerInfo_data=validated_data.pop('transformerInfo') temperatureCorrectionHV_data=validated_data.pop('temperatureCorrectionHV') temperatureCorrectionLV_data=validated_data.pop('temperatureCorrectionLV') transformerNamePlate=validated_data.pop('transformerNamePlate') uk_data=validated_data.pop('uk') turnRatioTolerance_data=validated_data.pop('turnRatioTolerance') detcTapChanger_data=validated_data.pop('detcTapChanger') #Remember to add other parts of test data test_data=validated_data.pop('tests') #print(validated_data) main_data=Main(**validated_data) # for data in temperatureCorrectionHV_data: # print (data) TemperatureCorrectionHV.objects.create(main=main_data,**temperatureCorrectionHV_data) TemperatureCorrectionLV.objects.create(main=main_data,**temperatureCorrectionLV_data) DETCTapChanger.objects.create(main=main_data,**detcTapChanger_data) UK.objects.create(main=main_data,**uk_data) TransformerInfo.objects.create(main=main_data,**transformerInfo_data) TransformerNamePlate.objects.create(main=main_data,**transformerNamePlate) TurnRatioTolerance.objects.create(main=main_data,**turnRatioTolerance_data) # Test.objects.create(main=main_data,**test_data) return main_data def save(self,data=None, **kwargs): if data!=None: main_data=self.create(validated_data=data) main_data.save() return else: return super().save(**kwargs) ` I figured out that it is because that Main.objects.all() doesnt return those nested data and just return the id field of them and because of that i get KeyError in serializer because it is looking for the actual object,not its id. -
403 error while fetching from my own server: CSRF Token missing
I have a social-media-like page that displays all posts by each user and users are able to edit their own posts with an Edit button. When the edit button is clicked, a textarea pre-filled with post content plus a Save and a Cancel button are displayed. When the Save button is clicked, I make a fetch request to update the content without reloading the page. However, I'm getting 403 because the csrf token is missing. What confuse me is that I don't have a form in my HTML template. Where should I put {% csrf_token %}? network.js: function clearEditView(postId) { // Show edit button and original content document.getElementById(`edit_button_${postId}`).style.display = "block"; document.getElementById(`content_${postId}`).style.display = "block"; // Hide edit form document.getElementById(`edit_form_${postId}`).style.display = "none"; } document.addEventListener('DOMContentLoaded', function() { // Add event listener that listens for any clicks on the page document.addEventListener('click', event => { // Save the element the user clicked on const element = event.target; // If the thing the user clicked is the edit button if (element.id.startsWith('edit_button_')) { // Save necessary variables const editButton = element; const postId = editButton.dataset.id; const saveButton = document.getElementById(`save_${postId}`); const cancelButton = document.getElementById(`cancel_${postId}`); const postText = document.getElementById(`content_${postId}`); // Hide edit button and original content editButton.style.display = "none"; … -
Django include template as variable to use in default
I'd like to include a default template as a variable to pass it into a default case, like below: <div class="row max-h-200 overflow-hidden"> {% include 'blog/userprofile_deleted.html' as deleted_profile %} {{ user.profile.bio | safe | default:deleted_profile }} </div> Is this possible in django 3.2.9 ? Currently I have to write out the default text as html in a single line: <div class="row max-h-200 overflow-hidden"> {{ user.profile.bio | safe | default:'<h4> Very long html string! </h4> <span>Comment as <b>you</b> with your own profile!</span><span>Create your Account at the <a href="#footer">bottom of the page</a>,or by visiting <a href="{% url "register" %}"><code>/register</code></a> !</span>' }} </div> -
Displaying join tables (many-to-many relationships) with django-extensions graph_models
For an exhaustive visual understanding of a data model, is there a way to display join tables (they actually exist in the DB) of many-to-many relationships with graph_models from the django-extension (3.2.1) module? This is the current help I got and I cannot find it all through: $ python manage.py graph_models --help usage: manage.py graph_models [-h] [--pygraphviz] [--pydot] [--dot] [--json] [--disable-fields] [--disable-abstract-fields] [--group-models] [--all-applications] [--output OUTPUTFILE] [--layout LAYOUT] [--theme THEME] [--verbose-names] [--language LANGUAGE] [--exclude-columns EXCLUDE_COLUMNS] [--exclude-models EXCLUDE_MODELS] [--include-models INCLUDE_MODELS] [--inheritance] [--no-inheritance] [--hide-relations-from-fields] [--relation-fields-only RELATION_FIELDS_ONLY] [--disable-sort-fields] [--hide-edge-labels] [--arrow-shape {box,crow,curve,icurve,diamond,dot,inv,none,normal,tee,vee}] [--color-code-deletions] [--rankdir {TB,BT,LR,RL}] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] [app_label ...] Creates a GraphViz dot file for the specified app names. You can pass multiple app names and they will all be combined into a single model. Output is usually directed to a dot file. positional arguments: app_label optional arguments: -h, --help show this help message and exit --pygraphviz Output graph data as image using PyGraphViz. --pydot Output graph data as image using PyDot(Plus). --dot Output graph data as raw DOT (graph description language) text data. --json Output graph data as JSON --disable-fields, -d Do not show the class member fields --disable-abstract-fields Do not show the class … -
Why am I not able to create a super user in django? It's asking me to fill in every detail and on top of that, it asks me to enter a location
What can I do here? What kind of a location it is looking for from me? It has never happened ever earlier. -
How to set allow_null=True for all ModelSerializer fields in Django REST framework
I have a ModelSerializer . I want to set allow_null=True for all of the fields of the serializer . But I don't want to do it manually, I mean- I don't want to write allow_null=True for every field . Is there any shortcut? Is there anything like read_only_fields=() ? This is my Serializer class ProductPublicListSerializer(serializers.ModelSerializer): minimum_price = serializers.FloatField(source='min_product_price', allow_null=True) maximum_price = serializers.FloatField(source='max_product_price', allow_null=True) # rating = serializers.FloatField(source='productreview__rating', read_only=True) class Meta: model = Product fields = ( 'id', 'name', 'featured_image', 'minimum_price', 'maximum_price', 'total_review', 'average_rating') read_only_fields = ('name', 'featured_image', 'minimum_price', 'total_review') -
How to optimize a query on a model with foreign keys AND many to many field
(https://pastebin.com/qCMypxwz) These are my models. Right now 14 queries are made to get the desired result. Mostly, a query is made to get images associated with each product. Image is many to many field because each product has many images. productList = Variants.objects.select_related('prod_id__category') for productName in productList: products = dict() prod_id = productName.id products['id'] = prod_id products['category'] = productName.prod_id.category.category_name products['prod_name'] = productName.prod_id.prod_name prod_images = list(productName.image.values_list('image_url').distinct()) image_list = list() for image in prod_images: image_list.append(image[0]) products['image'] = image_list price = productName.price products['price'] = price createdAt = productName.createdAt products['createdAt'] = createdAt productListDict.append(products) -
Hardcode the value of a child class model field to be = to a field value in its parent
In a Django model, I would like to force a field of a child class to have a fixed value inherited from of a field of its parent. E.g.: from django.db import models class Entity(models.Model): class Type(models.TextChoices): Natural = ("Natural", "natural") Juridical = ("Juridical", "juridical") entity_type = models.CharField( max_length=9, choices=Type.choices, default=Type.Natural, ) class Person(Entity): person_type = Entity.Type.Natural # <--- forcing it to be 'Natural' from parent class ... I want to create such person_type field and forcing its value to be 'Natural' for each person object created using the Person class. This field can then be displayed in the admin, but the user must not have any kind of option to modify it. Same in the DB, ideally. I found nothing which relates to this idea in the doc: https://docs.djangoproject.com/en/4.1/ref/models/fields/ and I'm not able to apply this answer to set the value of the person_type field: https://stackoverflow.com/a/68113461/6630397 -
select not creating category entry in django database
I need to make it so that the select from the form is displayed in the database, None appears in its place in the database everything is added except categories and stocks I was told that I need to add value to option, but nothing happened to me what's wrong Here is my views.py : def create_product(request): categories = Category.objects.all() stock = Stock.objects.all() if request.method == 'POST': product = Product() product.title = request.POST.get('title') product.category = Category.objects.get(id=request.POST.get('category')) product.price = request.POST.get('price') product.user = request.POST.get('user') product.amount = request.POST.get('amount') product.stock = request.POST.get('stocks') product.user = request.user product.save() return redirect('index') return render(request, 'main/create.html', {'categories':categories,'stocks':stock}) Here is my models.py : class Product(models.Model): title = models.CharField(verbose_name="Название товара", max_length=250) categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) price = models.IntegerField(verbose_name="Цена") user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products') amount = models.CharField(max_length=250,verbose_name='Количество') user = models.ForeignKey(User, on_delete=models.PROTECT) stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' def __str__(self): return self.title My create template : <div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);"> <h1 class="display-6">Создайте товар</h1> <form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Название</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" … -
pipenv pytest ignores source changes or uses cached source?
I have a Django 4.0.6 project, Python 3.9.15, Ubuntu 22.10, pipenv 2022.10.25, pytest 7.1.2 The test output was cached somewhere and now any modification is ignored unless I delete the method. The steps I performed: Run the test: pipenv run pytest src/some/path/models.py The test fails, showing the correct error in traceback. Modify the method body. Run the test again. The test fails again, BUT the traceback shows old code, unmodified. Removing the method solves the problem, but any modification made to the method source makes it appear again in traceback, UNMODIFIED. Does pipenv/pytest/whatever cache the source somewhere? pipenv run pytest src/some/path/models.py --cache-clear did not help. As well as removing the .pytest_cache/. I tried removing the venv/some/path/__pycache__/models.cpython-39.pyc file (and all compiled *.pyc files in venv) But nothing seem to help. The same traceback appears every time I run tests. -
'int' object has no attribute 'save' in django
I have a value in a database on phpmyadmin and I want to change this value by a new calculated value. The function save() doesn't work and the error tells me that it's because it's an interger. I don't know how to solve this problem. def DeleteBulle (request, id_bulle): #suppression de la bulle par l'id id_bulle param = Bulles.objects.get(pk=id_bulle) #param.delete() #adaptation du champ "nombre de bulle" dans la table "site" site=param.id_site print('site', site) compte=Bulles.objects.filter(id_site=site).count() print('nombre bulle avec site identique', compte) nbrbulle=Bulles.objects.get(pk=id_bulle).id_site.nombre_bulles nbrbulle=compte nbrbulle.save() #réussite print("Bulle supprimée") return redirect('api_bulles_frontend') I don't know how to solve this problem. Thank you for your help. -
docer-compose.yml in Django project: environment variables are not created from the .env file
My docker-compose.yml: version: '3.8' services: web: build: ./app command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - .dev.env my Dockerfile in ./app: FROM kuralabs/python3-dev WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip3 install -r requirements.txt COPY . . My file '.dev.env': ALLOWED_HOSTS='localhost 127.0.0.1' DEBUG=1 SECRET_KEY='django-insecure-...' I run the project with the commands: $docker-compose build $docker-compose up -d I get variables in settings.py: load_dotenv() print(f'Environment: {os.environ}') my variables from the '.dev.env' file are not in the list of environment variables. Please help me understand why '.dev.env' variables don't get into the environment? -
Django incomplete migration of table with multiple foreign keys
Django version: 4.1.2 After heaving the following table defined in the model: class Tasks(models.Model): name_text = models.CharField(max_length=200) duration_int = models.IntegerField(default=1) ... the next two tables have been defined: class Metiers(models.Model): name_text = models.CharField(max_length=50) ... class TasksProperties(models.Model): task = models.ForeignKey(Tasks, on_delete=models.CASCADE, related_name='task_relation') metier = models.ForeignKey(Metiers, on_delete=models.CASCADE, related_name='metier_relation') ... doing the migration, the metier is not created inside the SQL table, but the rest: class Migration(migrations.Migration): dependencies = [ ('simo', '0009_alter_specialdays_day_date'), ] operations = [ migrations.CreateModel( name='Metiers', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name_text', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='TasksProperties', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('workload_mh', models.IntegerField(default=8)), ('task', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='simo.tasks')), ], ), ] Is there any reason, why metier is not taken into account? -
Need to show result on the same page - Django
I'm creating a password generator app. The app is working and stores the value on db. The problem is whenever I refresh, the form resubmits and takes the previous value and stores. Also, I want to show the email and password on the same page. Whenever I refresh, I want to show an empty form with empty fields. Views.py def home(request): if request.method=='POST': inputemail = request.POST.get('InputEmail') gen = ''.join(random.choices((string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation), k=10)) newpass = Item(email=inputemail,encrypt=gen) newpass.save() return render(request,'home.html',{"gen":gen}) return render(request,'home.html',{}) Home.html <form method = 'post' id='pass-form' > {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input type="email" class="form-control" name="InputEmail" > <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <button type="submit" name = "submit" class="btn btn-primary">Generate Password</button><br><br> </form> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Generated Password</label> <input type="text" id="InputPassword" name = "genpassword" value = {{gen}} > </div> Urls.py urlpatterns = [ path('',views.home,name='home'), ] -
When I filter I need to request.GET.value to be selected
I have to filter some data so I need to use a select field but when I submit the form the result disappears. I have to selected the value that is choice previous ` <label class="text-secondary">Discount Type</label> <select name="discount_type" class="form-control" > <option value="" class="text-center" >Select Type</option> {% for i in type %} <option {% if i.0 == request.GET.status %} selected {% endif %} value="{{ i.0 }}" >{{ i.1 }} </option> {% endfor %} </select>` -
Django Heroku deployment not serving static image files with Whitenoise
My css and js static files are working but my images are not loading. whitenoise==6.2.0 works in development but not with debug off.. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" django_heroku.settings(locals()) URLS.PY if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) some template {% load static %} <center><img class="rounded" src="{% static 'images/sm_logos/about-1.png/'%}" style="height:300px; width:300px;"></center> C:\Users\Boss Chris\Desktop\Projects\CBlog\CBlog_project\blog\static\images\sm_logos\about-1.png appreciate your help.. been at this since yesterday and maxed out on pushups.. cant do anymore.. tried putting my static files in S3 too.. doesn't work but i'll try again tmrw if there's no solution -
Search in multiple models in Django
I have many different models in Django and I want to search for a keyword in all of them. For example, if you searched "blah", I want to show all of the products with "blah", all of the invoices with "blah", and finally all of the other models with "blah". I can develop a view and search in all of the models separately, but it's not a good idea. What is the best practice for this situation? -
DjangoCMS - Render database data to html
I'm testing out the DjangoCMS but I cannot understand how to create custom plugins that enable rendering data out of the database. I'd like to create a plugin that shows all the users for example but I can't understand how to pass the data into the HTML file. I followed the DJangoCMS documentation to create a custom plugin that shows the guest name, I've already tried to add users = User.objects.all() and then pass it to the render function but I receive an argument exception because the render function does not allow so many arguments, so what's the approach in DJangoCMS? models.py from cms.models.pluginmodel import CMSPlugin from django.db import models class Hello(CMSPlugin): guest_name = models.CharField(max_length=50, default='Guest') cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User from .models import Hello @plugin_pool.register_plugin class HelloPlugin(CMSPluginBase): model = Hello name = _("Hello Plugin") render_template = "hello_plugin.html" cache = False def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) return context