Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Class has no objects member pylint
Ever since I started learning Django, I get an error appearing all over Visual Studio. Data mobel names get underlined in red. All the code works so this is more of an annoyance than anything. -
how to pass variables in the urls in django?
i tried to pass variables in url in django but it keeps getting 404 error urls.py from django.conf.urls import include, url from django.contrib import admin from test_url import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^detail/<int:id>/',views.detail) ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def detail(request,id): return HttpResponse("<h1>{}.</h1>".format(i -
Django Email Timeout on Production Server
I recently deployed a site that I developed in Django onto a production server running Ubuntu 19.10 and Apache/2.4.41. I've been able to get my site functioning in every respect with the exception of sending emails using SMTP. When running my site on the development server on my local machine Django is able to send emails without issue, but on the production server any attempt by the site to send an email hangs and eventually results in a server error. In Apache's error.log I'm finding this at the bottom of the traceback: TimeoutError: [Errno 110] Connection timed out. Curiously, this problem persists if I turn on port 8000 and run this site with Django's development server from the remote machine. I've made sure that my settings.py is configured properly (as I mentioned this works fine on my local computer). settings.py ... EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = site_config.get('EMAIL_USER') EMAIL_HOST_PASSWORD = site_config.get('EMAIL_PASS') My suspicion has been that the issue must be related to my firewall blocking outgoing traffic on port 587, but I double checked my settings and couldn't see how this could be the case. I even manually set rules to allow … -
Choosing from a list of text files from Google Drive into my Django app homepage?
So I'm trying to get a grasp for how authenticated requests work with the GoogleDrive API. I'm needing to pull a list of text files from Google Drive to select for uploading to my app window. The way I had imagined it was how draw.io does their interface where you choose to Google Drive and it will show a list of items in your drive. Not sure how to go about doing this so any help or guidance would be awesome -
Want to return invoice total in django app
here i want to return invoice total in my Django Order App. In my models.py i took a field named total_amount with default value is 0. Then, i wrote this piece of code to get total amount. def get_total_amount(self): return sum(self.products.all().values_list('total_amount', flat=True)) But, somehow it returns the default value 0 not the total amount. How can i get total amount? Please see my models.file and also screenshot i attached below. models.py: https://paste.ubuntu.com/p/jNg6wpwRTD/ screenshot: https://i.postimg.cc/mgz4d6TJ/screenshot-01.png Thanks in Advance. -
Login user with a login link
I want to send a login link to the users. I know there are some OneTimePassword apps out there with thousands of features. But I just want some easy and barebon way to login user via login link. My question is if this is a correct way to go about this. Like best practice and DRY code. So I've set up a table that stores three rows. 1. 'user' The user 2. 'autogeneratedkey' A autogenerated key 3. 'created_at' A Timestamp When they login, the'll be sent a mail containing a login link valid for nn minutes. So the login would be something like https://example.net/login/?username=USERNAME&autogeneratedkey=KEY The tricky part for me is to figure out a good way to check this and log in the user. I'm just guessing here. But would this be a good approach? class login(generic.CreateView): def get(self, request, *args, **kwargs): try: autgeneratedkey = self.request.GET.get('autgeneratedkey', '') username = self.request.GET.get('username', '') obj_key = Login.objects.filter(autgeneratedkey=autgeneratedkey)[0] obj_user = Login.objects.filter(userusername=username)[0] try: if obj_user == obj_key: #Compare the objects if same if datetime.datetime.now() < (obj_key.created_at + datetime.timedelta(minutes=10)): #Check so the key is not older than 10min u = CustomUser.objects.get(pk=obj_user.user_id) login(request, u) Login.objects.filter(autgeneratedkey=autgeneratedkey).delete() else: return login_fail else: return login_fail except: return login_fail return redirect('index') def … -
Angular 8 upload file to Django server with FormControl
Note: I don't want to use FormData, want to use FormControl if is possible. I have a form that send some data to Django server and it handle it and store the data. Here is my Django funcion def create(self, request): company = CompanyForm(request.data, request.FILES) if company.is_valid(): company = company.save() serializer = CompanySerializer(company) return JsonResponse(request.data, safe=False) else: return JsonResponse(request.errors, safe=False) This is the Angular Form <form [formGroup]="companyForm" id="ngForm" enctype="multipart/form-data" #documentEditForm="ngForm" (ngSubmit)="CreateCompany()"> //Some other fields. <mat-form-field> <ngx-mat-file-input formControlName="com_logo" placeholder="Logo"></ngx-mat-file-input> <mat-icon matSuffix>folder</mat-icon> </mat-form-field> </form> As you see I use the ngx-mat-file-input for input file handling here is the component codes for FormControl companyForm = new FormGroup({ com_name: new FormControl('', Validators.required), com_owner: new FormControl('', Validators.required), com_phone: new FormControl('', Validators.required), com_address: new FormControl(), com_email: new FormControl(), com_status: new FormControl(), com_website: new FormControl(), com_logo: new FormControl(), }); // From Array of errors to show on front end. formErrors: any = {} CreateCompany(): void { this.apiService.createItem(this.companyForm.value, 'company').subscribe( result => {}, error => {} ); } As I checked the console, I send the image info to server, but when I return the request.FILES on Django it is empty. {com_name: "Pomtech", com_owner: "JSsss", com_phone: "072044920", com_address: "9170 N. Beacon Rd",…} com_name: "Pomtech" com_owner: "JSsss" com_phone: "072044920" com_address: … -
How to make a Django website HTTPS using AWS ElasticBeanstalk, AWS Certificate Manager, and a domain from NameCheap?
I have followed these procedures: Purchased a domain from NameCheap: yartsagumba.com Uploaded a django website to AWS Elastic Beanstalk, and the django website runs on the browser by clicking on url of AWS eb: https://django-env.fi9zmpvvyq.us-east-1.elasticbeanstalk.com/ Added CNAME to url of AWS eb to Namecheap in Advanced DNS. Created a SSL certificate by using AWS Certificate Manager, and approved the certificate received on my email with the domain name: *.yartsagumba.com Used AWS Route 53 with the following configuration. Modified Load Balancer as below: Most of the documents implies that these steps should suffice. The website: yartsagumba.com is working without https. In order to make my website https, do I need to change any setting inside the django project? -
Using datetime.strftime and soutract it with timedelta
I am trying to use datetime.now() with timedelta and soustract it so I get the time for yesterday. yesterday = datetime.now().strftime("%Y-%m-%d") - timedelta(days=1) But when I tried to do it, it gives me this error : unsupported operand type(s) for -: 'str' and 'datetime.timedelta' So I tried to convert it to an int but with no success. -
Default value in Django templates
I wanted to have a little form in my django template, that would pop-up as "Materialize Modal" on clicking a button. And one of the field should be a pre-filled value from one of the model in my project. I used a normal html form and add a prefilled value with our very own django double curly braces {{}}. But it is showing only 1st object value of that category class. I tried to google but i cant find if there is some different keyword to use for pre-filled form value. Here is how my template look like. {% for a in category.articles_set.all %} <div class="container"> <div> <label>Article</label> <input type="text" value="{{a.name}}"> </div> <div> <label>Address</label> <input type="text" value="{{a.address}}"> </div> <div> <label>email</label> <input type="text" value="{{a.email}}"> </div> </div> {% endfor %} -
'django_pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX',
DATABASES = { 'default': { 'ENGINE': 'django_pyodbc', 'PORT': '1433', 'NAME': 'course', 'USER': 'sa', 'PASSWORD': '1234', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, }, }, } -
can i insert to db through model.py in django python
can i insert data through model.py in django model.py class details(models.Model): team_id = models.AutoField(primary_key = True) gbu_id = models.IntegerField() team_name = models.CharField(max_length=48) team_desc = models.TextField() updated_time = models.DateTimeField(default=datetime.datetime.now()) status = models.IntegerField(default=1) @staticmethod def add_team_details(): details_obj = details() details_obj.gbu_id = "2" details_obj.team_name = "FTO" details_obj.team_desc = "test data" details_obj.save() return "Success" -
Need to run django application in a domain name without specific port
I am newbie to Django recently I created a Django app and I uploaded to the server. I assigned a domain name to it. each time I run the server I need to type xyz.com:8000 to see my website. Is there any way to resolve this issue? Also, I have doubt. Do I need to type python manage.py runserver 0:8000 to launch the website or it's just run automatically like PHP. -
setting form data in views
I'm using django-shapeshifter (https://pypi.org/project/django-shapeshifter/) with two forms, FormA and FormB - these are combined into a single form. THey are model forms, so I'm using MultiModelFormView from shapeshifter. views.py class AddFormsView(LoginRequiredMixin, MultiSuccessMessageMixin, MultiModelFormView): form_classes = (zooForm, animalMetadataForm) template_name = 'zoos/add_zoo_shapeshift.html' success_url = '/' def forms_valid(self): forms = self.get_forms() raven_form = forms['ravenmetadataform'] recording_form = forms['recordingform'] if recording_form: recording_form.data['created_by'] = self.request.user return super(AddFormsView, self).forms_valid() If I try setting data in the forms_valid method I get warned that This QueryDict instance is immutable When using normal modelforms (i.e. without shapeshifter) I have previously set form values in the form_valid method, for example: def form_valid(self, form): context = self.get_context_data() animal_data = context['animal_data'] with transaction.atomic(): form.instance.created_by = self.request.user I guess the equivalent isn't supported -
Unique together with Django models
I recently had a table in my database which made use of the Unique_together() function. My script collected data and inserted unique values into my Database without any problems. I then messed up my model and migrations and now, I can't get it to work properly. My script manage to insert just one row in the database and nothing else. I just can't seem to find what I have messed up. Any feedback/help would be highly appreciated! from django.db import models # Create your models here. class tablol(models.Model): a = models.DateTimeField(null=True, default=None) b = models.CharField(primary_key=True, max_length=50) c = models.CharField(max_length=50) d = models.CharField(max_length=50) e = models.CharField(max_length=50, null=True, default=None) f = models.CharField(max_length=50, null=True, default=None) g = models.CharField(max_length=50) h = models.CharField(max_length=50, default=None, null=True) i = models.CharField(max_length=25) j = models.CharField(max_length=50) k = models.IntegerField() l = models.CharField(max_length=15, null=True, default=None) m = models.DecimalField(max_digits=10, decimal_places=4, null=True, default=None) n = models.CharField(max_length=5, null=True, default=None) o = models.CharField(max_length=50, null=True, default=None) p = models.CharField(max_length=50, null=True, default=None) q = models.CharField(max_length=50, null=True, default=None) class Meta: managed = True db_table = 'tablol' unique_together = (('b', 'c', 'd', 'g', 'i', 'j', 'k'),) def __str__(self): return self.names -
Using Python 3/Django, how do I export MySql table data as a YAML file?
I'm using Python 3.7, Django 2.0 with MySql 5.7. I have an InnoDB table mysql> show create table address_country; +-----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | address_country | CREATE TABLE `address_country` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) COLLATE utf8_bin NOT NULL, `code` varchar(2) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=499 DEFAULT CHARSET=utf8 COLLATE=utf8_bin | +-----------------+-------------------------------------------------------- How do I export the table data as a YAML file? I would preferably like to develop a solution that doesn't hard-code any of the MySql table name or columns but any solution is better than no solution at this point. -
How to merge pdf in Django when the files are protected and serviced by X-sendfile and Apache/Nginx?
I'm currently using x-sendfile and Apache to service protected media files on a django based web-app. The server is configured such that the code only has indirect access to the protected media files through apache and x-sendfile: if request.user.hasPermission(): response['X-Sendfile'] = unicode(filename).encode('utf-8') return response This works great for 1 file, but I would like to implement a feature allowing the user to merge multiple pdfs together. For example: file1Path = foo1 file2Path = foo2 response[x-sendFile1] = unicode(file1Path).encode('utf-8') response[x-sendFile2] = unicode(file2Path).encode('utf-8') return response I'm new to django and I'm having trouble reconciling traditional methods for merging pdf (Django and weasyprint, merge pdf) with x-sendfile (https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/). Is there a way to merge concatinate multiple fileresponses/x-sendfile together in Django? -
How to iterate over inlineformset_factory fields only in HTML
I am trying to figure out how to access inlineformset_factory ,i set to represent my ForeignKey fields to present them in html i would like to iterate over those inlineformset_factory only in html, but i can't figure out how to achieve it, i can get display only field manually like {{form.task_description}} , but no luck to iterate over all ForeignKey fields , i would like to dispaly each object in collapse bs4 if someone could help me point to achieve it. Please advice Thanks my views.py related class goes as follows class TaskIdUpdateView(UpdateView): taskidformset = inlineformset_factory(MainTask,ChildTask, fields=('task_description','task_info','task_complete', 'sub_task','task_precent_complete','task_due_date','task_assign')) model = MainTask template_name = "taskid_update.html" form_class = TaskUpdateForm my formd.py related class class TaskUpdateForm(ModelForm): TASK_STATUS_CHOICES = [ ('ST', 'STARTED'), ('NS', 'NOT STARTED'), ('IP', 'IN PROGRESS'), ('PA', 'PAUSED'), ('CO', 'COMPLETED'), ] INPUTֹTIMEֹFORMATS = ['%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', '%Y/%m/%d', # '10/25/2006' '%Y/%m/%d %H:%M', '%m/%d/%y', '%Y-%m-%d %H:%M:%S'] # '10/25/06' #Main Task objects task_title = forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'})) global_task_info = forms.CharField(required=True, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'})) due_date = forms.DateTimeField(required=False, input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={ 'class': 'form-control', 'id': 'picker' })) global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} )) task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'})) complete = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={'type':'checkbox', 'class':'custom-control-input', 'id':'switchcomplete'})) overall_precent_complete = forms.IntegerField(widget=(forms.NumberInput(attrs={'type':'range', 'min':'0', 'max':'100', 'value':'50', 'class':'range-slider__range', 'id':'PreRange'}))) task_location = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) #Child Tasks objects … -
Problem with Django and accounts in my linux server
Im working in this django project with a partner in a server. When he is logged with his account and tries to execute python3 manage.py runserver 0.0.0.0:8000 this is what he gets: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/db/backends/postgresql/base.py", line 25, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/dist-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.7/dist-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", … -
django DRF custom permissions: view-level permissions for detail views
Im unsure about how to deal with permissions in detail views (such as api/teams/<int:pk>). Suppose I have a custom permission class in place that should allow access if the requesting user is in the queried team. something along the lines of: class IsInTeam(BasePermission): def has_permission(self, request, view): # should I implement this at all? def has_object_permission(self, request, view, team): return team.hasMember(request.user) Since has_object_permission is called anyway (because "stock" views check the permissions upon calling get_object according to the docs: Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call .check_object_permissions(request, obj). If you are using the generic views then this will be handled for you by default. Now, according to this, has_object_permission will only be checked if has_permission has returned True. While this makes sense, one could argue that since this view is strictly based upon CRUD operations on a specific object denoted by pk, all necessary checks could be performed within the has_permission method. The question is: Would this be bad practice? If so, why? The only reason I can come up with, is, that … -
how i can use DICOM files through Django app?
and here is forms.py . and i want to upload DICOM file not just ordinary file class Patient(models.Model): name = models.CharField(max_length = 200) DICOM_FILE = models.FileField(upload_to='basicapp/', default="") def get_absolute_url(self): return reverse("basicapp:Patient_Create") -
Django update or create existing row in database does not work
I am using Django 3.0.2, database SQLite. I create model weight: class Weight(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) weight = models.FloatField() My goal is to create row for every day. If I will write more time per day, only last_modified and weight will be updated depends on user_id and date. From command line, I can create new row, but cant update it. When I try this: Weight.objects.update_or_create(user_id=2, weight=123, date=date.today()) Weight.objects.update_or_create(user_id=2, weight=456, date=date.today()) It will create two row: 1 2020-02-01 16:22:57.275688 123 2 2020-02-01 2 2020-02-01 16:23:02.925780 456 2 2020-02-01 I would expect one row in the output: 1 2020-02-01 16:22:57.275688 456 2 2020-02-01 Can anybody help me to explain why it does not work? Maybe I am missing something but cant figure it out. -
Jonson response - Ajax, Django is not working properly
I know some Django but I am completely new in AJAX. I am looking for some way to use this in my project and I found this application djangoajax. According to the documentation, I try to use it in my project. I added applications in the settings file, created a view, and changed the urls file. views.py @ajax def my_view(request): c = 2 + 3 return {'result': c} urls.py path('ajax/response/', views.my_view, name='ajax_response'), templates.py <a class="btn" href="{% url 'testing:my_view' %}">Test my AJAX</a> After clicking the button, I receives more or less the following answer: But it has nothing to do with what I should receive: {"status": 200, "statusText": "OK", "content": {"result": 5}} Where am I making a mistake? Any help will be appreciated -
How to prevent direct URL access django
I wish to implement a blanket policy of disallowing all direct URL access within my django project. I have managed to implement an object-level url control using the built in def test func method , however i also wish to prevent those that have access to the object , from directly accessing the url to my forms which ammends / adds relations to this object. Therefore , i wish to know if it is possible to differentiate between requests that are redirected via hrefs , and those that are directly typed into the browser , and thus giving me the ability to block it from within my views. -
How to make static style-sheet working in django?
By running this code in normal html it runs with style also. But whenever I run it in django it does not run and just show me text. views.py def index(request): return render(request, 'index.html'); main url urlpatterns = [ path('', include('app1.urls')), path('admin/', admin.site.urls) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html <!-- Animate.css --> <link rel="stylesheet" href="{% static '../static/css/animate.css' %}"> <!-- Icomoon Icon Fonts--> <link rel="stylesheet" href="{% static '../static/css/icomoon.css' %}"> <!-- Simple Line Icons --> <link rel="stylesheet" href="{% static '../static/css/simple-line-icons.css' %}"> <section id="fh5co-home" data-section="home" style="background-image: url(../static/images/W1.png);" data-stellar-background-ratio="0.5"> <div class="gradient"></div> <div class="container"> <div class="text-wrap"> <div class="text-inner"> <div class="row"> <div class="col-md-8 col-md-offset-2 text-center"> <h1 class="to-animate">Welcome in the World of White Hats</h1> <h2 class="to-animate">Your Problem with auto Solution</h2> </div> </div> </div> </div> </div> </section> Folder structure