Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Moving Django models to a shared library to use on multople django projects
Currently I have a large Django backend project with multiple models. I want to split the models from the source code into a separate project, a shared lib. I already copy pasted the models but I am afraid for my database. How do I best do this in practice? What about my current migrations? Is there an easy way to use Django models on multiple projects? -
Using jsonb_object_keys postgres func in Django?
is there a way to use jsonb_object_keys postgres function in django with the built in ORM ? -
How to compare values from two models
Please tell me if it is possible to check at the model level. a product with different fat content is produced. and there are buyers whose fat content is normalized. how can the check be implemented. and output to the template. eg if self.product_fat < self.customer_fat_max return self.customer And these are my models: class Product(models.Model): porduct = models.CharField(max_length=50) product_fat = models.FloatField() def __str__(self): return self.sample class Specification(models.Model): customer = models.CharField(max_length=50, unique=True) customer_fat_max = models.FloatField() def __str__(self): return self.customer -
is django-paypal server side or client side? [closed]
I'm trying to add a payment system into my Django website, I have client side however it doesn't seem very secure so I am looking at using server side paypal. Is django-paypal server side? Can anyone recommend a good tutorial to impliment server side paypal? -
How to Change OneToOne model Field Admin Default Message in Django Admin in?
I have suppose following model. class Replied(BaseModel): reply = models.OneToOneField(Review, on_delete=models.CASCADE) show_reply = models.BooleanField(default=False) replied_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name = 'Reply' verbose_name_plural = 'Replies' def __str__(self): return self.content When I tried adding more than reply to certain reply the error message by default given by Django Admin is as follow. Reply with this Reply already exists. I want certain message like this. Reply to this review already exists. How can I do that? In my opinion it should be done in admin so here is my admin.py code @admin.register(Replied) class RepliedAdmin(ModelAdmin): list_display = ( 'replied_by', 'created_at') list_filter = ('replied_by',) list_display_links = ('replied_by',) -
Get last record by date for multiple table with many-to-one relationship
I have 3 tables : class Item(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200, unique=True) image = models.URLField() class Prix_x1(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) class Prix_x10(models.Model): def __str__(self): return self.item.name prix = models.IntegerField(null=True) saved_at = models.DateTimeField() item = models.ForeignKey(Item, on_delete=models.CASCADE) What i want is to retrive the last price by 1 and by 10 for each Item in my BDD. I have already tried many things, but either it's not gives me what i want or either the request is like 20seconds I want to show the result in a table like : Thanks for your help ! -
Django: Management data is missing or...-Error
Good morning, inside my views.py I'm using the inlineformset_factory, and when writing the code inside my template this way... <form method="post"> {% csrf_token %} {{ formset.as_table }} {{ formset.management_form }} <button type="submit">Edit</button> </form> ...everything works fine the way it should! But what if I want to paste my formset inside a for-loop like this?! Where do I have to put in the management_form, because if it's missing, I'm getting an Management data is missing or ...-error! <form method="post"> {% csrf_token %} {% for form in formset %} <div> <p>Title 01<p> {{ form.data_01 }} </div> <div> <p>Title 02<p> {{ form.data_02 }} </div> ... {% endfor %} <button type="submit">Edit</button> </form> Thank you for all your help and have a great day! -
DRF permissions checking based on request data
So my view has a property called member which returns the associated member object for each view. This is my Member model. Class Member(models.Model): @cached_property def permissions(self): # implementation to calculate perms return [] user = models.ForeignKey('users.user', on_delete=models.CASCADE) box = models.ForeignKey('uploads.Box', on_delete=models.CASCADE) created_at = models.DateTimeField() So I also have this model called Role. Class Role(models.Model): name = models.CharField() permissions = BitField() And I have a RetrieveUpdateDestroyView for the role along with a serializer. Class RoleSerializer(ModelSerializer): permissions = BitFieldSerializer() Class Meta: model = Role fields = '__all__' Class RoleRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyView): serializer_class = RoleSerializer permission_classes = [IsAuthenticated] lookup_field = 'id' The member property of the view is based on the request's user. I want to make sure that the member can give only the permissions they have to the role. How can I achieve this? -
Is my `asgi.py` file being ignored in Django
When I run python manage.py runserver my asgi.py file does not get called at all. Do I have to run it with gunicorn or daphne or is it possible to run it in development mode? # asgi.py import os import django from django.core.asgi import get_asgi_application from dotenv import load_dotenv from my_app.middleware import websockets print("In ASGI.py file") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'core/.env')) django.setup() application = get_asgi_application() application = websockets(application) print("Completed") -
Django REST: ViewSet DELETE AttributeError: module 'django.db.migrations.serializer' has no attribute 'data'
DRF 3.12.2 I'm trying to create an endpoint which deletes all CategoryTargetGroups with the given category id "cat_id". Example url, this should delete all CategoryTargetGroup objects with category=61: http://localhost:8000/api/ctg-delete/?cat_id=61 However I'm getting the following error when calling it: AttributeError: module 'django.db.migrations.serializer' has no attribute 'data' The model: class CategoryTargetGroup(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False) target_group = models.ForeignKey(TargetGroup, on_delete=models.CASCADE, null=False) The view: class CategoryTargetGroupDelete(viewsets.ModelViewSet): queryset = CategoryTargetGroup.objects.all() serializer_class = CategoryTargetGroupSerializer @action(detail=False, methods=['delete']) def delete(self, request): cat_id = request.query_params['cat_id'] queryset = CategoryTargetGroup.objects.filter(category=cat_id) queryset.delete() return Response(serializer.data) Front end axios call: axios .delete(AuthUrls.API_CTG_DELETE, { headers: { authorization: "Token " + getUserToken(), }, params: { cat_id: cat_id } }) -
Why is this input value not in the POST request?
On my page i got this form splitted in several divs: <form id="myForm" action="{% url 'validate_question' %}" method="post"> <div id="questionanswers"> <h2>Antworten</h2> {% for answer in answer_info %} <div id="d{{forloop.counter}}"> <p> <label><b>{{forloop.counter}}. Antwort</b></label> <button id="b{{forloop.counter}}" type="button" value={{forloop.counter}}>Antwort löschen</button> <input name="answer{{forloop.counter}}" class="max" type="text" value="{{ answer.3 }}"></input> <input type="hidden" name="answer_id{{forloop.counter}}" value="{{answer.0}}"/> <input type="hidden" name="answertext_id{{forloop.counter}}" value="{{answer.2}}"/> </p> <p> <label>Antwort richtig?</label> <input name="answercorrect{{forloop.counter}}" type="checkbox" {% if answer.1 %} checked="checked" {% endif %}></input> </p> </div> {% endfor %} </div> <div id="buttons"> <input type="submit" value="Änderungen speichern." /> </div> There is loop which loads all the answers to a question in this case, which the user then can edit and submit the form to save the changes. All the input in the first <p> gets transmitted without a problem. But for some reason the answercorrect<id> input of the second <p>isn't in my POST data after submitting the form. If I add some hidden input to the second paragraph it's there but i cant figure out what the problem with the checkbox input is. -
Dokku postgres: Is the server running on host "localhost"
I created dokku and created my app. Every code is working fine,but somehow my app and database is not working together.I am getting this error when i am trying to git push: Error django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Here are my steps to create and link the app: git clone https://github.com/link dokku apps:create welpie dokku postgres:link welpiedb welpie cd welpie git remote add dokku dokku@dokku.me:welpie git remote set-url dokku dokku@<ipadress>:welpie git push dokku main:master I get no error in any of these steps.I also check if welpiedb is running fine. Dokku postgres:info welpiedb Dsn: postgres://postgres:**@dokku-postgres-welpiedb:5432/welpiedb Status: running Settings.py DB_SETTINGS = dj_database_url.parse('postgres://postgres:**@dokku-postgres-welpiedb:5432/welpiedb') Can somebody help me on this please? -
When I send it as a put in Django, it creates a new item
If you have code like the one below and try to update an item with put from JavaScript, a new item with the content you tried to update will be created. How can I update the item without creating a new item? Also, is it okay to write the update definition the same way as the create definition? Django class EntrySerializer(serializers.ModelSerializer): project = ProjectSerializer(read_only=True) project_post = serializers.PrimaryKeyRelatedField( queryset=Project.objects.all(), write_only=True) class Meta: model = Entry fields = '__all__' def create(self, validated_date): validated_date['project'] = validated_date.get('project_post', None) if validated_date['project'] is None: raise serializer.ValidationError("project") del validated_date['project_post'] return Entry.objects.create(**validated_date) def update(self, instance, validated_date): validated_date['project'] = validated_date.get('project_post', None) if validated_date['project'] is None: raise serializer.ValidationError("project") del validated_date['project_post'] return Entry.objects.create(**validated_date) React / JavaScript export const editEntry = ({ id, entry }) => (dispatch, getState) => { axios.put(`${url}/api/entries/${id}/`, entry, tokenConfig(getState)) .then(res => { dispatch({ type: EDIT_ENTRY, payload: res.data }) }).catch(err => console.log(err)); } -
Can not find a tag which contains emoji using BeautifulSoup
I convert my json from django request body to dict data = json.loads(request.body) then i try to find some tag which contains specific emojis using re module. data[...]['message'] contans text, and sometimes there can be emojis ... soup = BeautifulSoup(html, 'lxml') text = data[...]['message'].replace(')', '\)').replace('(', '(\(').strip() review = soup.find('p', itemprop='reviewBody', text=re.compile(text)) # always returns None if there is at least one emoji -
Django Handling Multiple Forms
I'm currently working on To-Do App using Django. I want to add new task items under a to-do using Modal. But the Task Form is not displayed/rendered. As I'm rendering two view function in one html file and two different forms. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey(Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseNotFound, JsonResponse, HttpResponseRedirect from .models import Todo, Task from .forms import * from django.utils import timezone from django.contrib.auth.forms import UserCreationForm from django.views.decorators.csrf import csrf_protect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.views.generic import View from django.contrib.auth.models import User from django.core.paginator import Paginator def register(request): form = userRegisterForm() if request.method == 'POST': form = userRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password2') return redirect('login') else: form = userRegisterForm() context = {'form': form} return render(request, 'todo/register.html', context) def logoutUser(request): logout(request) return redirect('login') @login_required(login_url='login') def home(request): todo_form = TodoForm() current = timezone.now() todo_items_upcoming = Todo.objects.filter(user_id=request.user, completed=False).order_by('-date_created') todo_items_completed = Todo.objects.filter(user_id=request.user, completed=True).order_by('-date_created') … -
django - Filtering for multiple query parameters
Put the parameters in the postman url. When I sent it like this, [GET]http://127.0.0.1:8000/devices?device_uuid=aaa&fcm_token=bbb&user=ccc i want the resulting values to be device_uuid, fcm_token, and user_id all applied filter values. views.py class DevicesViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): queryset = Devices.objects.all() serializer_class = DevicesSerializer def get_queryset(self): queryset = Devices.objects.all() device_uuid = self.request.query_params.get("device_uuid", None) # fcm_token = self.request.query_params.get("fcm_token", None) if device_uuid is not None: queryset = queryset.filter(device_uuid=device_uuid) return queryset models.py class Devices(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="Devices", null=True ) device_uuid = models.CharField(max_length=45, null=True) fcm_token = models.BigIntegerField( null=True) user_agent = models.CharField( max_length=45, null=True) use_yn = models.CharField( max_length=1, default="Y") device_crt_dts = models.DateTimeField(auto_now_add=True) device_modify_dts = models.DateTimeField(auto_now_add=True) Which code value should I add? -
Version conflict django-oauth-toolkit>0.12.0 and urllib3==1.25.11
Why I have a problem with updating Django from version 1.11.29 to 2.0.13. When updating the library django-oauth-toolkit to version 1.2.0 - version support Django 2.0 I receive an error: __version__ = pkg_resources.require("django-oauth-toolkit")[0].version pkg_resources.ContextualVersionConflict: (urllib3 1.25.11 (/.virtualenvs/django-oauth-tookit-conflict/lib/python3.6/site-packages), Requirement.parse('urllib3<1.25,>=1.21.1'), {'requests'}) -
When to use "from django.contrib.gis.db import models"?
I am working on a django project that uses Postgres with the PostGIS extension enabled. When creating my models, should I use the following code in all my django apps or only in apps that contain models with geolocation fields? from django.contrib.gis.db import models -
Setting up audit logs/trails in Django (Django REST)
I'm looking for a really decent package/middleware for django (Django REST) that helps logs an audit trail of HTTP requests and response activity within a Django app. Ideally, I'd want to store the data in a redis cache, AWS S3 or some other datastore, but logging to a text file also sounds reasonable. So far, I haven't a good package out there. I'd like to create a custom audit logging open source solution out there. But before I do, I wanted to find out if anyone knows something good that already exists! Otherwise, I guess it's rock and roll for custom dev <3. -
how to serve django media files in LiteSpeed webserver
I deployed a django project on shared host , and my media files did not loadedproduct image not load what config do i do for fix this issue? setting.py STATIC_URL = '/site_statics/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets") ] STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn", "static_root") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "static_cdn","media_root") # MEDIA_ROOT = '/static_cdn/media_root' urls.py: urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('admin/', admin.site.urls), path('<lang>/', home_page, name='home'), path('', home_redirect), path('<lang>/products/', include('products.urls')), path('<lang>/', include('agents.urls')), path('<lang>/', include('information.urls')), path('<lang>/', include('media_app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django REST - @action decorator "Unresolved reference 'action'"
I'm trying to use the @action decorator in my views.py but it's not being recognized. Is it deprecated or something? class CategoryTargetGroupDelete(APIView): queryset = CategoryTargetGroup.objects.all() @action(detail=False, methods=['delete']) def delete(self, request): cat_id = request.query_params['cat_id'] queryset = CategoryTargetGroup.objects.filter(category=cat_id) queryset.delete() return Response(serializer.data) -
How to get data from database when a new message is there
I would like to create something like cat. A page that displays you all your messages and the ability to go to the inbox of each. Now I confront myself the problem of how to do that when a new message is sent by a user of any Inbox he can display on the first page where you can show all the cat from a user, and this with Django Channels. Does anyone have an idea ?? -
How to allow permissions to patch and delete for author and admin at the same time?
I am a little bit lost how can I at the same time write has_object_permission(For author) and has_permission(For admin)in the same class, won’t one overwrite another? Or there is another way to do this? -
How to convert a Django queyset containing DateTimeField into a Pandas datetime index?
I have a model with a DateTimeField and I would like to create a datetime index with it. The idea is to then compare the datetime indexes with another datetime indexes called ranges. The model is very simple: class Candle(models.Model): dt = models.DateTimeField() The Pandas datetime index : start = timezone.make_aware(datetime.combine(date(2018, 1, 1), datetime.min.time())) end = timezone.now().replace(minute=0, second=0, microsecond=0) ranges = pd.date_range(start=start, end=end, freq='H') print(type(ranges)) <class 'pandas.core.indexes.datetimes.DatetimeIndex'> The Django QuerySet : dt = Candle.objects.filter(market=m).values('dt') print(dt) <DataFrameQuerySet [{'dt': datetime.datetime(2021, 3, 2, 6, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 2, 5, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 2, 4, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 2, 3, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 2, 2, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 2, 1, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 2, 0, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 23, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 22, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 21, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 20, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 19, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 18, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 17, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 16, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 15, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 14, 0, tzinfo=<UTC>)}, {'dt': datetime.datetime(2021, 3, 1, 13, … -
How to send/post a foreign key Id from JavaScript to Django rest framework using fetch api?
I am new to Django Rest Framework and I am having a hard time in posting a foreign key into the database in javascript. I am using the Fetch API to do this. Whenever I try to post, the foreign key's value is outputted as null. It should be the foreign key's Id. Below is my Model.py from django.db import models # Create your models here. class Subject(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.FloatField(default="1.00") def __str__(self): return self.name class Instructor(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email_address = models.EmailField(max_length=100) password = models.CharField(max_length=50) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=True) date_joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.first_name Below is my Serializer.py from rest_framework import serializers from .models import Subject, Instructor class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' class InstructorSerializer(serializers.ModelSerializer): class Meta: model = Instructor fields = '__all__' depth = 1 Below is my Views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from .models import Subject, Instructor from .serializers import SubjectSerializer, InstructorSerializer # Create your views here. class SubjectViewSet(viewsets.ModelViewSet): serializer_class = SubjectSerializer queryset = Subject.objects.all() @action(detail=False, methods=['GET']) def get_total(self, request): total_subject = self.get_queryset().count() return Response(total_subject) @action(detail=False, methods=['GET']) def get_newest(self, …