Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update multiple images in django?
I'm trying to develop a post feauture with multiple images related to it and I have encoutered some problems I can't solve. So, in my models.py I have a Post model and PostImages model with one to many relationship: class PostImages(models.Model): post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, null=True, blank=False) I upload multiple images like this: def addpost(request): if request.method == 'POST': form = CreatePostForm(request.POST) images = request.FILES.getlist('images') if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() for i in images: PostImages.objects.create( post_id = post, image = i, ) return redirect('index') else: return redirect('addpost') else: context = {'formpost': CreatePostForm} return render(request, 'addpost.html', context=context) addpost.html: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formpost.as_p }} <input required name="images" type="file" multiple> <input type="submit" value="Submit"> </form> And I can't figure out how to edit multiple images: I tried something like this in my views.py def update_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.user != post.author: return redirect('index') context = {} images = post.postimages_set.all() count = 0 for i in images: count += 1 imagesformset = formset_factory(UpdateImagesForm, extra=count) context['formset'] = imagesformset if request.method == 'POST': form = UpdatePostForm(request.POST, instance=post) formset = imagesformset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): form.save() for form in formset: if form.is_valid(): … -
What is the best authentication method in django rest framework?
I want my website authentication to be strong For that purpose I have found the following things Combination of Base authentication with CSRF validation for session based authentication JSON Web Token Authentication support for Django REST Framework Which one is better among them? Or is there any other better method out there -
How do I use a for loop to reuse a django form in a template
After struggling with this issue for a while, I am hoping someone here can point me in a more productive direction. I am trying to take an indeterminate number of variables in a database (obtained through a different template) and render them on a webpage, each variable with a simple data entry form, to be saved back to the database. Basically, it's a tracker for analysis. Say I want to track my daily sleep, running time, and calorie intake (the variables). I have those saved in a database as variables and want to call upon those variables and show them on a webpage with a daily entry form. I am using a "for" loop right now and it renders the way I want it to, with the variable name and the form, but it is only saving the last item in the variable list. How do I amend the code below such that when I hit the save button for each form rendeded, it saves the information for that variable (not just the last one rendered). Below is the code. Any and all help would be infinitely appreciated. Models... class Variable(models.Model): date_added = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) # … -
django html canvas load a background image on canvas
i have a html canvas where the user saves canvas and the user can laod their saved drawings onto canvas My models are as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) class image(models.Model): upload = models.ImageField() project = models.CharField(max_length=250) My load function is as follows it filter thedrawing model and displays on canvas based on project field.now i have another model where i have an image for each project saved. so i need to display the image of project filteres(only one image for each project) on background while laoding the points onto canvas. My view function to load the drawing.It def load(request): """ Function to load the drawing with drawingID if it exists.""" try: filterdata = Drawing.objects.filter(project=2) ids = filterdata.values_list('pk', flat=True) length = len(ids) print(list[ids]) print(length) drawingJSONData = dict() drawingJSONData = {'points': [], 'lines': []} for id_val in ids: drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText) drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"] drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"] print(drawingJSONData) drawingJSONData = json.dumps(drawingJSONData) context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response My javascript file to load the image onto canvas // Checking if the drawing to be loaded exists if … -
nginx rtmp_module http version
I use nginx rtmp to set up streaming platform with Django. Nginx have setting on_publish, there I enter the address where to send the request when the broadcast started. The problem is nginx sends a request with HTTP/1.0, but Django accept requests with HTTP/1.1 What can I do? Can I write http_version for nginx somewhere, or how to make django accept a request with HTTP/1.0 Config nginx worker_processes 1; events { use kqueue; worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; server { listen 8080; server_name localhost; root path_to_root; location ~ ^/live/.+\.ts$ { # MPEG-TS segments can be cached upstream indefinitely expires max; } location ~ ^/live/[^/]+/index\.m3u8$ { # Don't cache live HLS manifests expires -1d; } location / { proxy_pass http://127.0.0.1:7000/; proxy_http_version 1.1; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } rtmp { server { listen 1935; application stream { live on; allow play all; on_publish http://127.0.0.1:7000/start_stream; on_publish_done http://127.0.0.1:7000/stop_stream; hls on; hls_path path_to_live; hls_nested on; hls_fragment_naming system; hls_datetime system; } } } Error in django: [12/Mar/2021 12:11:50] "POST /start_stream HTTP/1.1" 500 93963 It's request from postman, OK Forbidden: /start_stream [12/Mar/2021 12:12:02] "POST /start_stream HTTP/1.0" … -
Displaying recurring events in Django Calendar
I am new to Django and I am trying to design a calendar app that displays events. I am using the provided source code as the initial code for the calendar: https://github.com/sajib1066/django-eventcalender. While this code works fine, I am trying to implement occurrences to each event, so each event can repeat in a specific frequency defined by me. To do this i used "django-eventtools" (link:https://github.com/gregplaysguitar/django-eventtools/tree/391877dc654427cce1550ad62fd3537786dfed26). While I am able to already display each event on the calendar, i can't make it display everyday when it is already defined to repeat daily. To display each event, I am using a generic.ListView but I am guessing my issue is that I can't use my occurrence data in the context to be displayed. models.py: class Event(BaseEvent): # adicionar cliente user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('calendarapp:event-detail', args=(self.id,)) @property def get_html_url(self): url = reverse('calendarapp:event-detail', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' class MyOccurrence(BaseOccurrence): title = models.CharField(max_length=50, unique=True, default='No Title') event = models.OneToOneField(Event, on_delete=models.CASCADE) def __str__(self): return self.title def create_event_occurence(sender, instance, created, **kwargs): if created: for event in Event.objects.all(): MyOccurrence.objects.get_or_create(title=instance.title, event=instance, start=instance.start_time, end=instance.end_time) post_save.connect(create_event_occurence, sender=Event) … -
Django doesn't add new tasks and buttons
I'm doing django todo app and Django delete(complete )button doesn't appear. Also, I can't add new tasks. Once buttons appeared but there was Reverse for 'completed' with arguments '('',)' not found. 1 pattern(s) tried: ['completed/(?P<todo_id>[0-9]+)$'] error. views.py: tasks = [] @login_required def index (request): tasks = NewTask.objects.all() if "tasks" not in request.session: request.session["tasks"] = [] if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): todo = form.cleaned_data["task"] return HttpResponseRedirect(reverse( "todo:index")) else: return render(request, "todo/index.html", { "form":form }) return render(request, "todo/index.html", { "tasks":tasks, "form":NewTaskForm(), }) def completed(request, todo_id): item = NewTask.objects.get(pk=todo_id) item.delete() messages.info(request, "item removed !!!") return HttpResponseRedirect('') index.html: <ul class="tasks"> {% for todo in tasks%} {% csrf_token %} <form class = "done" action="completed/{{task.id}}" method="post"> {% csrf_token %} <input type='submit'><i class="fas fa-check"></i> </form> {%endfor%} </ul> forms.py class NewTaskForm(ModelForm): class Meta(): model = NewTask fields = ['task'] models.py class NewTask(models.Model): task = models.CharField(max_length=10000) done = models.BooleanField(default=False) def __str__(self): return self.task -
Django - Datatables - Chained Dropdown List - Reset the last selected options when reloading to the page
I was inspired by this article to set up chained dropdown list How to Implement Dependent/Chained Dropdown List with Django. I created three chained dropdown list (named respectively id_division, id_section id_section) above a Datatable (https://datatables.net) named table : <div class="form-row" style="margin-left: 0" id="id-orga-form" data-divisions-url="{% url 'load_divisions' %}" data-sections-url="{% url 'load_sections' %}" data-cellules-url="{% url 'load_cellules' %}"> <span style="margin-right: 10px">Filtrer : </span> <div class="form-group col-md-2"> <label for="id_division">Division</label> <select name="Division" id="id_division" class="form-control-sm"></select> </div> <div class="form-group col-md-2"> <label for="id_section">Section</label> <select name="Section" id="id_section" class="form-control-sm"></select> </div> <div class="form-group col-md-2"> <label for="id_cellule">Cellule</label> <select name="Cellule" id="id_cellule" class="form-control-sm"></select> </div> </div> Each list is used to apply a filter on a specific column. This works perfectly. $('#id_division').change(function () { divisionId = $(this).val(); $("#id_section").html(''); // initialize an AJAX request pour SECTION $.ajax({ url: $("#id-orga-form").attr("data-sections-url"), // add the division id to the GET parameters data: { 'division': divisionId }, // replace the contents of the section input with the data success: function (data) { $("#id_section").html(data); } }); search_division = $.trim($('#id_division option:selected').text()); if ( divisionId === null || search_division === '---------') { table.column([7]).search('').draw(); } else { table.column([7]).search('"' + search_division + '"').draw(); } $("#id_section").trigger("change"); }); $("#id_section").change(function () { sectionId = $(this).val(); $("#id_cellule").html(''); // initialize an AJAX request pour CELLULE $.ajax({ url: $("#id-orga-form").attr("data-cellules-url"), // add … -
Python, Django: Merge respectively join multiple models with foreignkey
Good evening, I would like to ask if there's a possibility inside django (database-queries) to merge multiple models with one request. I'm not very good in sql but I think it's called join or merge there? models.py class ObjectA(models.Model): name = models.CharField(max_length=50) class ObjectB(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(default=0) object_a = models.ForeignKey(ObjectA, null=False, blank=False, on_delete=models.CASCADE) class ObjectC(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(default=0) object_b = models.ForeignKey(ObjectB, null=False, blank=False, on_delete=models.CASCADE) What I'm trying to achive... object_a | object_b_name | object_b_amount | object_c_name | object_c_amount a_01 | b_01 | 17 | c_01 | 42 a_01 | b_02 | 21 | c_02 | 0 a_02 | b_03 | 145 | c_02 | 29 a_03 | b_04 | 0 | c_02 | 31 a_03 | b_05 | 0 | c_04 | 102 a_04 | b_06 | 73 | c_09 | 54 Is something like this possible or is it a problem, that each class only contains the foreignkey to the "previous level"? Hoping someone has an answer!? Thanks to all of you and have a great weekend! -
Field is empty in database after self-written clean_field is called
I'm trying to secure that each email can only be used once, thus having the following clean method from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): email = forms.EmailField() . . . def clean_email(self): """ Check if that email already exists in the database """ email = self.cleaned_data["email"] if User.objects.filter(email=email).exists(): raise ValidationError("This email already exists") return email and all the checks works as intended. The issue is that after the user is created, the email field is empty. Even if I hardcode the returned-email i.e class UserRegisterForm(UserCreationForm): email = forms.EmailField() . . . def clean_email(self): email = self.cleaned_data["email"] if User.objects.filter(email=email).exists(): raise ValidationError("Der er allerede en bruger med den email") return "my_email@email.com" it is still empty in the database when the user is created. I have attached the view aswell below, if that could be it #views.py def register(request): if request.method=="POST": #post request form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Yey - success! Log in here ") return redirect("login") else: form = UserRegisterForm() return render(request,"users/register.html",context= {"form":form}) What am I missing here? -
Error compiling Dockerfile to install wikipedia-API in Python
I´m trying to compile my Docker but I found the error bellow in my Django project. I tried to include urllib3 and request in my dockerfile but the error is the same. It´s looks like some about temporary config/cache directory error, but I don´t know how can I fix it in my Django project. Matplotlib created a temporary config/cache directory at /tmp/matplotlib-njyb_ktv because the default path (/.config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 589, in … -
Django Rest Framework adds an extra word when do query
Im trying to get data from a server. This server have a bbdd with name Schools and there inside have two tables called student and teacher, they have a one to many relationship. I only have read permissions so i cant do migrations. Im working with Django and DjangoRestFramework It seems its all ok but when I do a call to the view I have this error: 1146, "Table 'Schools.api_teacher' doesn't exist obviously does not exist that table, the correct would be Schools.teacher Is there a way to correct this? -
How do I add my html navbar into another html file in django
I am still very new to Django and I want to add the HTML for a navigation bar and its respective CSS into my base HTML file. Here is what I did up till now: in app/base.html: {% extends "BritIntlSchl/navbar.html" %} {% load static %} <!DOCTYPE html> <html> <head> <title>page title</title> <link href="{% static 'appname\stylebase.css' %}" rel="stylesheet"> <link href="{% static 'appname\navbarstyles.css'}" rel="stylesheet" %}"> {% block head-content %}{% endblock head-content %} </head> {% block nav%}{% endblock nav %} {% block content1 %}{% endblock content1 %} </body> </html> and in app/navbar.html: {% block nav%} <div class="wrap">...</div> {% endblock nav%} I am pretty much lost here. I am sure that putting{% block nav%} around the nav bar does nothing. How do you suggest I go about this? I'm using Django 2.1. -
How to create product based file
I have a shop that based on Oscar framework. One of my product is a service that based on a file that the customer upload. The customer choose the service, upload a file, there are some calculations and a price that based on the file the customer uploaded. Any idea how to do it with Oscar? Until now, I did it with a regular form. Or shall I need to create a new product class and new view? -
Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at
there I am using a queryset in Django- whenever I run the server, it gives an error. I don't know whether its an issue with my models.py or .. I tried looking up this DeferredAttribute object on Google, but I didn't really see any answer that works for me Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x0000021CBFAE7940>. models.py from django.db import models from django.utils import timezone class User(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=50) password = models.CharField(max_length=30) class Meta: db_table = "managestore_user" class Data_source(models.Model): name = models.CharField(max_length=30) class Meta: db_table = "managestore_data_source" class Data(models.Model): customer_idd = models.CharField(max_length=30) customer_name = models.CharField(max_length=30) gender = models.CharField(max_length=30) country = models.TextField(max_length=30) city = models.TextField(max_length=50) state = models.TextField(max_length=50) category = models.TextField(max_length=100) sub_category = models.TextField(max_length=100) product_name = models.TextField(max_length=100) sales = models.FloatField() quantity = models.IntegerField() discount = models.FloatField() profit = models.FloatField() class Meta: db_table = "managestore_data" class Manage_store(models.Model): data_source_name = models.TextField(max_length=30) file_name = models.TextField(max_length=30) execution_time = models.TextField(max_length=30) number_of_records = models.IntegerField() data_source = models.ForeignKey(Data_source, on_delete=models.CASCADE) data = models.ForeignKey(Data, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Manage_store, self).save(*args, **kwargs) class Meta: db_table = "managestore_manage_store" view.py def upload(request): # if forms.is_valid(): # answer = … -
Django working with query parameters in raw Postgres queries
I use the `amount = (request.GET.get('page'))` and then i convert it into a int `amount= (int)amount` but when i tried to run this query: `cursor.execute('SELECT column1, FROM table LIMIT amount')` I get a error: `column "amount" does not exist` So is the any way how i can get the value to the query? -
I can't understand how to use correct static in django
I'm trying to display a picture whose address is saved in the Django models attribute. As I know you need to enter in the fieldurl({% static movie.img %}) but it doesen't works. If only use url({% static 'img/default-movie.png' %}) it works. That is my query sets from django shell: In [21]: Movie.objects.first().img Out[21]: <ImageFieldFile: ../MovieApp/movies/static/img/1202296.jpg> P.S (I should mentioned, that these fields are in for loop {% for movie in movies %} ) -
Can I use an API Key to identify a server that is an API consumer?
I'm facing a straightforward architectural challenge, which is that I have a central API written in Django and DRF. It has in it an API key library, in which there is an API key stored along with some other cryptographic information, and a column called "name". I can imagine with a little bit of customization I could add extra fields to this entity. I have multiple API consumers, which are themselves end-user browsable services, which communicate with this API. I need to be able to send notifications from within the centralized API - this requires access to the user's contact point, which is a URL, sometimes an IP address especially if it's behind a proxy. Since I need this URL, I need to store it somewhere perhaps in the database. There is get_base_uri() in Django, but I don't think it is for this purpose, especially since IP addresses are typically not necessarily connected to the consumer. How should I store, authenticate and authorize an API consumer's request? Should I submit the notification endpoint on every request (quite tedious), use the API key on every request (sent along with the request headers, would also need to implemented, but it would be … -
django filter data and make union of all data points to assignt to a new data
My model is as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) Sample data saved in drawingJSONText field is as below {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data def load(request): """ Function to load the drawing with drawingID if it exists.""" try: #drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) #drawingJSONData2 = json.loads(Drawing.objects.get(id=3).drawingJSONText) #drawingJSONData = dict() #drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] #drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] #drawingJSONData = json.dumps(drawingJSONData) #drawingJSONData = Drawing.objects.get(id=3).drawingJSONText filterdata = Drawing.objects.filter(project=1).count() drawingJSONData = Drawing.objects.get(id=filterdata).drawingJSONText #drawingJSONData = filterdata[1].drawingJSONText #drawingJSONData["points"]=filterdata["points"] #drawingJSONData["lines"] = filterdata["lines"] # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response Any suggestions on to achieve it -
Docker on GCE always restarting
Problems I am having with my Docker instance on a GCE VM: It keeps restarting I cannot access tcp:80 after creating several firewall policies Here are the steps I took in creating the instance with gcloud: Why is Google Compute Engine not running my container? What I have tried: To open the port, I created a new policy and updated tagged the VM, but still running: nmap -Pn 34.XX.XXX.XXX # results in: PORT STATE SERVICE 25/tcp open smtp 110/tcp open pop3 119/tcp open nntp 143/tcp open imap 465/tcp open smtps 563/tcp open snews 587/tcp open submission 993/tcp open imaps 995/tcp open pop3s # 80/tcp is not open Alternatively, I tried opening the port from inside the container after SSH: docker run --rm -d -p 80:80 us-central1-docker.pkg.dev/<project>/<repo>/<image:v2> curl http://127.0.0.1 #which results in: curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused Also, running docker ps from within the container shows a restarting status. If it helps, I have two docker-compose files, one local and prod. The prod has the following details: version: '3' services: web: restart: on-failure build: context: ./ dockerfile: Dockerfile.prod image: <image-name> volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 env_file: - … -
django.db.utils.OperationalError: Problem installing fixtures: no such table: pages_page__old
i am a begginer in code and when y try to make : python3 manage.py createdb. after to add my password i have an error, after the superuser create succesfully. and the finish of the following error is : django.db.utils.OperationalError: Problem installing fixtures: no such table: pages_page__old all my error : Traceback (most recent call last): File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: pages_page__old The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/martaf/Travail_insPYration/shop/manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/mezzanine/core/management/commands/createdb.py", line 61, in handle func() File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/mezzanine/core/management/commands/createdb.py", line 109, in create_pages call_command("loaddata", "mezzanine_required.json") File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/commands/loaddata.py", line 115, in loaddata connection.check_constraints(table_names=table_names) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 276, in check_constraints cursor.execute( File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/utils.py", … -
How can I host my Django project on cpanel?
I'm using cpanel on hostinger and I want to host my Django project on cpanel but there's no "set up a python app" on the board. I googled it and saw people say I need to install cloud linux os. but I don't know how please tell me how can I do that or if there is an alternative way to do that. i'm a collage student and I need this for my project. please help! -
DjangoListField analouge for an individual object resolver
I am using Django + GraphQL and it is extremely convenient to use DjangoListField. It allows me to override get_queryset at the ObjectType level and make sure all permissions verified there. In that manner I have a single place to have all my permission checks. However, whenever I need to do something like: contract = graphene.Field(ClientContractType, pk=graphene.ID(required=True)) I have to also duplicate permissions validation in the resolve_contract method. I came up with the following solution to ensure permission and avoid duplication: def resolve_contract(self, info, pk): qs = ClientContract.objects.filter(pk=pk) return ClientContractType.get_queryset(qs, info) It works but I'd love to have some sort of DjangoObjectField which will encapsulate this for me and, potentially, pass arguments to the ClientContractType in some way. Have someone had this problem or knows a better solution? -
makemigrations/migrate error django.db.utils.OperationalError: no such table
I have an application that I have made using PostgreSQL as a database management system, but due to a series of things that have happened, now I want to use SQLite, but when I run makemigrations or migrate, it throws me the error django.db.utils.OperationalError : no such table: blogapp_category. With PosgreSQL it works perfectly, but I can't get it to work with SQLite ... (I have also tried to deploy the application with heroku and got the same error ...) This is the traceback: Traceback These are my models: blogapp\models.py class Category(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(to=User, on_delete=models.CASCADE) # body = models.TextField() body = RichTextField(blank=True, null=True) post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='uncategorized') # category podría ser un ManyToManyField # https://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django likes = models.ManyToManyField( to=User, related_name='blog_posts', blank=True) # null has no effect on ManyToManyField snippet = models.CharField(max_length=255) header_image = models.ImageField( blank=True, null=True, upload_to='images/') def get_likes(self): return self.likes.count() def __str__(self): return '{} - {}'.format(self.title, self.author) def get_absolute_url(self): # https://docs.djangoproject.com/en/3.1/ref/urlresolvers/#reverse return reverse('article_detail', args=[str(self.id), ]) # return reverse('home') class Meta: ordering = ['-post_date'] class Profile(models.Model): user = models.OneToOneField(to=User, null=True, on_delete=models.CASCADE) bio … -
Django - Filter by multiple values (Logical AND) on ManyToMany field
I'm trying to build job-candidate match system. I want to filter Candidates by Critical Skills needed for the Job. Every candidate has multiple skills. Every Job has multiple 'required' JobSkill which is a model that also contains importance of the skill. I want to filter my candidates and to get only candidates how have all the critical skills required for a job. A critical skill is defined as a JobSkill with importance = 3. For a given job 'job_1' I want to get the relevant candidates as follows: critical_skills = job_1.required_skills.filter(importance=3) relevant_candidates = Candidate.objects.filter('candidate how has all the critical_skills) models.py: class Skill(models.Model): title = models.CharField(max_length=100, blank=False, unique=True) class JobSkill(models.Model): skill = models.ManyToManyField(Skill) class Importance(models.IntegerChoices): HIGH = 3 MEDIUM = 2 LOW = 1 importance = models.IntegerField(choices=Importance.choices) class Job(models.Model): title = models.CharField(max_length=100, null=False) required_skills = models.ManyToManyField(JobSkill, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Candidate(models.Model): title = models.CharField(max_length=100, blank=False, null=False) full_name = models.CharField(max_length=100, blank=False, null=False) skills = models.ManyToManyField(Skill, blank=True) I would appreciate any help with this!! Thank you