Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can we run console command by django function
I want to run this command with the help of django function can we do this? python manage.py rebuild_index i want this when post_save function run how i can do this? -
How to upload document on an Article using article id when it does not even exists
currently i am in a very weird situation. I am trying to upload document using article id and user id to an article. But the issue is when I try to select article id from the document model, it gives error that article doesnt exists. And tbh that is true, because how can i upload document to an article when it doesnt even exists. So how can i use article id in such situation? Below is my document model in which i am sending user id and article id for uploading document. documentmodels.py class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") user_fk_doc=models.ForeignKey(User, on_delete=models.CASCADE, related_name="users_fk_doc") article_fk_doc=models.ForeignKey(Article, on_delete=models.CASCADE, related_name="articles_fk_doc") document=models.FileField(max_length=350, validators=[FileExtensionValidator(extensions)], upload_to=uploaded_files) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0, blank=True) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) and below is the articles models, class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) published=models.DateTimeField(auto_now_add=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") -
Django Admin Limit Model list
i have this models in my project: ` class Luce(models.Model): appartamento = models.ForeignKey('Appartamento', on_delete=models.CASCADE, related_name="bollette") numero = models.IntegerField() data = models.DateField() dal = models.DateField() al = models.DateField() importo = models.FloatField() file = models.FileField(upload_to='fatture/%Y/%m/%d') def __str__(self): return "Fattura Luce dal " + str(self.dal.strftime('%d/%m/%Y')) + " al " + str(self.al.strftime('%d/%m/%Y')) def file_link(self): if self.file: return format_html("<a href='%s'>Scarica</a>" % (self.file.url,)) else: return "No allegato" file_link.allow_tags = True class Meta: verbose_name = "Luce" verbose_name_plural = "Luce" class Appartamento(models.Model): nome = models.CharField(max_length=50) camere = models.IntegerField() class Meta: verbose_name = "Appartamento" verbose_name_plural = "Appartamenti" def __str__(self): return self.nome ` What i would do is to limit the visibility of model "Luce" in the way some users ( staff user ) can access only to their "Appartamento" My admin.py is this one: ` class LuceAdmin(admin.ModelAdmin): list_display = ('data', 'dal', 'al', 'importo', 'file_link') search_fields = ['data', 'dal', 'al'] list_filter = ('appartamento',) admin.site.register(Luce, LuceAdmin) class AppartamentoAdmin(admin.ModelAdmin): list_display = ('nome', 'camere') admin.site.register(Appartamento, AppartamentoAdmin) ` What ca i do ? I mean some staff user has limited access only to objects of type "Luce" assigned to one specific category "Appartamento". THanks -
Server Error (500) - rendering lists in django
I am getting a Server Error (500) when i'm trying to render a list to one of my web pages in Django. def find_jobs(request): job_details = [job_position for job_position in JobPost.objects.all() if job_position.Status is not JobPostStatus.Closed] Seeker_applied_job = seeker_applied_job() print(job_details) content = {'title': "Job seekers", 'jobs': job_details, 'message': "to view job postings", } print(content) return render(request, 'seek_job.html', content) the print(job_details) line returns this [<JobPost: Opportunist at OpportunityM>, <JobPost: Digital Marketer at OpportunityM>, <JobPost: Nurse at NHS>] When I remove 'jobs': job_details from content, the seek_job.html page renders. But when I try adding it back, it returns a Server Error (500) page. I have another view function similar to this one which works fine. -
Implementing JS in Django templates
I have a list of ingredients, for every ingredient, I would like to give the option to delete the current ingredient via using a popup that asks the user "are you sure they want to delete this?" If confirmed, I want that ingredient to be deleted. Currently, no matter which ingredient I choose to delete, it always the deletes the first ingredient in the list. For example, if the list of ingredients is ['cheese', 'lettuce'], I click remove ingredient under lettuce, and it will still delete cheese. I've never used javascript in Django templates before, I think I need to pass the ingredient into the openPopup function, but I'm not sure how to do it, any help would be appreciated! I've looked at the Django docs for using JS in templates but it's not crystal clear to me. How do I go about doing this? <div class="ingredient-container"> {% for ingredient in ingredients %} <div class="ingredient"> <b>{{ ingredient|title }}</b><br> <small><a href="{% url 'core:edit_ingredient' ingredient.id %}">Edit Ingredient</a></small> {% empty %} {% endfor %} <!-- This button opens the popup up to confirm deletion of the ingredient--> <button class="remove" type="submit" onclick="openPopup()">Remove Ingredient</button> <div class="popup" id="popup"> <h2>Delete Confirmation</h2> <p>Are you sure you want to … -
Django multiple models that have a foreign key to another model
Example: A system that processes different types of csv files. The different types of csv files have different content inside. So the current way im thinking about modeling this is: File model that stores some generic info about each file processed, like the name, date etc. class File(models.Model): name = models.CharField() Then models that stores the content for each type of file and these models link back to the File model: class Example1File(models.Model): file = models.ForeignKey(File, related_name=example_file_1_content) ... (all columns for this file) class Example2File(models.Model): file = models.ForeignKey(File, related_name=example_file_2_content) ... (all columns for this file) Is there an easy way for example to loop through the files table and get the content for each file and django would just know in which table to go look? for file in File.objects.all(): file.??? Or would I only be able to do this by storing a type field on the file and then getting the content with the reverse relationship like this. for file in File.objects.all(): if file.type == FileTypes.ExampleFile1: file.example_file_1_content But what if there are a lot of different file types? Im still in the process of learning about how django handles relationships/reverse relationships so I might just not be there yet … -
django issue : i get erro 404 page note found
I try to write a django code fo a registration page the error snip and code: enter image description here """ """ -
Django configuration in PyCharm
After few years using Mac and Linux for my dev I have to pass on windows now. I have a project which run on docker-compose and that works very well on Mac and Linux but on windows I have some configuration problems with PyCharm. If I run the docker compose by hand: works well If I run the project threw the "run" or "debug" in pycharm: works well But when I try to run the "manage.py command" threw pycharm I got this traceback: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. That would be just a small problem but it seems that Pycharm does not recognize django in the docker interpreter because all the django specific code is highlighted and the autocompletion doen't work anymore. Basic example: if I use {% load ... %}, the load tag is not recognized. It is definitly a problem in the configuration of pycharm but I can not find where it is. Any idea? -
How can I retrieve my post request using JavaScript
I have two projects, the first one is Node.JS. jsonobj = JSON.stringify(generateMockData) xhrToSoftware.send(jsonobj); xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true); xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhrToAPI.send(jsonobj); It's sending data to the second project Django Python. I can receive the data using my views.py. post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible? for example: <script> //get the data that posted by the node.js </script> UPDATE: I tried using the answers below like this one: fetch('http://127.0.0.1:8000/path/') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => console.error(error)); but I'm having an error it says that: SyntaxError: Unexpected token '<', "<!-- <d"... is not valid JSON I think that's because I'm returning an html file in my views.py: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return render(request, 'waterplant/iot/data.html') so, I change it to jsonresponse like this: def data(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) # for simulation value = post_data.get('data') return JsonResponse({"msg": value}, status=200) After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. … -
Example of jqgrid with python
So I've cloned this https://bitbucket.org/romildo/django-jqgrid-demo.git as I am looking for a working example of jqgrid with django. I've been updating the code (as this seems like it was written for a version 2 of django and I'm workng on 4.1) I'm completely stumped by the lines from jqgrid import JqGrid giving me this error ModuleNotFoundError: No module named 'jqgrid' I cannot find a reference to jqgrid within pip and I cannot install one (jqgrid is not a python package) I understand that jqgrid is a javascript component around jquery but how do I get that to work in Python I have google for django-jqgrid and on youtube. None of the answers provide enough information to get a simple working example up. There seems to be an assumption that everything is installed and I'd like to understand what is required where and how to reference What am I missing? -
Convert SQL Query into Django Query ORM
I have this sql query, I need to use Django ORM format delete from foodies_orderstall as os where os.order = <order-id> and not exists ( select * from foodies_ordermenu as om where om.order_stall = os.id ); -
Converting a complex dictionary list to a dictionary
I would like to convert this dictionary list below into a dictionary data=[ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } ] And I would like to have this result, just the starting brackets that we change to {..} data={ { 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } } -
ImageField storage options based on settings
I am using django-storages with the Azure backend. I would like to use the local provided Django solution when running locally and the Azure storage when running in production. How would I change this based on the settings? Do I just use an IF statement below these? # local image = models.ImageField(upload_to="profile_pics", blank=True, null=True) # production image = models.ImageField(upload_to="profile_pics", blank=True, null=True, storage=AzureMediaStorage()) -
What's the diffrence bettwen timezone.now and auto_now_add parameters in DateTimeField field in Django models?
I'm writing my first Django app - blog. When creating Post model I'm asked to create publish and created fields with timezone import. publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) It's explained that "By using auto_now_add, the date will be saved automatically when creating an object" and "timezone.now returns the current datetime in a timezone-aware format". So it seems to me that they both same job. Why not use default=timezone.now in both fields? What's the difference? It's my first question so sorry in advance if I made some mistakes. -
PgAdmin Queries fast Django orm very slow
When I write a query via pgAdmin, I get very fast results, but the queries made with Django orm are very heavy, what could be the reason? database connection as below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user', 'USER': 'users', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'data': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'data', 'USER': 'datas', 'PASSWORD': 'toor', 'HOST': '192.168.1.1', 'PORT': '5432', }, } The query I sent with pgAdmin PgAdmin 97 msec SELECT COUNT(id) as noti FROM notification WHERE created_at BETWEEN '2022-11-15 00:00:00' AND '2022-11-15 23:59:59' The query I sent with django Django 20.44 s from django.utils.timezone import get_current_timezone from datetime import datetime get_today = datetime.now(tz=get_current_timezone()) Notification.objects.using('data').filter(created_at__year=get_today.year, created_at__month=get_today.month, created_at__day=get_today.day).count() I'm making multiple database connections with Django the second database is running very heavy query how can I fix this -
solr search returning 3 result but when i it try to iterate object is not working
I have implement solr search and try to run this in a shell when i fetch all record it gave count 3 it's correct but when i try to display title and body it's gave me an error please let me help this solr-9.0 python3 and django 4 for solr > post_text.txt templates/search/indexes/blog/post_text.txt {{ object.title }} {{ object.tags.all|join:", " }} {{ object.body }} in search_indexes.py from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish') def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().published.all() Now in shell from haystack.query import SearchQuerySet from blog.models import Post sqs = SearchQuerySet().models(Post).all() sqs.count() # return 3 but when i run this loop then geting error for x in sqs: x.object Traceback (most recent call last): File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2018, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 2, in <module> File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/haystack/models.py", line 81, in _get_object self._object = self.searchindex.read_queryset().get(pk=self.pk) File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/query.py", line 636, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/media/jaskaran/7707D65C2F49F611/study/django/ven/lib/python3.8/site-packages/django/db/models/query.py", line … -
How to fix IntegrityError 1048 in django
So, i just made a upload feature to insert data into databases. Data inserted successfully into the database but show an error messages Before, i tried to change the column name on my excel .. i thought it was the problem, but after i undo the changes to default .. error still happened. Here's my view code Views.py if 'uploaddatasiswa' in request.POST: dataset = Dataset() new_siswa = request.FILES['uploadSiswa'] if not new_siswa.name.endswith('xlsx'): messages.info(request, 'Format tidak valid!') else: imported_data = dataset.load(new_siswa.read(),format='xlsx') for data in imported_data: tambah_siswa = modelUser( username = data[0], namadepan = data[1], namabelakang = data[2], password = data[3], email = data[4], jeniskelamin = data[5], tanggallahir = data[6], agama = data[7], alamat = data[8], telepon = data[9], role = "siswa" ) tambah_siswa.save() return HttpResponseRedirect("/admin/daftarsiswa") return render(request,'tambahsiswa.html') Models.py class modelUser(models.Model): namadepan = models.CharField(max_length=200, null=False, blank=False) namabelakang = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) password = models.CharField(max_length=200, null=False, blank=False) email = models.CharField(max_length=200, null=False, blank=False) jeniskelamin = models.CharField(max_length=200, null=False, blank=False) tanggallahir = models.DateField() agama = models.CharField(max_length=200, null=False, blank=False) alamat = models.CharField(max_length=200, null=False, blank=False) telepon = models.CharField(max_length=200, null=False, blank=False) jumlahkelas = models.CharField(max_length=200, null=True, blank=True, default=0) role = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.username Tables -
How can I get value from one function in another function in Django, views()
Hello I am new to Django I want to get latitude and longitude from myview1 function to myview function so that I can Post that values and put into the relevant code. PLease Can anyone guide me regarding this? def my_view1(request): latitude='latitude' longitude='longitude' context = {'latitude':latitude, 'longitude':longitude} my_view(context) return (context) @csrf_exempt @require_http_methods(["POST"]) def my_view(request,context): if request.method == "POST": # value_data=(my_view1(data=request.POST)) value_data=my_view1().objects.all() latitude = request.POST.get(value_data['latitude']) longitude = request.POST.get(value_data['longitude']) # In this example I am reading a file with (time, x, y) as dimensions xarr = xr.open_rasterio('/home/shaheer07/New Rasters/image_factors.tif') # Slice one of the bands img = xarr[0, :, :] #Use the .sel() method to retrieve the value of the nearest cell close to your POI pixel_value = img.sel(x=latitude, y=longitude, method="nearest") image = '/home/shaheer07/New Rasters/image_factors.tif' with rasterio.open(image) as f: # Load metadata meta = f.meta # Use the transform in the metadata and your coordinates rowcol = rasterio.transform.rowcol(meta['transform'], xs=latitude, ys=longitude, zs=None) y = rowcol[0] x = rowcol[1] # Load specific pixel only using a window window = Window(x,y,1,1) raster_values = f.read(window=window) return JsonResponse(pixel_value,raster_values, status=status.HTTP_201_CREATED) else: return JsonResponse('Nothing') -
Django CSRF Protection GraphQL API
I do have a graphqlAPI which I use for CRUD Operations to my database. The authentication is tokenbased. So if an user wants to make cruds (mutations) to my database, it needs a valid token in order to do that. What I dont know is if my graphql API is also protected against CSRF attacks as I exempt this protection with csrf_exempt without csrf_exempt it needs a csrf token. Is there a way to ask for a valid csrf token without sending it over the frontend ? The graphql api is only used for the backend for inserting data into the database in which I cant get the csrf token over the frontend. Backend/Frontend: Django Database: Mongo Thanks -
How to include staticfiles in wsgi django project?
Today I ran into a problem connecting static files to my project. If I run django app with command: python manage.py runserver <ip>:<port>then static files are found. If I run the django app as a wsgi service (systemctl start myapp), I get an error that no static files were found. My project in /home/alevt/health_check. I have next structure of project: ---- client -------- manage.py -------- my.ini -------- app ------------ urls.py ------------ settings.py ------------ wsgi.py -------- health_app ------------ urls.py ------------ static --------------- scripts ----------------- myscript.js ------------ templates --------------- index.html settings.py INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'health_app', ...] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') index.html <script src="{% static 'scripts/myscript.js' %}"></script> ERROR Not Found: /static/scripts/create-table.js my.ini [uwsgi] http = 10.107.14.161:8000 module=app.wsgi:application chdir = /home/alevt/health_check/client/ wsgi-file = /home/alevt/health_check/client/app/wsgi.py virtualenv=/home/alevt/health_check/env single-interpreter = true enable-threads = true master = true And my file of service Description=uWSGI instance to serve myproject [Service] ExecStart=/usr/bin/bash -c 'uwsgi --ini /home/alevt/health_check/client/my.ini' KillSignal=SIGQUIT Type=notify [Install] WantedBy=multi-user.target``` -
Multiple CN LDAP integration in Django project
I want to use multiple CN names in LDAP configurations. I tried to use AUTH_LDAP_REQUIRE_GROUP = "CN=GROUP_NAME1,OU=MSG Distribution Groups,DC=XXX,DC=XXX,DC=XXX" How can I allow multiple groups in CN? Thanks in advance. -
it safe to request url in django? [closed]
I need to check if user submitted url really exists. but I found in some sources that it is not safe to send request from django to the site for this. do you have any suggestions django used to have validation for this but then removed it for security reasons I found code samples: but verify_exists is deprecated for security reasons and has been removed in Django 1.5 -
Cannot connect to redis while using Sentinels in django-redis
Currently I am trying to integrate redis into my django project which is docker based. I was able to integrate redis using the DefaultClient but it doesn't work for SentinelClient My settings.py looks like this: DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' SENTINELS = [ ('redis://9b39d2b0eb5d', 26379), ] # 9b39d2b0eb5d is the ip of redis sentinel container CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis-queue-1:6379', 'OPTIONS': { 'SENTINELS': SENTINELS, # django_redis.client.SentinelClient 'CLIENT_CLASS': 'django_redis.client.SentinelClient', 'CONNECTION_POOL_CLASS': 'redis.sentinel.SentinelConnectionPool', }, } } It doesn't throw any exception, django just gets stuck on loading -
Django rest framework updating a OneToOne field
I have a User model that inherits from AbstractUser which has an email field. And a profile model that has an OneToOne relation with the User model class User(AbstractUser): email = models.EmailField(unique=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(max_length=13, validators=[phone_regex], unique=True, null=True, blank=True) birth_date = models.DateField(blank=True, null=True) about = models.TextField(max_length=2000, blank=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}" view.py class ProfileViewSet(ModelViewSet): .... @action(detail=False, methods=["GET", "PUT"], permission_classes=[IsAuthenticated]) def me(self, request, *args, **kwargs): profile = Profile.objects.get(user_id=request.user.id) if request.method == "GET": serializer = ProfileSerializer(profile) return Response(serializer.data) elif request.method == "PUT": serializer = ProfileSerializer(profile, request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): user = CurrentUserSerializer() def update(self, instance, validated_data): user_data = validated_data.pop('user') user_ser = CurrentUserSerializer(instance=instance.user, data=user_data) if user_ser.is_valid(): user_ser.save() instance.phone = validated_data.get('phone', instance.phone) instance.birth_date = validated_data.get('birth_date', instance.birth_date) instance.about = validated_data.get('about', instance.about) instance.save() return instance class Meta: model = Profile fields = [ 'id', 'user', 'phone', 'birth_date', 'about', ] Now when I try to update a user profile I get status: 400 Bad Request error { "user": { "email": [ "user with this email already exists." ] } } using patch instead of put or partial=True doesn't change anything I still get this error. What can I do here? -
Django: Async POST Request
I am trying to make an async post request using the following approach: First of all, I have defined a fixture to return the client: @pytest.fixture(scope="session") async def async_app_client(): async with AsyncClient() as client: yield client Then i use the client to execute the post request. @pytest.mark.asyncio @pytest.mark.django_db() async def test_single_statistic_task_monitoring( async_app_client, statistic_object_univariate ): print(reverse("statistics-list")) response_post = await async_app_client.post( reverse("statistics-list"), statistic_object_univariate, format="json", ) The error i am getting is: AttributeError: 'async_generator' object has no attribute 'post' However, for examples online many use httpx AsyncClient to make the post request. What is the problem here?