Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Uninstall Django from Window10?
I command I deleted Django using "pip uninstall django". But it did not install again. The error message is: C:\Django>python -m pip install -U pip Requirement already up-to-date: pip in c:\python\lib\site-packages (19.2.3) I don't know which command to use to completely remove and reinstall. -
Django /JQuery - Disabling certain dates on JQuery Date Picker
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
Genre for models in DJango
I am creating a site with Django, and I encounter a problem with the administration site. When I create a new model, I can assign a verbose_name for the singular and plural in the meta class, but I don't find any option that allows me to assign what gender that model is, that is, whether it is feminine (female) or masculine (male). For example, I have the city model, which in Spanish would be "Ciudad" and would be feminine. Then when on the admin site I add a new record, the legend "Se añadió con éxito el ciudad" appears, when the right thing would be "Se añadió con éxito la ciudad". I know this could be a translation issue, but I suppose something should indicate to the translations that the model should put "el" or "la" as the case may be. Can anybody help me? -
Getting type-error using custom middleware in specific view
This is my middleware class HasAccessMiddleware(object): def __init__(self, get_response): print("init") self.get_response = get_response def __call__(self, request): allowed_ips = WebSettings.get_allowed_ip() ip = request.META.get('REMOTE_ADDR') # Get client IP if ip not in allowed_ips: return HttpResponse("false", status.HTTP_401_UNAUTHORIZED) print("call") return self.get_response(request) this is my setting MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tools.middleware.HasAccessMiddleware', ) and this is my view @decorator_from_middleware(HasAccessMiddleware) def json_backup(request): pass I am getting this error TypeError: __init__() takes exactly 2 arguments (1 given) Would you help me find what is wrong? Thanks -
Django update all objects on html rows via save button
As per the below image I want to create a form where I can update the edited values. So far I can get the data from the request._post and loop thru the values and update them. Is there a better / simpler way of doing this ? ######################## MODEL ##################### class sampleModel(models.Model): primaryKey = models.CharField(max_length=100,primary_key=True) text = models.TextField(null=True,blank=True) ######################## VIEW ##################### def sampleModel_list_view(request): if request.method == 'POST': pass #DO SOMTHING objs = sampleModel.objects.all() context={'objs':objs,'title':'List of all objects'} return render(request,'sampleModel_list.html',context) ######################## HTML ##################### <form method='POST' action='.' enctype='multipart/form-data'> {% csrf_token %} {% for obj in objs %} <div class='card'> <div class='card-body'> <input type='text' name='primaryKey' placeholder='' value='{{obj.primaryKey}}' /> <input type='text' name='text' placeholder='' value='{{obj.text}}' /> </div> </div> {% endfor%} <input type='submit' class="btn btn-success" value='Save'/> -
At the time of registering a user, the username is automatically changed to a different username
I am creating two types of user using flags(is_grievant,is_department) The problem I am facing is that when I am registering a user, the username is automatically changed to a different username. What I mean to say is as you can see here, under the user model it is registered with the correct username(Asad) User Model, shown inside the Admin View but in the grievants model it is showing with the username(Raju). Raju is the username of a department model. Grievant Model, shown inside the Admin View view.py @method_decorator([login_required, grievant_required], name='dispatch') class GrievantComplaintListView(ListView): login_url = '/login/' model = Complaint context_object_name = 'complaint_list' template_name = 'grievant_complaint_list.html' def get_queryset(self): student = Grievant.objects.get(student=self.request.user) complaint_list = Complaint.objects.filter(grievant=student) return complaint_list @method_decorator([login_required, grievant_required], name='dispatch') class CreateComplaintView(CreateView): login_url = '/login/' redirect_field_name = 'complaint_detail.html' template_name = 'create_complaint.html' form_class = ComplaintForm model = Complaint def form_valid(self, form): student = Grievant.objects.get(student=self.request.user) form.instance.grievant = student return super().form_valid(form) class ComplaintDetailView(LoginRequiredMixin,DetailView): login_url = '/login/' model = Complaint template_name = 'complaint_detail.html' def grievant_register(request): registered = False if request.method == 'POST': if Grievant.objects.filter(Registeration=request.POST['Registeration']).count() >0: response = {} response['error'] = 'This Registeration Number already exists' return render(request,'student_register.html',response) user_form = SignUpForm(data=request.POST) profile_form = GrievantProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.set_password(user.password) user.is_grievant = True user.save() profile = … -
WebSocket handshake: Unexpected response code
(index):12 WebSocket connection to 'ws://app.quicktreatment4u.com/ws/chat/fsdfds/' failed: Error during WebSocket handshake: Unexpected response code: 404 -
Move http to https in Django
my website have SSL certificate. But when I scan by using ScreamingFrog, inlinks exist http. So, How can I move all http to https quickly instead remove each link in my post. Thanks. -
Django: How can I have two different ModelChoiceFields return to the same Model Field?
I want the user to be able to see which categories they are a part of, which would come from the Private_Users model. I also want them to be able to see which Private_Category they have created. First issue: private_category2 only returns the object from the Private_User. I want it to return the object from the Private_Category. Second issue: I want private_category2 to be entered into the same model field as private_category if private_category was never filled out. Is there any way to get these things done without creating a new field in Private_Category? forms.py class PostForm(forms.ModelForm): ... private_category = forms.ModelChoiceField(queryset = None, widget=forms.Select( attrs={ 'style':'width:33%;' }), required=False) private_category2 = MyModelChoiceField(queryset = None, widget=forms.Select( attrs={ 'style':'width:33%;' }), required=False) def __init__(self, user, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['private_category'].queryset = Private_Category.objects.all().filter(owner=user) self.fields['private_category2'].queryset = Private_Users.objects.all().filter(name=user) models.py class Private_Category(models.Model): owner = models.ForeignKey(User, related_name='privateowner', on_delete=models.CASCADE, null=True) category_password = models.CharField(max_length=50) title = models.CharField(max_length=200, unique = True) description = models.CharField(max_length=500) image = ProcessedImageField(upload_to='category_photo', processors=[ResizeToFill(500, 500)], format='JPEG', options={'quality': 100}) def __str__(self): return self.title class Private_Users(models.Model): name = models.CharField(max_length=50, null=True) category = models.ForeignKey(Private_Category, null=False, on_delete=models.CASCADE, default=None) def __str__(self): return self.name -
Check if a Model is already linked to its related Model via render_change_form
I have an admin form for adding Slides to my website's main slider on homepage. Now, the user has an option to link it to an existing news (using the news_slide field), so that a visitor can click on the slide and be redirected to the news article. The relationship between Slide & News is a 1-to-1 relationship. So, I had to filter the news_slide field so that it excludes News that are already linked to a slide (which I was able to do). But I have 2 problems now when user edits a Slide: The default value of news_slide is empty instead of the News it was associated to The News it was associated to is also excluded from the options. Let's say he only needed to change the Slide caption, but still he has to update the news_slide field (since it was changed to empty) yet he won't find that news on the options now. I need to know how to check if the Slide is linked to a News, and exclude ONLY those News that are linked to other Slides. Screenshot and code below: As shown, this Slide is linked to a News: But when I edit … -
Is it possible to make a mobile app in Django?
I was wondering if it is possible for me to use Django code I have for my website and somehow use that in a mobile app, in a framework such as, for example, Flutter. So is it possible to use the Django backend I have right now and use it in a mobile app? So like the models, views etc... -
Django Rest Framework CreateAPIView url primary key should be come from another model, not respected model
At first see my models: from django.contrib.auth.models import User class Group(models.Model): person = models.ManyToManyField( User, through='PersonGroup', related_name='person_of_the_group' ) class PersonGroup(models.Model): group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='group_person_of_group' ) person = models.ForeignKey( User, on_delete=models.CASCADE ) and this is my views: class AddGroupMembers(CreateAPIView): serializer_class = PersonGroupSerializers queryset = Group.objects.all() lookup_field = 'pk' def create(self, request, *args, **kwargs): # Make requst data mutable if not request.data._mutable: request.data._mutable = True request.data['person'] = request.user.pk request.data['group'] = kwargs['pk'] serializer = PersonGrouperializers(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) and this is my serializes: class PersonGroupSerializers(ModelSerializer): class Meta: model = PersonGroup fields = '__all__ I want the urls pk will be mess pk, http://127.0.0.1:8000/mess/api/v1/mess/<int:mess.pk>/ I want when i hit the endpoint, i should able to create PersonGroup where, if you see my views, you will know how i am populating this table. I mean, the endpoint url will be identified by any of Group pk but there i should able to PersonGroup Hope you got it, can anyone tell me how to achive this? -
Django - replace "model object" by the value
I have a model Currency defines below: class Currency(models.Model): """ Currency Model Defines the attribute of Currency """ class Meta: verbose_name = "Currency" verbose_name_plural = "Currencies" ordering = ['Currency_Name'] def __str__(self): return self.Currency_Name Currency_Date = models.DateTimeField(auto_now_add=True) Currency_Date_Update = models.DateTimeField(auto_now=True) Currency_Name = models.CharField(max_length=3, unique=True) Is_Secondary_Ccy = models.CharField(max_length=1, choices=Y_N_BOOLEAN) Primary_Currency = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True) # to refer to itself Primary_Factor = models.IntegerField(default=1) Currency_Name_Reuters = models.CharField(max_length=3) The model is linked to itself by the column "Primary_Currency" In my admin (image below) I can see the linked, but if i open the dropdown, the label is not user friendly "Currency object (0) etc..." Can I have the value "Currency_Name" of the "Primary_Currency" ? thanks for your help :) -
Not able to submit django form
I don't know why my form is invalid. Despite everything seems to be normal. I am not getting any error. sending you screenshot of models.py Here is my forms.py class LeadForm(forms.ModelForm): product_queryset = [] product_name = forms.MultipleChoiceField(choices=product_queryset, required=False) contact = PhoneNumberField() def __init__(self, *args, **kwargs): super(LeadForm, self).__init__(*args, **kwargs) self.fields["product_name"].choices = [(pro.get('id'), pro.get('name')) for pro in Products.objects.all().values('id', 'name')] class Meta: model = Lead exclude = ('created_at','created_by') widgets = { 'date_of_enquiry': DateInput(attrs={'type': 'date'}) } Here is my views.py def create_lead(request): u = User.objects.get(username=request.user.get_username()) if request.method == 'POST': print(request.POST) # form = LeadForm() form = LeadForm(request.POST) if form.is_valid(): print('inside valid') form.save(commit=True) form.created_by = u form.save() form = LeadForm() context = {"form": form} return render(request, 'create_lead.html', context) -
Python convert string to date-time format [duplicate]
This question already has an answer here: How to print a date in a regular format? 22 answers I have this string: '2020-04-10 10:00:23+00:00' I need this output: '04/10/2020 10:00 AM UTC' Is there any way to convert it in python or on front-end (angular/ionic4) -
Write data to xls and download it in python-django
I have successfully created .csv file and now want to create .xls for the same data. After which I want to download it as well. So after creation of csv file from python I am sending response to the ajax function and downloading it from there using jquery. def expense_export(request): print(request.POST) if request.is_ajax(): ids = request.POST.getlist('ids[]') expenses = Expense.objects.filter(id__in=ids) data = [] field = ['SLNO', 'Date of Recording', 'Category', 'Sub Category', 'Invoice Date', 'Invoice No', 'GST No. Mentioned', 'Vendor Name', 'Details', 'Gross Value', 'SGST', 'CGST', 'IGST', 'Total Invoice Value', 'TDS(if any)', 'Net Payble'] field1 = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Search Results.csv"' sno = 1 max = 0 for record in expenses: pay_data = [] if record.record: curr = 0 for pay_record in record.record: pay_row = [pay_record['date'], pay_record['amount'], pay_record['mode'], pay_record['ref'], pay_record['bank']] pay_data = pay_data + pay_row curr = curr + 1 if curr > max: max = curr gst_exist = 'No' if record.vendor: if record.vendor.gst_no: gst_exist = 'Yes' igst = int(record.gst) / 100 * record.amount tds = int(record.tds) / 100 * record.amount net_amount = int(record.amount) + int(igst) row = [ sno, record.timestamp.strftime('%d-%m-%Y'), record.expense_name, … -
JQuery - Changing calendar dates based on model data
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" (if the apartment already isn't booked ) and book the apartment. When the user clicks on the date input field, a jquery datepicker pops up and he can then pick the date via the calendar, same for end date. Once he goes through with the booking, I want the dates to be "disabled" in the calendar so no one else can pick them. This is the datepicker that I'm using: https://jqueryui.com/datepicker/ and the code: <script> $(function () { $("#datepicker").datepicker(); }); </script> Im a total Django / web development newbie, and need some pointers in order to start somewhere with this task, I know some JS but jquery is new to me, that's why I'd like some help. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I have an Reservation model which saves the start … -
Doubts how to design data with Django and PostgreSQL when having a value for every hour of the year
I am running a django app with PostgreSQL as my database. I have a building model called building. From this model I create many building instances. I have another model which is called forests from which I create many forests instances. (Let's assume I have even more models for which the same applies) Now I want to add data (let's call it x) for every building and for every forest for every hour of the year. That means I will have 8760 values for every building and forest instance. For instance: Hour1 : 234 Hour2 : 667 ... HourX : x ... Hour8760: 34 These 8760 values will be added, roughly estimated, 10-15 times a day, so that could lead to 131400 values a day. Now, I have doubts on how to design that. I thought I could go with a model like so: class Hour(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) forest = models.ForeignKey(Forest, on_delete=models.CASCADE) hour = models.IntegerField(...) value = models.FloatField(...) timestamp = models.CharField(max_length=200, null=True, blank=True) My second thought is to design it with a JSONField inside of an ArrayField like discussed here: Django JSONField inside ArrayField. So maybe I could save a dictionary for every building and every forest OR … -
problem with get_absolute_url django python
I used get_absolute_url in my app but it works only on admin site (by button view on site). On my website, the hyperlink is not responding. I've checked every line of code a couple of times and it seems like everything's fine. Does anyone know why it doesn't works? models.py class CrashReport(models.Model): number_id = models.AutoField(primary_key=True) date_notice = models.DateField(auto_now=False, auto_now_add=False) SHIFT_NUMBER = ( ('I', 'Zmiana I (6:00 - 14:00)'), ('II', 'Zmiana II (14:00 - 22:00)'), ('III', 'Zmiana III (22:00 - 06:00)'), ) which_shift = models.CharField( max_length=3, choices=SHIFT_NUMBER, blank=True, default='I', help_text='Zmiana.' ) who_notice = models.ManyToManyField(Author, help_text='Select a occupation for this employee') description = models.TextField(max_length=1000, help_text='Please type what happened') which_stuff = models.ManyToManyField(Device, help_text='Select a exactly devices') PROCESSING_STATUS = ( ('o', 'Otwarty'), ('p', 'Przetwarzanie'), ('z', 'Zakonczony'), ) status_notice = models.CharField( max_length=1, choices=PROCESSING_STATUS, blank=True, default='o', help_text='Status dokumentu.' ) def __str__(self): return f'ZGL /{self.number_id} / {self.which_stuff.all()} / {self.date_notice}' def get_absolute_url(self): return reverse('crashreport-detail', args=[str(self.number_id)]) views.py from django.shortcuts import render from django.views import generic from .models import CrashReport def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_crashreports = CrashReport.objects.all().count() # num_instances = BookInstance.objects.all().count() # Opens Crashreports (status = 'o') # num_crashreport_open = CrashReport.objects.filter(status__exact='o').count() context = { 'num_crashreports': num_crashreports, … -
Python Django render an html code from a db field
In my django project i have a model with a field that contain html code as text: html_test = models.TextField() for example in this field could be: <html> <header><title>This is title</title></header> <body> Hello world </body> </html> i would ti retrive this code and render dinamically showing the correspondenting html page without create a file or save it on disk. Someone know how can i render an html code in memory for display page and then destroy it? So many thanks in advance -
My swiper-pagination is overlapping with the text and my Hamburger appears behind the slider when open
i have a simple problem that i can't wrap my head around. My swiper-pagination that is supposed to appear at the bottom of the text overlaps with the text at the bottom of the page hence it cannot be seen clearly. I would like for it to appear like 10px below the text to clearly be seen by anyone visiting my site. Another problem is when you view it in mobile platform when you click on the hamburger the contents appear behind the slider and i would like then to come in-front of the slider and be clickable for clients to view the other pages. My project is on django and i have linked the swiper.min.js and swiper.min.css to my static root folder.My code is as follow below. If you seek more clarification please tell me and i will upload the additional details. Thanks in advance guys. Html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1'> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'buyer/main.css' %}"> <link rel="stylesheet" href="{% static 'buyer/swiper.min.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script … -
python manage.py migrate freezes
I'm trying to add forum to my website and I found saleor. So I want to test it on virtualenv first and I'm stuck following the installation. Whenever I run python manage.py migrate ... It just stucks showing no additional error I've created a new virtualenv then installed django, installed requirements via pip install -r requirements.txt in /saleor. I've set the database and user with superuser privileges set to all "saleor". I've changed my secret_key and port number in databases from settings.py. -
Can you reference only one from image gallery for Wagtail/Django?
{% for item in page.architecture_images.all %} {% image item.image fill-800x800-c100 %} <p>{{ item.caption }}</p> {% endfor %} Is there a way to call only one image from this gallery that has 2+ images in it? -
How to fix 'TypeError: join() ' When displaying DB Images in Django Templates
I am trying to display some images uploaded to my DB via the admin page using the image.url attribute. When the page loads, the image.url is correct, but the terminal shows an internal server error with the traceback ending with "TypeError: join() argument must be str or bytes, not 'list'" I can't find where specifically the join method is called as the traceback seems to only talk about internal files. I thought it might be related to an override save function, but commenting the function out yields the same results. settings.py STATIC and MEDIA and MEDIA_URL are all set. Template: <img class='project-details-image' src="{{ project.image.url }} Model: image=models.ImageField(upload_to='project-covers/', default='/Default.png', null=True) settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/my_portfolio/my_portfolio/static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'my_portfolio/static'), ] MEDIA_ROOT = [ os.path.join(BASE_DIR, 'my_portfolio/img'), ] MEDIA_URL = '/img/' Traceback: File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/views/static.py", line 36, in serve fullpath = Path(safe_join(document_root, path)) File "/home/user/django-portfolio/lib/python3.5/site-packages/django/utils/_os.py", line 32, in safe_join final_path = abspath(join(base, *paths)) File "/usr/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) … -
Django APIClient test case returns 400 but postman works
I have these test cases in my tests.py """Unit tests for client application.""" from django.test import TestCase from rest_framework.test import APIClient # Create your tests here. class ClientTestCase(TestCase): api_client = APIClient() def test_get_clients(self): response = self.api_client.get('http://127.0.0.1:8000/client/clients/') self.assertEqual(int(response.status_code), 200) def test_add_client(self): response = self.api_client.post( path='http://127.0.0.1:8000/client/clients/', data={ 'name': 'Jon Snow', 'age': 18, 'gender': 'M', 'address': 'night watch wall', 'phone_number': '+9290078601', 'email': 'jon@nightwatch.com', }, content_type='application/json' ) self.assertEqual(response.status_code, 201) When I run these tests through command python manage.py test --debug-mode client/ -v 3 test_get_clients succeeds and test_add_client fails as the API returns 400. When I hit the same API I am hitting in test_add_client through postman, it returns the expected result. The body of postman API is { "name": "Bruce Wayne", "age" : 23, "gender" : "M", "address" : "abc asdasd asdasd asdada", "phone_number" : "+92 3242225259", "email" : "abc@xyz.com" } and in header there is Conent-Type:'application/json as I am already specifying in my test case. What might I be missing here? The output of running test case is not giving any insight at all.