Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I model a database view in Django if it doesn't have a primary key?
I have a database view that relates 2 companies by foreign keys like so: DB company_view: company1_id FK to Company, company2_id FK to Company, some_description text I try model in Django as unmanaged like so: class CompanyView(models.Model): company1 = models.ForeignKey(Company, related_name='company1_id', parent_link=True) company2 = models.ForeignKey(Company, related_name='company2_id', parent_link=True) class Meta: managed = False db_table = 'company_view' But it throws exception like: psycopg2.errors.UndefinedColumn: column company_view.id does not exist It doesn't make sense to have a primary id key, so is there any way around this? Thanks -
Python: Calculate time between current time and last login. (Automated Communication)
I'm trying to make a celery task that would send a basic reminder to our users. So in our automated communication project, we have these tasks: As you can see there are few actions that are different. So for now I have created a logic that fetches all the users from the DB and then continues by checking the time difference. But for now, I only have set-up for 2 hours or more. How should I use it correctly? I do not want to re-write each if statement because it's bad practice. How should I make it clear and reduce the system load? @app.task def check_registered_users(): from apps.users.models import User from apps.notifications.models import AutomatedCommunicationNotifications day_start = datetime.utcnow().date() day_end = day_start + timedelta(days=1) users = User.objects.filter(is_active=True, date_joined__range=(day_start, day_end)) users_that_received_notification = AutomatedCommunicationNotifications.objects.all().values('user__id') excluded_users = users.exclude(id__in=users_that_received_notification) for user in excluded_users: if user.last_login < user.last_login + timedelta(hours=2): # Sign-up uncompleted Push notification 2 hours after last login template = SiteConfiguration.get_solo().automated_comms_signup_uncompleted send_plain_email_task( email=user.email, subject=template.subject, html_message=template.content, from_email=f'{settings.EMAIL_FROM_PREFIX} <{settings.DEFAULT_FROM_EMAIL}>', ) -
How can I make the get_random_string Django module to return only numerical values?
What should I do to my simple code below, so that it only returns numerical values? >>> from django.utils.crypto import get_random_string >>> get_random_string(10) >>> 'PhaWT9X02U' Something like: 1067603657 And if it is possible, can you recommend an id field generated in this manner? -
How is PUT request handled in Django REST Framework?
I need to clarify how DRF works. Imagine there's a Django REST Framework application that manages two ressources: departments and employees: class Department(models): name = models.CharField(primary_key=True) class Employee(models): name = models.CharField() dept = models.ManyToManyField() with serializers: class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ('name', ) class EmployeeSerializer(serializers.ModelSerializer): dept = DepartmentSerializer class Meta: model = Employee fields = ('name', 'dept', ) Requesting (GET /employees/1) an employee returns the department as a nested object, which is good. What does DRF do, when I send PUT /employees/1 { "department": "sales" } Which part of the program does this request go through? I would assume First using dispatching a view is selected In the update Method (if overwritten) of the view, I can assign a serializer The request and Primary Key of the target are available through self.request and pk of the method handler What I end up doing now is to write a bloated update method, which kind of does not feel the way it should be where I check for every attribute if it is in the request and if yes than update it. def update(self, request, pk=None): employee = Employee.objects.get(pk=pk) if self.request.data.get("name"): employee.name = self.request.data.get("name") if self.request.data.get("dept"): employee.dept.add(self.request.data.get("dept") employee.save() … -
django-autocomplete-light template not rendering autocomplete widget
I am trying to make a search field on my homepage where you search entries by tag, and within that search field as you type in letters it should suggest you tags that contain what you have typed so far. I am using django-taggit for tags. I have followed this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/taggit.html It has support for django-taggit. template <div class="search-container"> <form method="post"> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} <button type="submit">Search</button> </form> </div> urls.py # AUTOCOMPLETE URL url(r'^tag-autocomplete/$', views.TagAutocomplete.as_view(), name='tag-autocomplete'), forms.py class SearchForm(autocomplete.FutureModelForm): class Meta: model = Intrare fields = ('tags',) widgets = { 'tags': autocomplete.TaggitSelect2('intrari:tag-autocomplete') } models.py class Intrare(models.Model): tags = TaggableManager() def __str__(self): return self.titlu views.py class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): intrari = [intrare.tags for intrare in Intrare.objects.filter(public=True)] tags = reduce(lambda x, y: x | y, [tags.get_queryset() for tags in intrari]) tags = [tag.name for tag in tags] qs = Tag.objects.filter(name__in=tags) if self.q: qs = qs.filter(name__contains=self.q) return qs Here is the result. The widget does not show properly -
Password is displayed as text in the admin panel (not hashed)
There is a CustomUser model inherited from AbstractUser. When registering a model in the admin panel, the password is displayed as text, that is, the type of this field is text, not password. I know that this problem can be solved if, together with the model, the ModelAdmin class is registered, in my case it will be CustomUserAdmin inherited from UserAdmin from django.contrib.auth.admin, and the password will be displayed correctly, but then the fields from CustomUser will not be displayed (as if the CustomUser model is registered, but only the fields of the User model will be displayed, when using a class inherited from the above-mentioned UserAdmin). What to do with this, please tell me! -
Python list value show in html table
Following show my python return: return render(request,'school\Views\Spredictions.html'{'len':length,'final':Ol_result,'data':marks_sheet}) Here, final : - ['pass','pass',''fail,'fail'] like this following show the my html code <tbody> {%for m in data%} <tr> <td>{{m.student_name}}</td> <td>{{final}}</td> </tr> {%endfor%} </tbody> I want to show one by one value in table interface, but show like that output of table How to solve this problem. Any one can help me Thank you -
Annotating single model instance (instead of queryset) in django
So, I have a Post model which contains PostVotes from users class Post(models.Model): voters = models.ManyToManyField(User, through="PostVote") #other stuff and the post vote can have a state of either "upvote" or "downvote" (I know I should be using enums or a bool for this before I start receiving those comments) and in many cases I need to count the total score of the object for the frontend. When I have the posts in a queryset, the following solution is working well: posts = Post.objects.all().annotate(vote=models.Sum( models.Case( models.When(postvote__state="upvote", then=1), models.When(postvote__state="downvote", then=-1), default=0, output_field=models.IntegerField() ) )) However, there are many cases where I want to do a similar thing but instead of a queryset I have just a single instance. How do I do this? Trying the above solution gives 'Post' object has no attribute 'annotate' -
Update model data after javascript alert button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. How exactly can I do this? My JS is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } Views.py: def acceptdonation(request): donations = Donation.objects.all() context = {} return render(request, 'acceptdonation.html', context) -
DJANGO REST FRAMEWORK IMAGE UPLOAD ["The submitted data was not a file. Check the encoding type on the form."]
I can't seem to upload an image to my project. I always get this error when i try to submit the form from the frontend : ["The submitted data was not a file. Check the encoding type on the form."] I've found some answers regarding the base64 encoding of the image but i can't seem to get it to work. Any help would be much appreciated!! thanks here is the source code: Models: class Person(models.Model): name = models.CharField(max_length=30) age = models.IntegerField(default=0) dob = models.CharField(max_length=10) image = models.ImageField(upload_to='images/', null=True) def __str__(self): return self.name class Details(models.Model): party = models.ForeignKey(Person,on_delete=models.CASCADE, related_name='party_details',null=True,blank=True) adress = models.CharField(max_length=50) date = models.CharField(max_length=20) arrival= models.CharField(max_length=20) def __str__(self): return self.adress Serializers: class DetailsSerializer(serializers.ModelSerializer): class Meta: model = Details # fields='__all__' fields = ('id','party','adress','date','arrival') class PersonSerializer(serializers.ModelSerializer): party_details =DetailsSerializer(many=True) class Meta: model = Person # fields='__all__' fields = ('id','name','age','dob','image','party_details') def create(self, validated_data): named_details = validated_data.pop('party_details') details = Person.objects.create(**validated_data) for named_detail in named_details: Details.objects.create(party=details, ** named_detail) return details def update(self,instance, validated_data): named_details = validated_data.pop('party_details') details = (instance.party_details).all() details = list(details) instance.name = validated_data.get('name', instance.name) instance.age = validated_data.get('age', instance.age) instance.dob = validated_data.get('dob', instance.dob) instance.image = validated_data.get('image', instance.image) instance.save() for named_detail in named_details: detail = details.pop(0) detail.adress = named_detail.get('adress',detail.adress) detail.date = named_detail.get('date',detail.date) detail.arrival = named_detail.get('arrival', … -
UnboundLocalError ,local variable 'order' referenced before assignment
i am trying to create an ecommerce website and i want to create an order for the user,however, i got an error saying that the order is referenced before assignment but i cant understand it . kindly advise the way to solve it. Thank you i am trying to create an ecommerce website and i want to create an order for the user,however, i got an error saying that the order is referenced before assignment but i cant understand it . kindly advise the way to solve it. Thank you def add_to_cart(request, pk): product = Product.objects.get(id=pk) order_item,created = OrderItem.objects.get_or_create( product =product, user = request.user, ordered = False, ) order_qs = Order.objects.filter(user=request.user,ordered=False) if order_qs.exists(): order =order[0] if order.items.filter(product__id=pk).exists(): order_item.quantity +=1 order_item.save() messages.info(request ,"Added additional worker successfully") return redirect("ecom:product_desc",id=pk) else: order.items.add(order_item) messages.info(request ," successfully booked") return redirect("ecom:product_desc" ,id=pk) else: ordered_date =timezone.now() order =Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request," Successfully booked") return redirect('product_desc',id=pk) #context ={'desc':desc} return render(request ,'products/desc.html',context) below is the error message i got.please advise how i can fix this error model.py file class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default =1) def __str__(self): return f"{self.quantity} of {self.product.name}" def get_total_item_price(self): return self.quantity * self.product.price def get_final_price(self): … -
Issues with JSONField order_by querying fields with punctuations in the name
I'm trying to query my DB for a JSONField that I have and I want to order it by the highest core amount. The issue i'm facing is that I have punctuations in the JSON objects name, and it returns an error in Django. I'm a bit unsure how to approach this issue. Query: db = Node.objects.all().order_by("data__golem.inf.cpu.cores") Model: class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) Example of the data: { "earnings_total": 20.476530214728843, "node_id": "0x189e2688456c08efdc578250ef64044dc5fed245", "data": { "id": "0x189e2688456c08efdc578250ef64044dc5fed245", "wallet": "0x10c830138690e335d315f135d7a09728239c4512", "golem.com.scheme": "payu", "golem.inf.mem.gib": 61.35306134819984, "golem.node.id.name": "ea26j8x2r712", "golem.runtime.name": "wasmtime", "golem.inf.cpu.cores": 16, "golem.inf.cpu.threads": 32, "golem.inf.storage.gib": 32.920249938964844, "golem.runtime.version": "0.2.1", "golem.com.usage.vector": [ "golem.usage.duration_sec", "golem.usage.cpu_sec" ], "golem.com.pricing.model": "linear", "golem.node.debug.subnet": "public-beta", "golem.inf.cpu.architecture": "x86_64", "golem.srv.caps.multi-activity": true, "golem.com.scheme.payu.interval_sec": 120.0, "golem.activity.caps.transfer.protocol": [ "https", "http", "gftp" ], "golem.com.pricing.model.linear.coeffs": [ 0.0, 0.00017602265896846447, 0.0 ], "golem.com.payment.debit-notes.accept-timeout?": 240, "golem.com.payment.platform.erc20-mainnet-glm.address": "0x10c830138690e335d315f135d7a09728239c4512", "golem.com.payment.platform.zksync-mainnet-glm.address": "0x10c830138690e335d315f135d7a09728239c4512" }, "online": true, "version": "0.7.1", "updated_at": "2021-07-23T13:11:59.294294+02:00", "created_at": "2021-06-08T20:54:34.951232+02:00" }, Traceback: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/local/lib/python3.9/asyncio/tasks.py", line … -
What is wrong in if request.method == 'POST'
Please what I am doing wrong in this function of Django ? def notification_read(request, pk): if request.method == 'POST': notification = get_object_or_404(Notification, pk=pk, viewed_at=None, user=request.user) form = NotificationForm(request.POST, instance=notification) if form.is_valid(): notification.viewed_at = timezone.now() notification.save(update_fields=['viewed_at']) form.save() return redirect('users:notification') How can I do this better ? Can anybody can explain, why it does not working good? -
Django. Go from one admin page to another
I'm completely new in Django. I have a large project. I need to add a feature: bulk edit using django admin panel. I figured out how to make another action, but I don't understand how to redirect a user from one admin page to another. How can I achieve this? My action function: def apply_to_brands(modeladmin, request, queryset): mymodels = django.apps.apps.get_model(app_label='brand', model_name='Brand') brands = Brand.objects.all() data = { 'brands': brands, } return HttpResponse()<--- Here I need some logic that redirects me to another admin page and preserves info that queryset contains. -
before learning Django, should I learn SQL or MongoDB?
I want to learn Django, do I need to learn SQL or MongoDB before learning Django. any help please cause I am so confused -
why I am Getting 500 error with javascript
good day, I am using Javascript to make "PUT" method to my python3 models and I am using Django Framework Below is my Javascript function loadit(id,state){ fetch(`/user/loadpigeon/${id}`, { method: "PUT", body: JSON.stringify({ loaded: !state, }), }); alert(id + " Successfully loaded" + state + "lap:ID" );} urls.py path("loadpigeon/<int:id>/", views.load_pigeon, name="loadpigeon"), views.py def load_pigeon(request, id): if request.method == "PUT": pigeon = Mypigeons.objects.get(owner=request.user ,pk=id) data = json.loads(request.body) if data.get("loaded") is not None: pigeon.loaded = data["loaded"] pigeon.save() return render(request, 'user/add.html') #return HttpResponse(status=204) on my html console I am getting this message: Failed to load resource: the server responded with a status of 500 (Internal Server Error) -
dj-rest-auth token user authorization problem
I am begginer who needs some help. I made custom token authentication, where token was stored in localStorage with expiration date, then to know if user is logged I just check if token exists - simply as that. However now I want to use dj-rest-auth to make things easier. After loggin in with form (username, password fields) I can not figure how to check if user has logged in or redirect him from login page. Can someone help me and give phrase to search because I dont get it at all and cant find exact tutorial or just sample code. I can get token and save it to local storage const handleClick = (e) => { console.log(state.username, state.password); e.preventDefault(); axios .post("http://127.0.0.1:8080/auth/login/", { username: state.username, password: state.password, }) .then((res) => { console.log(res.data.key); window.localStorage.setItem("Token", res.data.key); }) .catch((err) => console.log(err)); and then use it (I guess) import SignIn from "./containers/SignIn"; import axios from "axios"; import { useEffect, useState } from "react"; export default function App() { const [data, setData] = useState([]); const [isVisible, setIsVisible] = useState(false); const token = localStorage.getItem("token"); useEffect(() => { axios .get("http://localhost:8080/api/product-list/", { headers: { Authorization: `Token ${token}` }, }) .then((res) => { setData(res.data); }); }, []); const handleClick = … -
Combine one-to-one and many-to-many (django)
I have a model named "db_connector" and another one "project_site". A "project_site" can have many to many relation with "db-connector". But the "project_site" should have one default db-connector. What is the best design-pattern for this? Can I combine many to many and one to one like this: Many to many relation for alternative connectors linked to a project_site and one to one for the default connector linked to a project_site? -
How to insert a member into a group in Django with a GraphQL Mutation?
I have a basic group in my django-admin-panel and I want to define a mutation, where I can add a member (user) to a group with a graphQL mutation. -
Two model in one UpdateView "Django"
my views : from .models import Settings, SocialMediaSetting class UpdateSocialMediaSetting(LoginRequiredMixin, UpdateView): model = SocialMediaSetting fields = '__all__' template_name = "staff/settings/social-media-settings-update.html" class UpdateSettings(LoginRequiredMixin, UpdateView): model = Settings fields = '__all__' template_name = "staff/settings/settings-update.html" two different class in models without any relation, I want show both in one html and one form both models has just one object -
How to put conditions in filter for ALL or Something in Django
I am getting a some_id from request. If the some_id is -1 I have to select ALL or select the particular some_id. So I want something like this - model.objects.filter(some_id = '*' if some_id_val = -1 else some_id_val) I know I can chain with if like - if some_id_val != -1: model.objects.filter(some_id = some_id_val) . . . But I want a one liner solution. -
Reverse for 'viewed-notification' with arguments '('',)' not found. 1 pattern(s) tried: ['users/notification/(?P<pk>[^/]+)/read$']
What I am doing wrong here? I think the problem in url in html . views.py def notification_read(request, notification_id): notification = get_object_or_404(Notification, pk=notification_id, viewed_at=None, user=request.user) notification.viewed_at = timezone.now() notification.save(update_fields=['viewed_at']) if request.method == 'POST': form = NotificationForm(request.POST, instance=notification) if form.is_valid(): form.save() return redirect('users:notification') else: form = NotificationForm(instance=notification) return render(request, 'auth/notifications.html', {'form': form}) urls.py path('notification/<pk>/read', views.notification_read, name='viewed-notification'), template: <tr> <td> {{ item.message }} <td> <td> {{ item.created_at }} <td> <form method="post" action="{% url 'users:viewed-notification' object.id %}" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <span class="badge badge-error"> {{ form.viewed_at }} <p><input type="submit" value="See it"/></p> </form> </span> </td> </tr> What is the problem here? Where place where I did mistake? On my opinion it is not correct wtitten url?What do you think guys?Can anybody help? -
Django-filter: add atributes to multiple input filter.fields in a search form
How to add placeholders and remove titles to multiple inputs which are rendered into a single form using django-filters module filter.py class AdsFilter(django_filters.FilterSet): class Meta: model =Advert fields={ 'title':['icontains'], 'category': ['exact'], 'location': ['exact'], } index.html <form method="GET" action="{% url 'home' %}" id="form_id"> <div class="col-md-8"> <div id="glass"> <div class="wrapper"> {{ filtered_qs_form}} {{ location.form}} <button3 id="button3"type="submit" class="btn btn-primary">Search</button3> </div> </div> </div> </form> -
PDF from html in django (full support css and static files)?
What's the best way to generate pdf file from html template with full support of css and static files. I would like to pdf looks the same like in (ctrl + p method --> save as pdf). I was trying use xhtml2pdf but unfortunately isn't full css support and static. -
docker-compose run: django and postgres "strange" behavior
When I run the following command: docker-compose run django python manage.py startapp hello OR docker-compose run django python manage.py createsuperuser Instead of starting a new container, it opens a Postgres shell. However, when I'm using exec, like so: docker-compose exec django python manage.py createsuperuser Then it works as expected. Here is my docker-compose.yml file: version: '3.7' services: postgres: image: 'postgres:9.6.9-alpine' volumes: - postgres_data:/var/lib/postgresql/data env_file: - ./.env.dev django: image: django_dev build: context: . dockerfile: ./app/docker/django/Dockerfile volumes: - ./app/:/usr/src/app/ command: /usr/src/app/docker/django/start_dev ports: - 8000:8000 env_file: - ./.env.dev depends_on: - postgres node: image: node_dev build: context: . dockerfile: ./app/docker/node/Dockerfile depends_on: - django volumes: - ./app/:/usr/src/app/ - /usr/src/app/node_modules command: npm run dev ports: - '3000:3000' - "3001:3001" volumes: postgres_data: Dockerfile: FROM python:3.9.5-slim-buster WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt update \ && apt install -y curl \ && curl -sL https://deb.nodesource.com/setup_lts.x | bash - \ && apt-get -y install libpq-dev gcc \ && pip install psycopg2 \ && pip install psycopg2-binary RUN pip install --upgrade pip \ && pip install pipenv COPY ./app/Pipfile /usr/src/app/Pipfile RUN pipenv install --skip-lock --system --dev RUN apt-get update && apt-get install -y libglu1 COPY ./app/docker/django/entrypoint /usr/src/app/docker/django/entrypoint COPY ./app/docker/django/start_dev /usr/src/app/docker/django/start_dev RUN sed -i 's/\r$//g' /usr/src/app/docker/django/start_dev RUN chmod …