Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filter foreign key could not get in drop down
filter.py class StudentFilter(django_filters.FilterSet): # SchoolName = django_filters.ModelMultipleChoiceFilter(queryset=MasterSchool.objects.all()) class Meta: model = Student fields = ['StudentId', 'School', 'Division'] Here I have tried School__SchoolName, but it does not show the dropdown list. model.py class MasterSchool(models.Model): SchoolName=models.CharField(max_length=100, null=False, blank=False, unique=True) Active = models.BooleanField(default=True) class Meta: db_table='master_schools' class MasterDivision(models.Model): DivisionName=models.CharField(max_length=100, null=False, blank=False, unique=True) Active = models.BooleanField(default=True) class Meta: db_table='master_divisions' class Student(models.Model): StudentId=models.CharField(max_length=20, null=True, blank=True) StudentName=models.CharField(max_length=100, null=False, blank=False) Phone = models.CharField(verbose_name="Phone number", null=True, blank=True, max_length=10, validators=[validate_digit_length], default='1234567890') School = models.ForeignKey(MasterSchool, on_delete=models.CASCADE, null=True, blank=True, db_column='SchoolId') Division = models.ForeignKey(MasterDivision, on_delete=models.CASCADE, null=True, blank=True, db_column='DivisionId') StudentPhoto= models.ImageField( null=True, blank=True, default="default.png", upload_to='studentphoto/resgistred_photos/') PhotoMatrix=models.CharField(max_length=100, null=True, blank=True) class Meta: db_table='students' ordering = ['id'] view.py def StudentDetail(request): if(request.session.has_key('uid')): stud = Student.objects.all() schools = MasterSchool.objects.all() divisions = MasterDivision.objects.all() tableFilter = StudentFilter(request.GET, queryset=stud) students = tableFilter.qs page = request.GET.get('page', 1) paginator = Paginator(students, settings.PAGE_LIMIT) try: student_list = paginator.page(page) except PageNotAnInteger: student_list = paginator.page(1) except EmptyPage: student_list = paginator.page(paginator.num_pages) context = { 'student_list':student_list , 'students': students, 'tableFilter':tableFilter, 'root_url':settings.ROOT_URL, 'schools': schools, 'divisions': divisions } return render(request, 'web_api/student_details.html', context) html <form method="get" class="forms-sample" autocomplete="off" > {{tableFilter.form}} <button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button> </form> <div class="table-sorter-wrapper col-lg-12 table-responsive"> <table id="sortable-table-2" class="table table-striped"> <thead> <tr> <th>ID</th> <th>Student Name</th> <th>School Name</th> <th>Division</th> <th>Image</th> <th>Option</th> </tr> </thead> <tbody> {% for … -
i dont know why it has error with catalog/url.py?
https://github.com/Angelheartha/ruci this is my github the erroe is the below raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'catalog.urls' from 'C:\Users\user\PycharmProjects\pythonProject28\locallibrary\cat alog\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. i dont know the reazon because i already wrote in catalog/url.py path, and i wrote views.py what is the issue? -
Registration of an anonymous DRF user
I'm writing an API questionnaire on the Django Rest Framework, when passing the survey, I collect the id of an authorized user. But what about an anonymous user who has passed the survey, how do I get his unique id? -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile?
I upload the excel file and insert the file in VBA_Parser of oletools but I am getting an error expected str, bytes or os.PathLike object, not InMemoryUploadedFile def upload(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] result = [] vba_parser = VBA_Parser(file) # this is where error occur vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros(): result.append("Caution, macros has been found in your excel file.") vba_parser = VBA_Parser(file) # this is where error occur. I couldn't figure out how to solve the issue. -
How To get text editor in django frontend
In my front end of django templates i want to use a text field editor like How to achive something like this -
(Django) How to keep input values after form submit
I have the following view (truncated): def scheduler( request, year=None, month=None, event_id=None, delete_id=None, ): # Handle the event form if request.POST: event_form = EventForm(request.POST, instance=event) if event_form.is_valid(): event = event_form.save() dfkl_number = event_form.cleaned_data['dfkl_id'] Event.objects.filter( id=event.id, ).update(dfkl_number=dfkl_number) start_time = event_form.cleaned_data['start_time'] start_time = user_tz.localize(start_time.replace(tzinfo=None)) end_time = event_form.cleaned_data['end_time'] end_time = user_tz.localize(end_time.replace(tzinfo=None)) # if the end time is before the start time, try setting it to the same day if end_time < start_time: end_time = end_time.replace( year=start_time.year, month=start_time.month, day=start_time.day) # if the hour is also before, just use the start time if end_time < start_time: end_time = start_time Event.objects.filter( id=event.id, ).update(start_time=start_time) Event.objects.filter( id=event.id, ).update(end_time=end_time) return HttpResponseRedirect('/events') What I want is that whenever I submit a form (if request.POST) whether the form is valid or not, the values of the inputs do not disappear. scheduler.html: {% if event_id %} <form action="{% url 'cal:event' event_id %}" method="post" class="form needs-validation to-do-form"> {% else %} <form action="{% url 'cal:events' %}" method="post" class="form needs-validation to-do-form"> {% endif %} {% csrf_token %} {% bootstrap_form_errors event_form type='non_fields' %} {% bootstrap_field event_form.title layout='horizontal' size='small' %} {% bootstrap_field event_form.description layout='horizontal' size='small' %} {% bootstrap_field event_form.event_type layout='horizontal' size='small' %} {% bootstrap_field event_form.dfkl_id layout='horizontal' size='small'%} <!-- start time --> <div class="form-group {% if event_form.start_time.errors %}is-invalid{% … -
Django ModelForm update function returning error
I currently have a settings model for my Django app which saves a set of settings for the rest of the program to read from. I have tried to create a way to update these settings on the app, as per the below code. When the update button is clicked, however, the app returns the 'error':'Bad info' variable instead of updating the database. Does anyone know what could be causing it because I cannot seem to find any errors in the code? Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: try: form = SettingUpdateForm(request.POST, instance=setting) form.save() return redirect('settingsHome') except ValueError: return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form, 'error':'Bad info'}) Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) #Income Statement Year To Date Income_Statement_Year_to_date=models.BooleanField(default = False) isytd_Only_use_main_accounts=models.BooleanField(default = False) isytd_Sort_by_account_name=models.BooleanField(default = True) isytd_Print_null_values=models.BooleanField(default = False) … -
how to process the return value of status=status.HTTP_400_BAD_REQUEST
In Django view, I have a view like this: @api_view(['POST']) def change_log(request): ...... return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then call it: def post_to_change_log(): try: requests.post(INNO_API_URL + '/change_log_add/', json=log_data) except: In main, I need to check the return value of post_to_change_log(true of false) main(): if(post_to_change_log): return 200 else: return error+return value from post_to_change_log The question is, how could I process the return value in the 3 functions, then when error happened, I can return the serializer.errors, status=status.HTTP_400_BAD_REQUEST) in main? Thank you. -
Can't login to django admin page Server Error (500)
Good work everyone, I'm trying to build a website using django, nginx and gunicorn. Everything works fine on the django development server and I can also open the front page of my site using nginx. Since the project is the project of the company I work for, I had to censor some parts due to company policy. Thank you for your understanding However, repeatedly sudo systemctl restart gunicorn When I try to login to the admin page or use my own custom login page, I get a Server error (500) despite running the command. Can someone tell me what I'm doing wrong? settings.py: enter image description here nginx: enter image description here -
How to cache ClassBasedAPIViews in Django Rest Framework?
I am serving list of products in DRF and I tried to use cache in ClassBasedApiViews, urls.py path('',ProductListAPIView.as_view(), name='products') views.py: class ProductListAPIView(ListAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer_class = ProductSerializer serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' depth = 1 There is no function like def get() ... So I can not use conventional decorator before the function to cache. What I have tried is path('', cache_page(300)(ProductListAPIView.as_view()), name='products') this works. In case of multiple decorators path('', vary_on_headers('Authorization')(cache_page(300)(ProductListAPIView.as_view())), name='products') works as well. Is there a better way to use both decorators cache_page and vary_on_headers for ClassBasedAPIView? -
How can I bulk create Django Model objects using xml iterparse?
I want to insert thousands of rows into postgres db. I plan to do this using bulk_create() in django. Since I am working in a low memory ssh terminal, I want to use iterparse() in xml python library My XML file looks like this <playerslist> <player> <fideid>25121731</fideid> <name>A C J John</name> <country>IND</country> <sex>M</sex> <title></title> <w_title></w_title> <o_title></o_title> <foa_title></foa_title> <rating>1063</rating> <games>0</games> <k>40</k> <birthday>1987</birthday> <flag>i</flag> </player> <player> . . . </player> . . . </playerlist> Here are my models class Player(models.Model): fide_id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=50, null=False) sex = models.CharField(max_length=2, null=False) birthday = models.IntegerField(null=True) class Ratings(models.Model): fide_id = models.ForeignKey(Player, on_delete=models.CASCADE) month = models.CharField(null=False, max_length=15) federation = models.CharField(max_length=15, null=False) title = models.CharField(max_length=4, default=None, null=True) w_title = models.CharField(max_length=4, default=None, null=True) o_title = models.CharField(max_length=4, default=None, null=True) foa_title = models.CharField(max_length=4, default=None, null=True) rating = models.IntegerField(null=True) games = models.IntegerField(null=True) k = models.IntegerField(null=True) flag = models.CharField(max_length=3, null=True) I want to insert the respective fields into their tables. I could do this on a normal computer but i am not sure how to parse this incrementally. Thank you. Edit : I think iterparse approach would require more transactions than bulk_create. I don't think we can use bulk_create() here. -
How to upload file and redirect to another page in django?
I showed up upload.html page after I log in. When I submit the upload file button I want to show upload or some other pages. it doesn't redirect to upload.html or any other pages. It redirects to the login page again. May I know what's the bug in my code? Here is the View.py login is strictly required. As soon as the user login I showed up upload.html page. I have two groups: (New user) and administration. @login_required(login_url='/registration/login/') def login_request(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return render(request, "upload.html") form = AuthenticationForm() return render(request = request, template_name = "registration/login.html", context={"form":form}) @unauthenticated_user def login(request): """ Creates login view Returns: rendered login page """ return render(request, 'registration/login.html') @allowed_users(allowed_roles=["administrator", "New user"]) def upload(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] workbook = load_workbook(filename=file, data_only=True) xls = workbook[workbook.sheetnames[0]] result = [] # macros check vba_parser = VBA_Parser(file) vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros(): result.append("Caution, macros has been found in your excel file.") count = 0 # check .exe, url for i in range(1, xls.max_row+1): … -
how to get id of the input text field in Django Views?
Currently in my form i have this <input type="text" name="textAnswer" maxlength="50" id="ed57a954-7afd-47ac-b6d4-979198455aa5" class="textinput textInput form-control"> I want the id of this input in views when form is submitted. I know how to get the value typed by user in textinput in views but dont know how to extract id of that input as well Currently i'm extracting Value with this code userTypedValue = request.POST.get('textAnswer') -
Date format for Django Admin
I have a Model with DateField. In Django admin when I try to enter the date in Django Admin in format "%d-%m-%Y" it throws error as Enter a valid date.. Since the default pattern is "%Y-%m-%d" I tried the following but couldnt find a satisfied solution over the docs: Change the format type with strftime in model. Add DATE_INPUT_FORMATS in settings. Change language code to "en-IN" Is there any way to save the date in "%d-%m-%Y" format. -
Browser is making an HTTP call after reloading an angular webpage
Hello I’m working on an angular project and I’ve few APIs to call.. I’ve set up the API Url as const SERVER_URL = https://api.example.com And it’s working perfectly fine unless and until I reload the page after some successful API Calls and then make an API call again.. I’m getting CORS error that: [blocked] The page at https://staging.example.com was not allowed to display insecure content from http://api.example.com Do anyone know where I’m doing things wrong? Because I’ve few other projects and I use same coding practices in them as well but they are working perfectly fine.. PS: Backend is in Django -
how to return doc file as response in django views?
i have my .doc file created in a django views. Now i want to return that doc file as response. how can i do this? this is my view def post(self, request, *args, **kwargs): with tempfile.TemporaryDirectory() as tem_dir: doc.save(tem_dir + '/' + template_name) f = open(tem_dir + '/' + template_name, 'r') response = HttpResponse(f, content_type='application/msword') response['Content-Disposition'] = 'attachment; filename='+template_name return response I am saving my doc file in a temporary directory. Also can the response will be visible using postman request? -
vs code autocompletes not working properly in Django
vs code doesn't suggest request in views.py , I've test pylance,jedi.. all off language server but didn't work. How can I get a better autocompleting in vs code? -
Django submission button doesn't link with view function
I am trying to create a small subscription input form on top of my page that allows users to enter their email, click "submit" and then it will call the subscribe function on the back-end. I am putting the form code in one of my template html file: <div class="container"> <div class="wrapper d-flex align-items-stretch" style="margin-bottom: 100px;"> {% include 'Reddit_app/sub_list.html' %} <div id="content" class="mr-4"> <div class=" lt-area"> <div class="tr-inner"> <form action="{% url 'subscribe' station.slug %}" method="POST" class="subscribe-form"> <div class="form-group d-flex mb-1"> <div class="icon"><span class="icon-paper-plane"></span></div> <input type="email" name="email" class="form-control" placeholder="Subscribe us"> </div> <button type="button" class="btn btn-primary t-btn">Submit</button> </form> </div> </div> {% block content %} {% endblock %} </div> </div> </div> Here is my urls.py urlpatterns = [ ... path('<slug:slug>/subscribe/', views.subscribe, name='subscribe'), ] and here is my subscibe function, but right now when I click submit, this function is currently not even called def subscribe(request, slug): station=get_object_or_404(Station, slug=slug) post_data = request.POST.copy() email = post_data.get("email", None) try: validate_email(email) except ValidationError as e: print("bad email, details:", e) return redirect('post_list', slug=station.slug) -
Django: Could not load model - NOT NULL constraint failed
how are you all? We are not able to insert the fixures data into our SQLite3 database. We are using UUid as our model id. Using the comand python.exe .\manage.py loaddata start.json Model class Estadual(models.Model): # Fields id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) estado = models.CharField(max_length=50) sigla = models.CharField(max_length=2, unique=True) valor = models.PositiveSmallIntegerField() created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationships user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: pass start.json [ { "model": "app.estadual", "pk": "59472bb0-7f6e-4026-a900-727b7cdd647f", "fields": { "estado": "AC", "sigla": "AC", "valor": 12, "user": ["4a695e40-6b3a-49fa-8beb-eed853ce17b0"] } },{ "model": "app.estadual", "pk": "5b321ca7-e8be-4580-8d36-080c663d5397", "fields": { "estado": "AL", "sigla": "AL", "valor": 12, "user": ["4a695e40-6b3a-49fa-8beb-eed853ce17b0"] } } ] Error Problem installing fixture 'C:...fixtures\start.json': Could not load app.Estadual(pk=59472bb0-7f6e-4026-a900-727b7cdd647f): NOT NULL constraint failed: app_estadual.created -
Change a primary key column to a foreign key with django
So I have models similar to the following: class Address(BaseModel): ... user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) This seemed appropriate at the time because an address could 'belong' to a user but recently I need to reuse this table for a 'applicants' whom are like users so would have access to many of their related tables; hence I've started changing models to the following: class Address(BaseModel): ... user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) # unique=True where necessary applicants = models.ForeignKey(Applicants, on_delete=models.CASCADE, blank=True, null=True) The problem seems to be mainly that the user field was a primary key for address and so while I made some progress getting past the initial migration errors of the new id field that django creates using this answer, I'm now getting the following migration error: psycopg2.errors.InvalidTableDefinition: column "user_id" is in a primary key django.db.utils.ProgrammingError: column "user_id" is in a primary key Looks like it's complaining about the former primary key that I'm now trying to turn into a foreign key. Additionally there's a good amount of data already present. I'm not sure how to get past this error. -
I am Unable to Send My email in django backend app
When i can send post request for contact view so try block can't run and except block should be run. Here i cant unable to send mail. Here error in send_mail function. So please Help me. view.py from rest_framework import permissions from rest_framework.views import APIView from .models import Contact from django.core.mail import send_mail,EmailMessage from rest_framework.response import Response class ContactCreateView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data print(data) try: send_mail( data['subject'], 'Name: '+ data['name'] + '\nEmail: '+data['email']+'\nMessage:'+ data['message'], 'kalpprajapati2002@gmail.com', ['kalp2002prajapati@gmail.com'], fail_silently=False ) contact = Contact(name=data['name'], email=data['email'], subject=data['subject'], message=data['message']) contact.save() return Response({'success': 'Message sent successfully'}) except: return Response({'error': 'Message failed to send'}) urls.py from django.urls import path from .views import ContactCreateView urlpatterns = [ path('',ContactCreateView.as_view()) ] models.py from django.db import models from datetime import datetime class Contact(models.Model): name=models.CharField(max_length=200) email=models.CharField(max_length=100) subject=models.CharField(max_length=100) message=models.TextField(blank=True) contact_date=models.DateTimeField(default=datetime.now,blank=True) def __str__(self): return self.email -
datetime.datetime object is not callable for last_modified decorator
from datetime import datetime @last_modified(datetime(year=2021, month=9, day=16)) def about(request): return render(request, 'about.html') I get 'datetime.datetime' object is not callable Exception Location: path\lib\site-packages\django\views\decorators\http.py in get_last_modified, line 83 Django 2.2 -
Django templating . Displaying things if only available
class OrderItem(models.Model): product = models.ForeignKey('Product' , on_delete=models.SET_NULL ,null=True) complete = models.BooleanField(default=False) order = models.ForeignKey('Order',on_delete= models.SET_NULL ,null= True) class Return(models.Model): customer = models.ForeignKey('Customer' , on_delete=models.SET_NULL , null= True , blank = True) order= models.ForeignKey('Order' ,on_delete=models.SET_NULL ,null=True) product = models.ForeignKey('Product' , on_delete=models.SET_NULL ,null=True) complete = models.BooleanField(default=False ) I have these above two models . In views.py i have sent : returns=Return.objects.filter(customer=customer,complete=False) In template , there is {% if order.return_set.exists %} {% for rett in order.return_set.all %} {% if item.product.id == rett.product.id %} Return in process! You will get call from our team shortly. {% else %} <form method="POST" action="{% url 'return_item_no' order.id item.product.id %}"> {% csrf_token %} <input type="text" placeholder="Reason" name="reason" style="border : 1px solid black"> <input type="number" placeholder="Quantity" name="quantity" style="border : 1px solid black"> <input type="submit" name="return_orderitem" value="Return Item" style="color: red; height: 20px;" > </form> {% endif %} {% endfor %} {% else %} <form method="POST" action="{% url 'return_item_no' order.id item.product.id %}"> {% csrf_token %} <input type="text" placeholder="Reason" name="reason" style="border : 1px solid black"> <input type="number" placeholder="Quantity" name="quantity" style="border : 1px solid black"> <input type="submit" name="return_orderitem" value="Return Item" style="color: red; height: 20px;" > </form> {% endif %} I want to display , a form if the specific item is not in … -
AttributeError when attempting to get a value for field - Django
I have a very weird issue in my Django project. Here is my model: class Connection(models.Model): user = models.ForeignKey(User, related_name='exchange_connections', on_delete=models.CASCADE) exchange = models.ForeignKey(Exchange, related_name='connection_exchange', on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) last_updated = models.DateTimeField(auto_now=True, blank=True) Here is my serialiser: class ConnectionSer(serializers.ModelSerializer): class Meta: model = Connection fields = '__all__' And my view: class UserPortfolioViewSet(viewsets.ViewSet): serializer_class = ConnectionSer queryset = Connection.objects.all() permission_classes = (permissions.IsAuthenticated, core_permissions.IsMineOnly) def list(self, request): try: user = request.user except: return HttpResponseBadRequest('No user') connections = user.exchange_connections.all() return Response(self.serializer_class(connections).data, status=status.HTTP_200_OK) I get this error from the view (GET): Got AttributeError when attempting to get a value for field user on serializer ConnectionSer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'user'. Which makes no sense to me because I don't create any exchange property in my serializer class..? And I also don't understand the last line: 'QuerySet' object has no attribute 'user'. -
Collectstatic on same folder?
am planning to move my project to production ! so hosted on pythonanywhere. Now am just confused about how to deal with collectstatic This is my folders: project -app1 -app2 -static // this contains all the static files for both app1 and app2 -utils So, as i have 100% of all static files inside static, where to perform collectstatic? Can i perform collectstatic inside "static" folder itself ? or do i need to point out seprate folder like "staticfiles" inside project ? My overall question is can we do collectstatic without pointing it to seprate folder ?