Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Cannot resolve keyword 'field_object' into field
I have a field object that I want to do filtering with Since the filter field will change dynamically. only_user=User.objects.first() field_object = only_user._meta.get_field(field) QuerySet = User.objects.filter(field_object="xxx") But I couldn't do it, it said Cannot resolve keyword 'field_object' into field. Choices are: ..... -
Creating and receiving model objects
In the admin area, I can create an object of class User, while selecting the project and filling in the user field. Now I have a base.html form, where there is a user field, and the project field is not, because I am on the page of a certain project with a unique id (for example: the form is on the / project / 1 / page (id = 1)). The question is how to create an object of the User class from a form so that it automatically appears in the admin panel. I managed to do this if you ignore the project (ForeignKey). Tell me what to add? base.html <form action="" method="post"> <textarea name="name"></textarea> <button type="submit">Send</button> </form> models.py class User(models.Model): project = models.ForeignKey(Project) user = HTMLField(blank=True, null=True) views.py def index(request): user = Project.objects.all() return render(request, "base.html", {"user": user}) def retro(request): a = User.objects.all() return render(request, "create.html", {"a": a}) def create(request): if request.method == "POST": tom = User() tom.name = request.POST.get("name") tom.save() return redirect('/') else: form = UserForm() return render(request, 'save.html', {'form': form}) In the admin there is a field project, i.e. drop-down list in which we can choose. Each project has its own id. When I am on … -
Not getting model form values in template
Django user profile model form data is not getting displayed on the template, not even giving me an error! I am learning to create Django registration form with user profile models I have created the registration form and profile form successfully but I am not getting any values from models.py file. Models.py class ExtenduserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) age = models.IntegerField() def __str__(self): return self.user.username @receiver(post_save,sender=User) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = ExtenduserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py class userprofile(forms.ModelForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = ExtenduserProfile fields = ('age','birth_date') views.py @login_required() def UserProfile(request,pk=None): profile = ExtenduserProfile.objects.all() return render(request,'dashboard/profile.html',{'profile':profile}) @login_required() def HomeScreen(request): if request.user.is_authenticated: username = request.user.username else : username = 'not logged in' context = {'username':username,'user':user} return render(request,'dashboard/Home.html',context) def singup(request): if request.method == 'POST': form = SignupForm(request.POST) user_profile = userprofile(request.POST) if form.is_valid() and user_profile.is_valid(): user = form.save() profile = user_profile.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username = username, password = password) login(request,user) return redirect(login_view) else: form = SignupForm() user_profile = userprofile() context = {'form':form, 'user_profile':user_profile } return render(request,'account/signup.html',context) HTML file {% extends 'dashboard/base.html' %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Profile</title> </head> {% block content%} <body> … -
Not able to access ForeignKey object using primary key
I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong, I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong I have already tried qs = Ipd.objects.get(patient__id=patient_id) qs = Ipd.objects.filter(patient__id=patient_id) qs = Ipd.objects.filter(patient_id=patient_id) but nothing worked models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False) def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient', 'reason_admission', 'presenting_complaints', 'rooms', 'date_of_admission'] views.py: @login_required def ipd(request, patient_id): object = Ipd.objects.filter(patient__patient_id=patient_id) if request.method == "POST": formtwo = IpdForm(request.POST) if formtwo.is_valid(): instance = formtwo.save(commit=False) instance.save() else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'object': object, 'form2': formtwo}) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), … -
Multi parameter method in django viewset router
May i know how to setup method with multiparameter like=> @action(methods=['get'], detail=True) def byshiftid(self, request,shiftid): print("Hello World") query = self.get_queryset().get(shiftid=shiftid) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) this shiftid is the parameter. Here is my router=> router.register('shifts_mas', ShiftViewSet, base_name='shifts') Normally my url will be like => api/shift_mas/ Now i would like to do like => api/shift_mas/byshiftid/?shiftid="shift1" something like that. I try like that => @action(methods=['get'], detail=True,url_path='/(?P<shiftid>)') def byshiftid(self, request,shiftid): print("Hello World") query = self.get_queryset().get(shiftid=shiftid) serializer = ShiftSummarySerializer(query,many=True) return Response(serializer.data) But its always say 404 not found. My requirement is to select the record by shiftid.So how can I setup the route like that? -
After receiving the signal how to render it out into template? *DJANGO*
I'm having a hard time rending out into template? after receiving the signal. like how to render the "hehe" into the page or html file i want. @receiver(post_save, sender=Person) def my_callback(sender, **kwargs): print("hehes") -
How to customize login form design?
I want to customize and create my own design on my login form but i don't know how to call the login form i use the form inside the admin. How can i remove the username: & password: and put it inside the text box ? i don't know how to start. Login.html <div class="container"> <form method="post"> {% block content %} {% csrf_token %} {{ form.as_p }} <button type="submit" name="button">Login</button> {% endblock %} </form> </div> {% endblock %} my output Username: {text box} Password: {text box} login button what i want is {text box "Username" "username_icon"} {text box "Password" "password_icon"} button login -
How to convert OrderedDict to Json
I am getting an OrderedDict from an API text in Django-Rest-Framework, how do i convert it into valid json? response = self.client.get(self.api_path + '/stuff.json') gives me [OrderedDict([('title', u'TestTitle'), ('items', [OrderedDict([('item1', u'test1'), ('item2', u'test2')])])]), OrderedDict([('title', u'TestTittle2), ('items', [OrderedDict([('item1', u'Fun stuff'), ('item2', None)])])])] if i use json.dumps() its gives me a json object but it changes None to null which invalidates the json I expect a Json object without replacement of None to null -
Como personalizar el queryset de de la vista generica list view en django
quiero un ejemplo de como personalizar el queryset de la listview en django, basicamente quiero aplicarle unos filtros pero no se como modificarla