Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I need help in designing a database (and signup and login on base of their role )in which there are three user
I want make sign up and login on the base of their role there admin can add users and approved the request of other two user so that they can login.When user click on the sign up the user see sign up page accorading to their roll and same for login . -
how to get rid off RecursionError: maximum recursion depth exceeded in comparison
I have written code for a user feedback form, but i get error called "RecursionError: maximum recursion depth exceeded in comparison". I have tried to add "import sys" in order to increase the default recursion depth limit by changing the number of limit in "sys.setrecursionlimit(1000)" but still I get the same error. views.py def ContactForm(request): submitted = False if request.method == 'POST': query_form = ContactForm(request.POST) if form.is_valid(): cd = query_form.cleaned_data # assert False return HttpResponseRedirect('/ContactForm?submitted=True') else: form = ContactForm(request) if 'submitted' in request.GET: submitted = True return render(request, 'ContactForm/contact.html', {'query_form': query_form, 'submitted': submitted}) -
When accessing a resource on website a forward slash gets removed from url when redirecting to https
I have an Nginx serving my django application. When I try to access example.com/resource it should redirect to https://example.com/resource but in my case it redirects to https://example.comresource (removing the / before resource) I have a very minimal Nginx configuration (as you'll see below). I don't know where to start to figure out what's wrong. server{ listen 443; listen [::]:443 ssl; ssl on; ssl_certificate /etc/ssl/example_com.crt; ssl_certificate_key /etc/ssl/example_com.key; server_name example.com; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /static/ { autoindex on; alias /home/administrator/example/collectedstatic/; } location /media { alias /home/administrator/example/store; } } server { listen 8000; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/administrator/example/collectedstatic/; } location /media { alias /home/administrator/example/store; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } There are no error messages, just a webpage not found. -
Django: How to get setUpTestData to run once for all tests?
I am running django + django_tenants + django_restframework. In the mulit-tenant environment, there needs to be an instance in the tenants table for each schema - in my testing, that means "public", "test", and "test2". Creating those tenants, and their corresponding schemas, need to be created for all tests. The data in those instances will not change, so I want to do this once at the beginning of the test run, and not have it repeated again for the duration. The things I've learned from my research: setUp() runs before each individual test setUpClass() runs before each test case setUpTestData() runs before each test case The problem I've run into is, when my second set of tests run, I get exceptions when trying to create the tenants/schemas because they already exist. I've also found setup_databases() in the Django advanced testing doc and am wondering if that is the place for this... i.e. can it be subclassed? This is my base class that all tests subclass from... class TenantTestCase(APITestCase): public_tenant = None test_tenant = None test2_tenant = None @classmethod def setUpClass(cls): cls.add_allowed_test_domain() cls.setUpTestData() @classmethod def setUpTestData(cls): print('run setUpTestData') cls.public_tenant = Tenant.create_tenant('Public') cls.test_tenant = Tenant.create_tenant('Test') cls.test2_tenant = Tenant.create_tenant('Test2') connection.set_tenant(cls.public_tenant) I read that … -
RichTextUploadingField does not save html tags
I'm using a RichTextUploadingField, but it does not save tags. # from ckeditor_uploader.fields import RichTextUploadingField used # in first line text = RichTextUploadingField(verbose_name='text', blank=True) after using this code it will show an editing box for text. but if I set a text to be some tag like , next time I try to edit entered text, it's not set to be also in my website it does not show it as an . -
subclass model auto increment does not with inheritmodel with autofiled in django
I defined a base class in django model like below class BaseModel(models.Model): id = models.AutoField(primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: abstract = True and I defined another class for actual model class Destination(BaseModel): city = models.CharField(max_length=100) I thought that when i create a Destination obeject dest = Destination(city='New York') dest.save() It'll automatically create an id, but apparently not. I got following error: NOT NULL constraint failed: tripmatch_trip.destination_id So how to use model inheritance and autofield correctly in django Thanks -
Validation of a Django model using a foreign key set after saving the form
I'm trying to do validate a Model based on a value that I set after save(commit=False). How can I achieve this? I have multiple Forms (Item, Listing, Price) that I combine in one view and then create one instance after the other while saving. # models.py ... class Category(models.Model): ... class Item(models.Model): category = models.ForeignKey(Category, ...) class Listing(models.Model): for_item = models.ForeignKey(Item, ...) class Price(models.Model): for_listing = models.ForeignKey(Listing, ...) amount = MoneyField(...) class MinPriceForCategory(models.Model): category = models.ForeignKey(Category, ...) amount = MoneyField(...) # views.py ... def add_item(self): ... # create form instances from request.POST etc ... item = form_item.save() listing = form_listing.save(commit=False) listing.for_item = item listing.save() # validation happens in the first call to save() price = form_price.save(commit=False) price.for_listing = listing # I need the validation to happen here so the instance of Listing is available price.save() -
Adding an InlineField to a ClusterableModel does not work
I have a Page class called EventDetail which in turn holds several messages (to be sent out via a cronjob). This is done as shown in the docs here: https://docs.wagtail.io/en/v2.5.1/reference/pages/panels.html?highlight=available%20panel%20types#inline-panels The thing is that I also want to be able to append several files to each message. But now I am not on a Page class any more, and I cant get it to work. I read on other forum posts, that it is possible to to this by making the model that should hold the InlinePanel into a ClusterableModel, but I cant get it to work. When doing this I get the following when accessing the page: FieldError at /admin/message/eventdetailmessage/create/ Unknown field(s) (files) specified for EventDetailMessage My code: class Message(models.Model): """ An abstract model of messages connected to an eventdetail """ title = models.CharField(max_length=255, blank=True) content = models.TextField() send_time = models.DateTimeField(verbose_name=_("Message send time")) sent = models.BooleanField(default=False) @property def edit_link(self): return self.url_helper.get_action_url("edit", self.id) @property def delete_link(self): return self.url_helper.get_action_url("delete", self.id) @property def create_link(self): return f"{self.url_helper.get_action_url('create')}?id={self.event_detail.id}" panels = [FieldPanel("title"), FieldPanel("content"), FieldPanel("send_time")] class Meta: abstract = True class EventDetailMessage(ClusterableModel, Orderable, Message): """ The actual implementation. Done like this in case we want do use wagtails built in functionality for creating on the fly. … -
how to get the value from the database based on the id
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input on another field. my question is how to hide the required option based on the returning ID. views.py def getSource(request): sources = Source.objects.all() return render(request,'create_folder.html',{'sources':sources}) create_folder.html <div class="formSelect" id="mouresaleMasdarDiv"> <select id="mouresaleMasdar" name="gender" required> <option value="">-- soource--</option> {% for source in sources %} <option val="{{ source.source_name }}"> {{ source.source_name }} </option> {% endfor %} </select> </div> <script type="text/javascript"> $('#mouresaleMasdar option[value="{{sources.get(pk = 1)}}"]').hide() </script> It gives an error so how to make this value hidden based on the id. -
Django - FileFields are not saved in db
I'm trying to create a form where admins could upload some file with FileField. Here is what I currently have: models.py class PhytoFile(models.Model): date = models.DateTimeField("Date", default = datetime.datetime.now) general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True) class Meta: verbose_name = "Liste - Fichier phyto" verbose_name_plural = "Liste - Fichiers phyto" def __str__(self): return str(self.date) views.py class AdminFichiersPhyto(CreateView): template_name = 'phyto/phyto_admin_fichiers.html' model = models.PhytoFile fields = ['general_treatment', 'other'] def form_valid(self, form): form.save() if self.request.POST.get('autre'): # gonna add some code to read the 'other' file print("autre") if self.request.POST.get('trtm_gen'): # gonna add some code to read the 'general_treatment' file print("traitement généraux") return HttpResponseRedirect(self.request.path_info) When I click on the Submit button created in a template, in the admin page I got a new line in my table, but the file I targeted with the FileField hasn't been saved. Do any of you have any idea of where it could come ? -
Django Database Query Optimisation with iterator() in templates
There are several rules on how to Optimise Database Queries in Django. One of them is iterator(). Does it make sense to use iterator in templates(HTML files)? Or when I loop in the template with for statement it is already an iterator and no additional optimization is needed? Example: {% for item in items.all%} {{ item.name }} {% endfor %} VS {% for item in items.all.iterator %} {{ item.name }} {% endfor %} -
Can I putting the whole excel in html which can have full excel functions
I am using django to build a website which can read an excel file and have some data modification. I would like to do something like everytime clicking save will automatically save a new version without replacement to my database. But I found that all the functions like search, copy, replace, filling rows should be written by myself, which is pretty complicated. Is there any way to post a excel on my website with all the excel functions like the one in excel web? The html just perform like another web version excel -
ModuleNotFoundError: No module named 'selenium' with django project
I am using selenium with Django project, when run server from Pycharm gives me importError but when run server from cmd works well why ?? -
multiprocessing is failing in psycopg2 2.8.3 version
I have updated the psycopg2 version to 2.8.3. After doing that multiprocessing connection pool is failing. Error traceback """ Traceback (most recent call last): File "/usr/local/lib/python3.5/multiprocessing/pool.py", line 119, in worker result = (True, func(*args, **kwds)) File "/usr/local/lib/python3.5/multiprocessing/pool.py", line 44, in mapstar return list(map(*args)) File "/app/project/utils/ddr_algorithm_main.py", line 461, in get_actual_datapoints years_in_practice = ddr_obj.get_years_in_practice(single_data_list_static) File "/app/project/utils/ddr_report_algorithm.py", line 436, in get_years_in_practice provider_data[3]) File "/app/project/utils/ddr_report_algorithm.py", line 477, in get_single_provider_years_in_practice_list list_result = [int(str(i[0]).split(',')[1]) for i in provider_years_in_practice_list if File "/app/project/utils/ddr_report_algorithm.py", line 478, in <listcomp> i[0] and str(i[0]).split(',').__len__() > 1] ValueError: invalid literal for int() with base 10: ' 1994)' """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/project/medical_info/management/commands/ddr_data_points.py", line 13, in handle ddr_main_class_obj.main() File "/app/project/utils/ddr_algorithm_main.py", line 358, in main create_datapoints = calculateParallel(provider_ids, threads=30) File "/app/project/utils/ddr_algorithm_main.py", line 554, in calculateParallel results = pool.map(class_obj.get_actual_datapoints, provider_ids) File "/usr/local/lib/python3.5/multiprocessing/pool.py", line 266, in map return self._map_async(func, iterable, mapstar, chunksize).get() File "/usr/local/lib/python3.5/multiprocessing/pool.py", line 644, in get raise self._value ValueError: invalid literal for … -
How to use HTTPS for LiveServerTestCase and StaticLiveServerTestCase?
Both django.test.LiveServerTestCase and django.contrib.staticfiles.testing.StaticLiveServerTestCase use HTTP connections only. I am currently writing integration/functional tests for a web app where people make payments using Stripe. To display the credit card form that comes from Stripe requires the use of HTTPS on the page, otherwise the credit card form will refuse to load. As such, I need something like StaticLiveServerTestCase that uses HTTPS connections so that the credit card form can load and be tested. What are the available solutions? Is running an external server (e.g. gunicorn, uwsgi) serving the django project over HTTPS the only viable option? -
Recursive string compare in Python
I have to compare two compare a list of strings fetched from the database and from a file. The data object could vary in length and I don't want the code to break because of the length. the condition is if obj1 >= obj2 the perform the code. but since the data can vary in length I have to hard code every possibility according to the length, which is tiring. According to the code if the obj1 length is greater than obj2 length then perform the program. Can you please tell me a way where I can compare a string of length 8 and length 4 without hard coding it through if else. I believe this is achievable through while loop. Which is sadly my weak point. HELP would be greatly appreciated. def LCR(): dest = Destination.objects.values_list('dest_num', flat=True) # This method turn the fetched data into a list. Example #['1233','4412','23135','123'] rates = {} ratelist = {} csv_file = open(r'.\adoc.csv') data_set = csv_file.read().decode("UTF-8") io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=str(u",")): rates[column[0]] = column[1] #Example data #['8523654','754','4563'] for desNum in dest: desNum = str(desNum) # print type(desNum) for venNum, venValue in rates.items(): venlen = len(venNum) deslen = len(desNum) if venlen … -
Programmitically use 'inspectdb' during runtime on dynamic database connections
I have a Django project where groups of users have their own database ("projects"). These projects are saved in a main database, from which django reads all the current projects and from those makes connections to their databases. This is why the connections are not written in settings.py. The piece of code that dynamically connects to the project-databases is run in the root urls.py, since I learned form another thread on stackoverflow that the code there is run once on start-up. Whenever a new project is created by a user, a piece of code creates a new database and connects to the new database by appending a connection to settings.DATABASES (see sample code below). A external program is triggered to fill the new database with data. Now the problem is that I cannot immediately use the database, since first I would need to run inspectdb to get the ORM structure for Django. I want to do this at runtime, because having to shut down the server and restart it would mean other users could not use their projects during that time. But even manually using the commandline, Django answers with an error that the connection does not exist. (I guess … -
User login with Django
I have a different user model with Django that does not refer to the specific user model. I know I need to use a custom user model, but in my case I have to use it like this. How do I log in for the registered user here? So how to use login? models.py class Shop(models.Model): name = models.CharField(max_length=100) email = models.EmailField() username = models.CharField(max_length=80) password = models.CharField(max_length=20) phone_number = models.CharField(max_length=11) phone_number2 = models.CharField(max_length=11) fax = models.CharField(max_length=11) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True) avenue = models.CharField(max_length=30) street = models.CharField(max_length=30) block = models.CharField(max_length=30) number = models.CharField(max_length=30) floor = models.CharField(max_length=30) def __str__(self): return self.name I want him to login with his username and password, but I can't succeed. -
Google Calendar API: Timezone bug
I am having a hard time figuring out why the Google calendar notifications always convert my event timings from the given timezone to the default timezone. Here is my event data: data = { 'summary': booking.calendar_event_title, 'description': booking.calendar_event_description, 'start': {'dateTime': start_date, 'timeZone': booking.address.timezone}, 'end': {'dateTime': end_date, 'timeZone': booking.address.timezone}, 'location': booking.address.formatted_address, 'timeZone': booking.address.timezone, 'attendees': [...], } Here, the start_date and end_date are in (let's say) CDT format. I'm passing the correct timeZone value as well. However, when I receive the calendar invite, It always shows time converted into the standard timezone (which is AEST in my case). I don't know what is going on here. Please help. -
Writing to an excel file and downloading it using django -XLWT
Im writing a code to open and write to an excel file and download it later using xlwt in python-Django. The code executes without error but the file is not getting downloaded in browser. Can anybody lookout what is missing? Thanks in advance My Code is similar to the accepted answer in this question on stackoverflow django excel xlwt resp = readExcel(request,path,filename) #Fuction Call print(resp) #Prints <HttpResponse status_code=200, "application/ms-excel"> def readExcel(request,filename,filename1): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="ErrFile.xlsx"' Error_workbook= xlwt.Workbook(encoding='utf-8') sheet1 = Error_workbook.add_sheet('attendance') ---Writing to excel sheet-- Error_workbook.save(response) return response I wanted the file to be downloaded in the browser -
django - syntax error for python f-sring in view
This gives my error: def get_desc(order): return f"""name: {order.name} phone: {order.phone}""" def pay(request, order) desc = get_desc(order) . . . Why? django doesn't support f-strings? -
Why is my function returning the object identity instead of the 'ip' variable?
Upon saving User sign up form, I expect to save an ip address of the user. I get the object identity of the get_client_signup_ip function instead: <function get_client_signup_ip at 0x04461810> forms.py: def save(self, commit=True, request=None): # user object (customuser) form is called to save with commit=true, so it gets teh ip and saves. user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.origin_ip = views.get_client_signup_ip if commit: user.save() return user views.py def get_client_signup_ip(request): g = GeoIP2() x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for ip2 = '192.227.139.106' city = g.city(ip2) else: ip = request.META.get('REMOTE_ADDR') ip2 = '192.227.139.106' city = g.city(ip2) return HttpResponse(ip) urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path('signup/', views.get_client_ip, name='signup_ipaddress') ] I expect to see an ip address in the User's origin_ip field. Instead I get an object identity for the get_client_sign_up function. -
Change ModelSerializer field key with function
I have a simple Django Rest Framework ModelSerializer for a model that has a field "name". I want to serialize it so the name is the value and its cleaned name is the key in the following way: "results": [ { "mymodel1" : "My Model 1" }, { "mymodel2" : "My Model 2" }] I currently have: class ModelSimpleSerializer(serializers.ModelSerializer): keyname = serializers.SerializerMethodField('get_model_keyname') class Meta: model = myModel fields = ( 'keyname', ) def get_model_keyname(self,obj): keyname = obj.name keyname = keyname .lower() keyname = keyname .replace(" ", "") return keyname which returns: "results": [ { "keyname" : "mymodel1" }, { "keyname" : "mymodel2" }] Any ideas? Thank you! -
Django combine 2 model queryset that have same value
I Have the following two model queryset, and I want to combine that have same value, Could you please have your suggestions on this??, any help will be appreciated. i already try this but not same what i want after= list(chain(q1, q2)) after= q1 | q2 q1 = [ {'cell': 633, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 634, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 635, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 636, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 637, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 638, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 639, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 640, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': 90, 'total_time': Decimal('7.920'), 'total_time_ot': Decimal('0.990'), 'total_time_ot1': Decimal('0.990'), 'total_time_ot2': Decimal('0.990'), 'total_time_ot3': None}, {'cell': 641, 'model': 'superstar', 'total_output_jam': 240, 'total_output_ot': … -
Warning : Unresolved import & Undefined Variables In Visual Studio Code Using Django [duplicate]
This question already has an answer here: Pylint “unresolved import” error in visual studio code 6 answers See Source Code Image here...Project Executed But When Open Source Code File Show Some Warning