Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another
Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another. So I have an account model and a blog post model, with the author as the foreign key. I am unsure of how i can do the querying of the account. Can anyone advise how this is normally done? Because I tried to do user_id=request.user.id but this would take me to my own account view. Thanks! html <a class="dropdown-item" href="{% url 'account:view' %}">{{blog_post.author}}</a> views.py def detail_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['blog_post'] = blog_post return render(request, 'HomeFeed/detail_blog.html', context) urls.py for accounts: path('<user_id>/', account_view, name="view"), models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Retrieve the same values whose data is there or exists and not the rest.In django
I want to have a data that does not have any empty value in database or in row. I wrote like this in my code. faq = FAQ.objects.values('question','answer','field_id') this the output in my terminal {'question': None, 'answer': None, 'field_id': None} {'question': 'Test question', 'answer': '<p>Testsaddsf description</p>\r\n', 'field_id': 'TestTest'} i don't want None value data. -
upload image and already saved image, this two parts want to display on two different html template
i use modelformset_factory to upload image, but i want to separate the already saved image(A in the below link) and upload image(B in the below link) on two different html template. How do i resolve this problem? thanks for your help!! enter image description here here is my code below: views.py def post_image(request): PictureFormSet = modelformset_factory(Picture, form=PictureForm, extra=3) if request.method == 'POST': formset = PictureFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return HttpResponse("Upload done!!") else: return HttpResponse("Upload Failed!!") else: formset = PictureFormSet() return render(request, "Image.html", {"formset": formset}) models.py class Picture(models.Model): article = models.ForeignKey("Article", related_name="article_photo", on_delete=models.CASCADE) photo = models.ImageField(upload_to="photo", height_field=None, width_field=None, max_length=100) first_photo = models.BooleanField(default=False) urls.py path('post/image/', post_image), html <html lang="zh-Hant-TW"> <head> <meta charset="UTF-8"> <title>post_image</title> </head> <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <input type="submit" value="Sumbit"> </form> -
how to get cart and order for a user who sell the product using django
I am building an ecommerce web-application using django where people come and sell their products. Recently i have done the coding where user come ,login and sell their products and another user come and buy these thing .All the order are coming to the admin panel. but i want the user that sell the products get these specific orders . but how the user who sell ,can get their orders and cart . I do not have any logic kindly anyone please guide me. Thnak you -
AJAX POST request error - `Uncaught TypeError: Illegal invocation`
If I try to do this, I get this error: Uncaught TypeError: Illegal invocation $(document).on('input', '#search-inp', (e) => { $.ajax({ type: 'POST', url: '/search/', dataType: 'json', data: { input: $('#search-inp').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'), }, success: function(data) { console.log(data); } }); }); And if I try to do this, I get this error: 403: Forbidden $(document).on('input', '#search-inp', (e) => { $.ajax({ type: 'POST', url: '/search/', dataType: 'json', processData: false, contentType: false, data: { input: $('#search-inp').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'), }, success: function(data) { console.log(data); } }); }); # This is my views.py def search(request): return JsonResponse(data={ 'test': 'test' }) What could be the problem? Your help is greatly appreciated. Thank you -
Django path regex construction
Am trying to construct Django URL path by a using a regex but the path can't be resolved to my view, the ending of the path should be like 127.0.0.1:8080/watch?v=bXHfrdi_fsU like those urls you see on youtube videos where the bXHfrdi_fsU is some random characters which will be passed to my view as id string using <str:id>. Here is what I have tried but was unsuccessful #urls.py import path, re_path from myapp import views urlpatterns = [ re_path = ('/(watch)\?v\=<str:id>', views.my_view, name='my_view'), ] and here is my views:- def my_view(request, id): string = str(id) return HttpResponse('It works,here is your string'+string) -
Seeding the random generator for tests
I made it work using factory-boy's get_random_state/set_random_state, although it wasn't easy. And the biggest downside is that the values are big. So the thing that comes to mind is to write it to a file. But then if I accidentally run the tests not telling it to seed from the file, the value is lost. Now that I think about it, I can display the value too (think tee). But still I'd like to reduce it to 4-5 digits. My idea is as follows. Normally when you run tests it somewhere says, "seed: 4215." Then to reproduce the same result I've got to do SEED=4215 ./manage.py test or something. I did some experiments with factory-boy, but then I realized that I can't achieve this even with the random module itself. I tried different ideas. All of them failed so far. The simplest is this: import random import os if os.getenv('A'): random.seed(os.getenv('A')) else: seed = random.randint(0, 1000) random.seed(seed) print('seed: {}'.format(seed)) print(random.random()) print(random.random()) /app $ A= python a.py seed: 62 0.9279915658776743 0.17302689004804395 /app $ A=62 python a.py 0.461603098412836 0.7402019819205794 Why do the results differ? And how to make them equal? -
How to change the user display name to their first name in Django
I am using the Django inbuilt user authentication system, from from django.contrib.auth.models import User. And I have realised that in the admin page it always displays the username of the user. Is it possible to change the def __str__ (self): method of that function to display a customized one, something like this. def str (self): return f"{self.first_name}" -
No Post matches the given query in django Error
So i have a project called star social project this project is similar to a socail media that you can post and create group but this project you can only post when you are in a group. So i get an error message that is not familiar to me which is on the title, i tried to search on google and get some result but when i implement it to my project it does not work. So why im getting this error is because i'm trying to create a comment section and when i click the add comment that's when i get the error message. So i'm here to ask someone to help me because i'm not really familiar on this error and i'm just learning django for about 2 months now. models.py ########################## ## POSTS MODELS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django.db import models from groups.models import Group from misaka import html from django.urls import reverse from django.utils import timezone User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = … -
Django: Won't Delete Post
I am trying to get my posts to delete on the click of a button that pops up on the screen instead of sending the user to a different delete page. The form works but it won't actually delete the posts. What am i doing wrong here Stack Overflow says im using too much code so ignore the next few lines. too much code too much code too much code too much code Some relevant info: templates: {% block head %} <head> <link rel="stylesheet" type="text/css" href="{% static 'css/my_posts.css' %}"> <title>Create - My Posts</title> <script> function togglePopup(){document.getElementById("popup-1").classList.toggle("active")} </script> </head> {% endblock head %} {% block content %} <div class="content_section"> <div class="btn_container"> <a class="new_post" href="{% url 'newpost' %}"><button class="new_post_btn">New Post</button></a> </div> <div class="content_section_two"> {% for product in products %} <div class="post_short_container"> <div class="title_container"> <a href="#" class="post_link"> <div><b>{{ product.title }}</b></div> </a> </div> <div class="right_btns"> <a href="{% url 'editpost' product.id %}" class="edit_link">Edit</a> <a href="#" class="stats_link">Stats</a> <div class="ad_btn_container"> <div class="ad_btn">Ad</div> </div> <div class="delete_btn_container"> <div class="delete_btn" onclick="togglePopup()">Delete</div> </div> </div> </div> <div class="delete_prompt_container" id="popup-1" action="{% url 'deletepost' product.pk %}"> <form method="POST"> {% csrf_token %} <p class="delete_prompt">Are you sure you want to delete this post?</p> <div class="cancel_delete_container"> <div class="cancel_button" onclick="togglePopup()">Cancel</div> <input value="Delete" type="submit" name="confirm" class="confirm_delete_button"> </div> </form> </div> … -
How to add expiry date in HUEY dynamic periodic task just like in celery tasks?
Is there a way to add expiry date to a Huey Dynamic periodic task ? Just like there is an option in celery task - "some_celery_task.apply_async(args=('foo',), expires=expiry_date)" to add expiry date while creating the task. I want to add the expiry date while creating the Huey Dynamic periodic task. I used "revoke" , it worked as it supposed to , but I want to stop the task completely after the expiry date not revoking it . When the Huey dynamic periodic task is revoked - message is displayed on the Huey terminal that the huey function is revoked (whenever crontab condition becomes true). (I am using Huey in django) (Extra) What I did to meet the need of this expiry date - I created the function which return Days - Months pairs for crontab : For eg. start date = 2021-1-20 , end date = 2021-6-14 then the function will return - Days_Month :[['20-31',1], ['*','2-5'], ['1-14','6']] Then I call the Huey Dynamic periodic task (three times in this case). (the Days_Month function will return Day-Months as per requirement - Daily, Weekly, Monthly or repeating after n days) Is there a better way to do this? Thank you for the help. -
Django Unable to pass a variable name in the next template
Hi I am facing a problem in my project . In the Patient list, if a Click the Notes row present in the Add notes column. The new template load where it will list the recent notes for the patients... and also it allows me add patient notes by selecting the patient ( i am passing the objects of patients through forms ) My problem .. How to add notes to the specified patient only. ( i.e. by not passing through forms) and also filtering to display the specfic Patient notes only. Code Model: class Notes(models.Model): doctorId = models.PositiveIntegerField(null=True) patientName = models.CharField(max_length=40, null=True) report = models.TextField(max_length=500) NoteDate = models.DateTimeField(default=timezone.now) #def __str__(self): # return self.patientName+" "+self.report @property def get_id(self): return self.id View @login_required(login_url='doctorlogin') @user_passes_test(is_doctor) def doctor_add_notes_view(request): appointmentForm=forms.PatientNotesForm() notes = models.Notes.objects.all().order_by('-NoteDate') mydict={'appointmentForm':appointmentForm,'notes':notes} if request.method=='POST': appointmentForm=forms.PatientNotesForm(request.POST) if appointmentForm.is_valid(): appointment=appointmentForm.save(commit=False) appointment.doctorId =request.user.id #request.POST.get('doctorId') doctors = models.Appointment.objects.all().filter(AppointmentStatus=True, status=True) appointment.patientName = models.User.objects.get(id=request.POST.get('patientId')).first_name now = datetime.now() print("Current date and time : ") print(now.strftime("%Y-%m-%d %H:%M:%S")) appointment.NoteDate = now print('doctors', doctors) appointment.save() return HttpResponseRedirect('doctor-view-patient') else: print(appointmentForm.errors) return render(request, 'hospital/doctor_view_patient.html',{'alert_flag': True}) return render(request,'hospital/doctor_add_notes.html',context=mydict) def doctor_view_patient_view(request): appointments1 = models.Appointment.objects.all().filter(AppointmentStatus=False, status=True,doctorId=request.user.id) print('appointments are ', appointments1) patientid = [] for a in appointments1: patientid.append(a.patientId) print('patientid', patientid) patients = models.Patient.objects.all().filter(PatientStatus=True, status=True, user_id__in=patientid) print('patients', patients) … -
Handing image file not found error in Django
I am trying to handle the image not found an error in Django by defining a custom view unhandle_urls. The way I am trying to do this is the following. Define a URL pattern inside urls.py by matching the image URL's pattern to my custom view unhandle_urls Here are my url patterns inside urls.py urlpatterns = [ .... path(r'images/*', unhandle_urls, name="redirecting the user"), ... ] However, I am still getting the same 404 error whenever any image is requested. Here is the error msg: GET https:my-website-base-url/images/searchbox/desktop_searchbox_sprites318_hr.png 404 (Not Found) I am not sure what the problem is. My guess is that the url pattern r'images/*' is not matching to https:my-website-base-url/images/searchbox/desktop_searchbox_sprites318_hr.png, but I try to look at this https://docs.djangoproject.com/en/3.1/topics/http/urls/ but could not find what's wrong with my approach. Any type of help will be appreciated. Thanks in advance. -
How to Filter on Related Model Count in Graphene Django
I have 2 models: import uuid from django.db import models class Country(models.Model): name = models.CharField(max_length=255, unique=True) def city_count(self): return self.city_set.count() class City(models.Model): country = models.ForeignKey('country.Country', on_delete=models.CASCADE) name = models.CharField(max_length=255) And 2 Schemas: import graphene from graphene_django.filter import DjangoFilterConnectionField from core.utils import ExtendedDjangoObjectType from .models import Country as CountryModel, City as CityModel class Country(ExtendedDjangoObjectType): class Meta: model = CountryModel filter_fields = { 'name': ['exact'], # 'city_count': ['exact'] => this does not work! } interfaces = (graphene.relay.Node, ) city_count = graphene.Int() def resolve_city_count(self, info): return self.city_count() class City(ExtendedDjangoObjectType): class Meta: model = CityModel filter_fields = ['name'] interfaces = (graphene.relay.Node, ) class Query(graphene.ObjectType): country = graphene.relay.Node.Field(Country) countries = DjangoFilterConnectionField(Country) city = graphene.relay.Node.Field(City) cities = DjangoFilterConnectionField(City) I can query the city_count on countries, but I can't seem to filter on it (exact, or gte greater than / lte less than) i.e. this works: { countries(first: 10) { edges { node { name cityCount } } } } but this doesn't: { countries(cityCount: 5) { edges { node { name cityCount } } } } and triggers the following error: TypeError at /api/graphql/ 'Meta.fields' must not contain non-model field names: city_count Any idea how I can filter/order on non-model fields? -
How to execute a function relative the request method with django rest framework?
I'm trying to just show a message in terminal if a post requisition, for exemple, be executed. Here I've made these function "get" to be executed but it also doesn't work. :/ if request.method == 'POST': print("Requistion made") views.py: from rest_framework import viewsets from piecesapp.api import serializers from piecesapp import models from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt class PiecesViewSet(viewsets.ModelViewSet): serializer_class = serializers.PiecesSerializer queryset = models.Pieces.objects.all() def get(self, request, format=None): print("Oi") return Response(serializer_class.data) class BoardViewSet(viewsets.ModelViewSet): serializer_class = serializers.BoardSerializer queryset = models.Board.objects.all() PS: I will remove this libs, it's just because i've tried some tutorials e it doesn't work. urls.py: from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'pieces', views.PiecesViewSet) router.register(r'board', views.BoardViewSet) urlpatterns = router.urls models.py: from django.db import models import uuid # Create your models here. COLOR_CHOICES = ( ('white','WHITE'), ('black', 'BLACK'), ) PICES_NAMES = ( ('king','KING'), ('queen','QUEEN'), ('rook','ROOK'), ('bishop','BISHOP'), ('knight','KNIGHT'), ('pawn','PAWN'), ) WHITE_KING_POSITION = ['e1'] BLACK_KING_POSITION = ['e8'] WHITE_QUEEN_POSITION = ['d1'] BLACK_QUEEN_POSITION = ['d8'] WHITE_ROOK_POSITION = ['a1','h1'] BLACK_ROOK_POSITION = ['a8','h8'] WHITE_BISHOP_POSITION = ['c1','f1'] BLACK_BISHOP_POSITION = ['c8','f8'] WHITE_KNIGHT_POSITION = ['b1', … -
Django ckeditor something is wrong
Hello guys i want to add ckeditor add my admin page but i've a error first i installed ckeditor and than i did those: settings.py INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #... SITE_ID = 1 #################################### ## CKEDITOR CONFIGURATION ## #################################### CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'media/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } ################################### urls.py urlpatterns = [ ... path('ckeditor/', include('ckeditor_uploader.urls')), ] models.py (django can't find ckeditor i think error is here) from ckeditor_uploader.fields import RichTextField, RichTextUploadingField class ModelClass: content = RichTextUploadingField() and also i did collectstatic thing but here is my error code ImportError: cannot import name 'RichTextField' from 'ckeditor_uploader.fields' (C:\Users\User\Desktop\Project\venv\lib\site-packages\ckeditor_uploader\fields.py) -
Django Rest Framework - Return S3 Object to client for user to download
I have an app where users can upload audio files (in the WAV format) and then they see some info about them on the frontend. I want a user to be able to click a file and then have it downloaded onto their computer, so they can listen to it and save it. When users initially upload a file, the file gets stored on Amazon S3, and then the S3 URL gets saved to the database. The backend of the application is in Django / Django Rest Framework and the Frontend is in React. With the code I currently have, nothing happens. I am not seeing any errors and nothing gets downloaded. I know that I can use a tag to download the file, but the problem is that the filename uses the key from S3. I want to be able to control the naming. That is why I am doing this server side. Django code: @api_view(['GET']) def download_audio_file(request, pk): audio = Audio.objects.get(pk=pk) s3_client = boto3.client( 's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION ) s3_response_object = s3_client.get_object(Bucket='bucket_name', Key=s3_key+'.wav') object_content = s3_response_object['Body'].read() response = HttpResponse(object_content, content_type='audio/wav') response['Content-Disposition'] = 'attachment; filename="audio.wav' return response React code: const handleDownloadAudio = (audio) => { fetch(API_URL+"api/audio/"+audio.id+"/download", { method: 'GET', … -
How can I render a Django render() response in an ajax function?
In my view, I return html if a form is valid: if form_valid(): return render(request, 'home.html', context=context) else: return HttpResponse(status=204) I'm submitting multiple forms via ajax and want to render the response, if the status code is not 204: $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function (response, status, jqXHR) { if (jqXHR.status !== 204) { document.write(response); // this works, but I lose some functionality. Some buttons stop working. // How can I render the response correctly? } } }); -
Django - Function should show all entries added to a list, but only one entry is appearing. HTML issue?
I am creating a way for a user to add a post to a list on a website. The page should show all the different items on their list, when they go to their watchlist page. Currently the page is only showing one item, not all of the items added. I know the other items are successfully added because when I view the page as admin http://127.0.0.1:8000/admin/ all the items are there. So I think my error is in the html file of the watchlist. Any help is appreciated as I am new to Django. html file {% extends "auctions/layout.html" %} {% block body %} <div class="container"> <h2>Items on your watchlist:</h2> </div> <div class="container" id="listings"> {% for item in items %} {% for i in item %} <div class="card mb-3" style="max-width: 540px;" id="card-listings"> <div class="row no-gutters"> <div class="col-md-4"> <img src="{{ i.image.url }}" alt="..." class="card-img" style="max- height:350px"> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{i.title}}</h5> <p class="card-text">{{i.description}}</p> <p class="card-text">${{i.price}}</p> <a href="{% url 'listingpage' i.id %}"><button class="btn btn-outline- success">Bid Now!</button></a> <p class="card-text"><small class="text-muted">{{i.time}}</small></p> </div> </div> </div> </div> {% endfor %} {% empty %} <h3>No listings found in your watchlist...</h3> {% endfor %} </div> {% endblock %} This function is for viewing the page … -
Django Error: Reverse for 'editpost' with arguments '('',)' not found. 1 pattern(s) tried: ['create/editpost/(?P<pk>[^/]+)/$']
I get this error when trying to use the template that should link to the edit page. I have seen someone do this using UpdateView but it gives the same error when i try it templates: <a href="{% url 'editpost' post.id %}" class="edit_link">Edit</a> urls.py: urlpatterns = [ path('editpost/<int:pk>/', views.editPost, name='editpost'), ] views.py def editPost(request, pk): post = Post.objects.get(id=pk) form = NewPost(instance=post) if request.method == 'POST': form = NewPost(request.POST, request.FILES, instance=post) if form.is_valid(): form.save() return redirect('myposts') return render(request, 'create/new_post.html', {'form': form}) -
Django SQL AJAX Call Not Responding
I have the following javascript script attached to a Create modal, in which I am trying to create a new entry into my SQLite3 table. I've adjusted the submit button type to = button rather than submit but now the button will not even click (the modal does nothing and does not go away/reset). Any ideas what would be causing this? stakeholders.html ........ <!--New Modal--> <div class="modal fade" id="new" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">New Item</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="employee" placeholder="employee" required> </div> <div class="form-group"> <input class="form-control" type="text" name="description" placeholder="description" required> </div> <div class="form-group"> <input class="form-control" type="text" name="stakeholder_group" placeholder="stakeholder_group" required> </div> <div class="form-group"> <input class="form-control" type="text" name="stakeholder_quadrant" placeholder="stakeholder_quadrant" required> </div> <button class="btn btn-primary form-control" type="button">SUBMIT</button> </form> </div> </div> </div> </div> ........ $('form#addUser').on('click','[type=button]', function(e){ console.log("ing") e.preventDefault(); var employeeInput = $('input[name="employee"]').val().trim(); var descriptionInput = $('input[name="description"]').val().trim(); var stakeholder_groupInput = $('input[name="stakeholder_group"]').val().trim(); var stakeholder_quadrantInput = $('input[name="stakeholder_quadrant"]').val().trim(); if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) { // Create Ajax Call $.ajax({ url: '{% url 'polls:crud_ajax_create' %}', data : { 'employee': employeeInput, 'description': descriptionInput, 'stakeholder_group': stakeholder_groupInput, 'stakeholder_quadrant': stakeholder_quadrantInput }, dataType: 'json', success: function … -
postgress Not working for Celery in docker and throwing could not connect to server error
Celery is not able to connect to PostgreSQL in my docker service and getting this error could not connect to server: Cannot assign requested address celery_1 | Is the server running on host "localhost" (::1) and accepting celery_1 | TCP/IP connections on port 5432? while PostgreSQL working fine for database and I am able to perform actions its just in case of celery . I have now 2 cases in this celery service celery: build: context: ./ dockerfile: Dockerfile command: celery -A sampleproject worker -l info environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_HOST=${POSTGRES_HOST} - POSTGRES_PORT=${POSTGRES_PORT} volumes: - .:/usr/src/app/ depends_on: - database - app - redis when I pass all PostgreSQL variables in celery environment its working. while I delete them its not working . why its happening ? and how I can resolve this ? so that I can run celery with proper way -
Unable to filter with POST request value Django
If I set integer value `(product = 1) then it's working fine instead of id, when I give id then the response is empty. id = request.POST.get("product") attrs = ProductAttributes.objects.filter(product=id).values('product', 'size__name') return JsonResponse(list(attrs), safe=False) -
Need some suggestions for using ManyToManyField with Crispy forms
I have a simple app that I built up from much of the information online that uses manytomany around the 'books and authors' paradigm. My model has a custom Account model for authors, a book model, and a through table - GroupMember model. I would like for authors to be able to log in and add their books, but I would also like for if a book has two authors then the GroupMember will capture that and show co-authored books in the profile of both authors. Currently, I have all of the authors profile information displaying correctly in-browser using {{ p_form|crispy }}, and using an objects.filter() I can query only the books by author's first name. The difficulty I am having is putting the filtered book(s) into the b_form so that as soon as the author profile is loaded the book title and publish year appear in the crispy textboxes. Right now those text boxes are empty - the good thing is that if I add a title and year they are successfully added to the database. But I think I'll add a separate button for add books functionality later. I still need to figure out the best way to … -
Employee Manager relationship SQLITE DJANGO
I am honestly struggling trying to understand how i can start off an employee to manager relationship. I've read a few things about LEFT, OUTER and INNER joins. I am using SQLite3 and django framework background: i have a user table, this contains information about the user. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, editable=False) bio = models.TextField(default='', blank=True) location = models.CharField(max_length=30,default='', blank=True ) department = models.CharField(max_length=30, default='', blank=True) team = models.CharField(max_length=30, default='', blank=True) jobrole = models.CharField(max_length=20, choices=job_role) My end goal, is that I would like to be able to have multiple managers to multiple users. Should i just add "reports_to" to the profile class, and then create a separate table that relates to the user-id and has a manager-id? so on the profile page, you can see who the user's manager is, and the manager can log into his profile and see who their employees are (multiple list).