Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Upload any kind of file in django 2
I'm New in Django 2. I was trying to upload a file in Django here is my code View.py def addBook(request): checkName = AddBook.objects.filter(title=request.POST.get('title')) if not checkName: bookAdd = AddBook( title=request.POST.get('title'), slug=slugify(request.POST.get('title')), description=request.POST.get('description'), cover_image=request.FILES.get('title'), file=request.FILES.get('title'), category=request.POST.get('category'), created_by=request.user.id, ) bookAdd.save() messages.add_message(request, messages.INFO, 'Book Saved Successfully') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.add_message(request, messages.INFO, 'Book Title Already Exists') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) I can save everything but I need to save the file path and save the file locally. I read their documentation but cannot help me out. Please help me to solve this problem -
Django: how to add "set & save" method to models.Model?
How to write set method so I can call it like this: object.set(field1 = 0, field2 = 1) Here is my class: class model(models.Model): class Meta: proxy = True def set(self, **kwargs): # Insert your genius code here. self.save() -
Error installing mysqlclient using pycharm
I get an error when I try to connect MySql database using pycharm or even cmd I downloaded visual studio 2017 but the problem is still there and I tried with cmd all the possible wheels but it says 'this wheel is not supported in this platform' This is the error I get when I try to install mysqlclient using pycharm -
Unsure as to how to format url in fstring
I've got the following code: return f"<td class='eventyes'><a href='{% url 'accounts:daydetail' %}?{{ day }}'><span class='date'>{day}</span><ul><div class='singleevent'>{d}</div></ul></a></td>" I'm getting the following error: File "<fstring>", line 1 (% url 'accounts:daydetail' %) ^ SyntaxError: invalid syntax What syntax should I use to correctly format the name of the view within the anchor tag? Thanks! -
Authentication credentials were not provided. (error) in angular 6 while integrating rest api (django)..?
"Authentication credentials were not provided." i m getting this error in angular 6 while API integration from django. i m new to this so i don't know much about authentication but as per DRF tutorial i believe i have done everything write please review this code below.? *REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'google_auth.authentication.GoogleAuthAuthentication', 'rest_framework.authentication.BasicAuthentication', # enables simple command line authentication 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) }* ngOnInit() { } onSubmit(f){ console.log(f.value); const header = new HttpHeaders({'Content-Type': 'application/json'}); this.http.post('http://12.12.12.12/rest-auth/login/', f.value,{headers:header}).subscribe(( data ) => { console.log(data) this.a =data; console.log(this.a.key); localStorage.setItem('userToken',this.a.key); this.router.navigate(['../profile']); alert("You are login") } ,error => {console.log(error); this.non_field_errors=error.error.non_field_errors; this.password_error=error.error.password; }) } } -
How will I know when to increase the size of my RDS instance. Using Postgres with django
How will I know when to increase the size of my RDS instance (vertical scaling). Using Postgres with django. Suppose I choose t2 micro to start how will I know when to increase its size. I am using a django Application using PostgreSQL and Amazon t2micro instance -
How do you implement content-disposition as an attachment for django_weasyprint package?
Using the django_weasyprint (class-based view implementation) package to generate a pdf. I'm able to generate a pdf in the browser but have trouble setting up a open/save-as dialog box pop-up feature. I know I have to set content-disposition equal to attachment (I think) but I'm struggling doing so. from django.conf import settings from django.views.generic import DetailView from django_weasyprint import WeasyTemplateResponseMixin class ArticleView(DetailView): # vanilla Django DetailView model = Article template_name = 'article_detail.html' class ArticlePrintView(WeasyTemplateResponseMixin, ArticleView): # output of DetailView rendered as PDF pdf_stylesheets = [ settings.STATIC_ROOT + 'css/app.css', ] I've tried to used this snippet (found on stackoverflow) as well but I'm slightly confused about the first argument, '/path/to/test.pdf', of the write_pdf method. Does that mean I need an actual pdf included in the application as opposed to it being generated from the article_detail.html. from weasyprint import HTML class PdfView(DetailView): model = TheModel template_name = 'pdf.html' def get(self, request, *args, **kwargs): template_response = super().get(self, request, *args, **kwargs) HTML(string=template_response.rendered_content).write_pdf( '/path/to/test.pdf', stylesheets=['/path/to/pdf.css'] ) return template_response I'd like to have the open/save-as dialog box to pop-up automatically. Any ideas on the easiest solution? -
Http request to Django hosted on LAN timed out
I want to host my Django rest-api on my local server so visitors to my hosted website can make calls to it. It works perfectly on localhost:8000. What I did was: I changed ALLOWED_HOSTS in my settings.py file to all ['*'] python3 manage.py runserver 0:8000 But now when I try to make a call to or visit http://171.66.208.134:8000/ I get: (quizkly_env) DN0a22641a:web shiningsunnyday$ http --json POST http://171.66.208.134:8000/quizkly/ content="Barack Obama was the 44th president of the United States." http: error: Request timed out (30s). (quizkly_env) DN0a22641a:web shiningsunnyday$ I also tried python3 manage.py runserver 171.66.208.134:8080 but got: System check identified no issues (0 silenced). January 25, 2019 - 03:28:56 Django version 2.1.5, using settings 'quizkly.settings' Starting development server at http://171.66.208.134:8080/ Quit the server with CONTROL-C. Error: That IP address can't be assigned to. What's going wrong? -
for free Django VC deployment on AWS, which is best? just EC2.t2 or Beanstalk
I want to make sure that my instance shuts down whenever the free tier is surpassed, so a literally free site. For starters, all I could see are alerts, but nothing such as the instance shutting down unless you make some kind of hack that the alert starts a process that shuts down the EC2 which is a bit of a mess. The deployments on EC2 I have seen are SSH, not VC. Beanstalk also starts EC2 instances as process is needed which can also spike costs a lot and I am only wanting a free hosted test. Since Beanstalk is linked to whichever EC2 I suppose you can still link it to a free EC2.t2? Please avoid recommending other hosting services as AWS is a must for this task. -
Attribute error: 'str' object has no attribute 'read' python-django
So the scenario here is, I have a endpoint that will take a zipfile, unzip it and save it to media dir for now. Here's the whole code for that def get_filenames(path_for_zip): with ZipFile(path_for_zip, 'r') as zip: return zip.namelist() class Upload(View): def post(self, request): context = {} upload_file = request.FILES['document'] unzip_file = get_filenames(upload_file) for files in unzip_file: print(files) fs = FileSystemStorage() fs.save('read.jpg', files) return render (request, 'toDo_app.html', context) I am using FileSystemStorage as you can see. ZipFile is unzipping properly and i can see it in print(files) but the issue is at FileSystemStorage I guess, Its not getting saved and I get the attribute error 'str' object has no attribute 'read'. Please point me out what did I do wrong and how should it be solved. Thank you. -
Django sitemaps 'Post' object has no attribute 'get_absolute_url'?
I'm creating a simple django 1.9 app that includes a blog and i want the site to have sitemaps consisting of the website pages and blog post entries.So far i am able to build a sitemap that generates the static pages as sitemaps but the blog post sitemap give me an error 'Post' object has no attribute 'get_absolute_url here is my code.Somebody please tell me where i'm going wrong. sitemaps.py from django.contrib import sitemaps from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse from administration.models import Post class StaticSitemap(sitemaps.Sitemap): changefreq = "daily" priority = 1.0 def items(self): return ['administration:index', 'administration:about'] def location(self, item): return reverse(item) class PostSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Post.objects.all()` models.py class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),) featured_image = models.ImageField(upload_to="Photos/posts/images", blank=True, null=True) post_short_description = models.TextField(default="No description available") title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') category = models.ForeignKey(Category) tag = models.ManyToManyField(Tag) author = models.ForeignKey(User,related_name='blog_posts',on_delete=models.CASCADE) body = RichTextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title urls.py from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.sitemaps.views import sitemap from administration.sitemaps import … -
Unable to hash password in Django Backend
If a user signs up on the frontend, the password is hashed just fine but when i try to create a password from Django's backend, the password is saved as plain text. admin.py def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user forms.py class RegisterForm(forms.ModelForm): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ('email',) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean_password2(self): # Check that the two password entries match password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password and password2 and password != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data['password']) # user.is_applicant = True user.is_active = True if commit: user.save() return user Please for some assistance. -
messages API twitter Challenge-Response Checks
I've seen that twitter changed their endpoints to get and send direct messages, I noticed from a reply from here that it is a workaround to be able to send messages with well-known libraries such as tweepy, but all I need in this case is to list the messages in my inbox. I've noticed that there is an account activity api which I can use to achieve this goal. But, I do not understand how to implement Challenge-Response Checks, can you provide an example? how twitter checks this? it is through a post request to my site? to what specific URI they do this? I tried sending a pipedream url as webhook (to see what kind of request they were doing, but absolutely no request was shown) -
How to use slicing on queryset for django form?
Let's say I have a django Model Player. Player model has a filed name 'points' a integer field. I need to show top 10 players ordered by points in from.ModelChoiceField. The queryset would be Player.objects.all().order_by('-poinst')[:10] But if I use slicing on queryset which would be set into form field, it raises error when submit button is clicked. Cannot filter a query once a slice has been taken. Any way to solve this? -
displaying data in django template using detail view
i'm having a problem displaying data on DetailView Template , basically wanna display all the data of one project areas and tasks my models looks like that ##models class Project(models.Model): name = models.CharField(max_length=100) ... class Area(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project ,on_delete=models.CASCADE, related_name='areas' ) class Task(models.Model): .... area = models.ForeignKey(Area ,on_delete=models.CASCADE, related_name='tasks' ) #view class ProjectDetailView(DetailView): model = Project template_name = 'project-detail.html' i can display project and areas using the reverse relationship but i'm unable to display tasks on every area . -
django ajax form submit to view without refreshing page
To implement a non-refreshing effect, I decide to use $.post() However, I need to send csrf token also, as a result, I cannot send only input contents of my form. Here's my code at .js, but the JSON.stringify($(this)) gives me things I don't want at the views.py back-end. .js $('#my-form').submit(function(e){ e.preventDefault(); url=$(this).attr('action'); data=JSON.stringify($(this)) $.post(url,{'data':data,'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()},function(data_returned){ alert('submit done'); }); }); at my views.py print("data:"+json.loads(str(request.POST['data']))) which gives me something like these: {"0":{"0":{},"1":{},"2":{"0":{},"1":{},"2":{}},"3":{},"4":{},"5":{},"6":{},"7":{},"8":{},"9":{},"10":{},"jQuery112402971640175601502":28},"context":{"0":{},"1":{},"2":{"0":{},"1":{},"2":{}},"3":{},"4":{},"5":{},"6":{},"7":{},"8":{},"9":{}," 10":{},"jQuery112402971640175601502":28},"length":1} Any suggestion? Thanks! -
Django Template Tagging inserting a single value from a ListView
So I am undertaking a website project and I am having some issues with one page. I essentially load NBA teams wins and losses onto a page and make my own makeshift standings ladder. The data loaded from my model is as follows: MODEL.PY from django.db import models from django.utils import timezone # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=500, unique=True, primary_key=True) wins = models.PositiveIntegerField() losses = models.PositiveIntegerField() created_date = models.DateTimeField(default=timezone.now) I use the ListView in my views.py file as follows: VIEWS.PY class LadderListView(LoginRequiredMixin, ListView): #this defaults to looking for the models name html so in this case team_list.html # so i changed it to template_name variable template_name = 'merchbet/ladder_list.html' model = models.Team and render the urls.py file as follows: path('ladder/', views.LadderListView.as_view(), name='ladder_list'), all of this successfully works. When I get to my html code I am able to the teams, and their win/loss records to print to the website with template tagging, but I am looking to inject one line at the bottom which shows the "Last Updated: {{ team.created_date }}. This is not working and I am not getting an errors, the "{{ team.created_date }}" just shows nothing on the url page. I have looked through … -
How do I remove a Posgresql image from a Docker container and install a new one
I'm new to docker and loveing it for the most part. The one thing I DON'T love is replacing a DB. I have a Vue/Django app that I borked the database on. I need to re run the migrations. It's a special case where I need to rebuild the DB for a user account. Regardless, I can't seem to do it. I've followed the instructions here (https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BDocker%5D-Remove-all-Docker-volumes-to-delete-the-database) and it looks like it works in that it lists what is removed. But then it doesn't seem to actually remove it. What I want to do is just switch to a new database in the container for Postgresql. Any suggestions? -
How to send extra parameters to the serializer, not included in the model?
I need to send parameters to the serializer that do not exist in the model, so the serializer delete this data I also have a nested serializer with a custom ".create()" function request data = {'data': [{'usuario': 269, 'coworkers': [328, 209], 'inicio': '2019-01-24T23:30:43.926Z', 'estado': 'progress', 'operacion': {'orden': 24068, 'proceso': 'ALEZADO FINAL-TORNO CNC T7 1'}}, {'usuario': 269, 'coworkers': [208, 212], 'inicio': '2019-01-24T23:30:43.926Z', 'estado': 'progress', 'operacion': {'orden': 24067, 'proceso': 'ALEZADO FINAL-TORNO CNC T7 1'}}]} Model: class TiempoOperacion(models.Model): inicio = models.DateTimeField(blank=True, null=True) fin = models.DateTimeField(blank=True, null=True) operacion = models.ForeignKey(Operacion, related_name='tiempos', on_delete=models.CASCADE) cantidad = models.IntegerField(default=0) usuario = models.CharField(max_length=40) motivo_pausa = models.CharField(max_length=140, default=None, null=True) estado = models.CharField( max_length=15, choices=TASKS_STATUS_CHOICES, default=UNACTION, ) Viewset: def create(self, request): datos = request.data.get('listorders') if 'listorders' in request.data else request.data tiemposerializer = TiempoOperacionSerializer(data=datos, many=True, fields=('coworkers', 'operacion')) if tiemposerializer.is_valid(): tiemposerializer.save() return Response(tiemposerializer.data) else: return Response(tiemposerializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer: def create(self, validate_data): operacion_data = validate_data.pop('operacion') print (f"\n\n validate_data : {validate_data} \n\n") if not operacion_data: raise ValidationError({ 'operacion': 'This field object is required.' }) coworkers = validate_data.get('coworkers') query_operaciones = Operacion.objects.filter(**operacion_data)[:1] if query_operaciones.count() > 0: operacion = query_operaciones[0] else: operacion = Operacion.objects.create(**operacion_data) tiempo_obj = validate_data tiempo = TiempoOperacion.objects.create(operacion=operacion, **tiempo_obj) if coworkers: tiempos_list = [] for coworker in coworkers: tiempo_obj.update({'usuario': coworker}) tiempos_list.append(TiempoOperacion(operacion=operacion, **tiempo_obj)) tiempos = TiempoOperacion.objects.bulk_create(tiempos_list) return … -
ISO 8601 string instead of datetime
I have faced this problem in other projects, but right now we're working in Django / Python with Vue.js and PostgreSQL. Nearly every 'date' field in our model is truly a date, not a datetime. The business users don't care about a time-part, in fact storing any such value is misleading. A good example is the effective date on a tax rate. From the user point of view, it takes effect at midnight on the specified date. If we store this as a Django DateTimeField or DateField, it requires a time-part. It could be 0000h, but the value has no meaning to the business, because they will never need to see or compare anything with the time-part. The Django functionality is great if we want to store a real datetime, put it into the database as UTC, and then display it to users in their local time through the automatic time zone conversion. But we don't. If the effective date is March 1, 2019, it should display as such regardless of the user's timezone. If the date is stored as a datetime (2019, 3, 1, 0, 0, 0) and entered by someone in Vancouver, it will appear as the next … -
How to store results from many TestCases (to one file) in django (unittest)?
I have several test cases which all have a similar tearDown: def tearDown(self): execution_time = time.time() - self.startTime result_list = [self._testMethodName] result = [str(x) for x in sys.exc_info()] if result[0] == 'None': result_list.append('PASS') elif 'Assertion' in result[0]: result_list.append('FAIL') else: result_list.append('ERROR') result_list.append(result) result_list.append(str(execution_time)) TEST_RESULTS.append(result_list) I'm using the tearDown function to store results from each test (in the test case) to a global TEST_RESULTS object (so each TestCase file has a TEST_RESULTS global defined). Then in the tearDownClass function im doing this to store results to csv: @classmethod def tearDownClass(cls): with open ('tests/results/test_case_1_output.csv', 'wr') as resultFile: wr = csv.writer(resultFile) wr.writerows(TEST_RESULTS) To me this is a terrible implementation. Globals defined everywhere and tearDown/tearDownClass implemented over and over again in each test case rather than defined once. Furthermore, I would like to create a test result file which collects results from all test cases. My hunch is this requires defining the file handle at the runner level (or somewhere before the TestCases are being called). This would allow me to reinitialize the csv file at a higher level (rather than arbitrarily in one TestCase). Does anyone have a suggestion on how this can be accomplished? Did not see a way to do this from … -
How to automatically connect to Cloud SQL via the proxy?
I have mySQL database set in settings.py like this: if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/myApp:europe-west1:myApp-instance', 'NAME': 'myApp', 'USER': 'myApp', 'PASSWORD': 'myApp', }} else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: # # $ ./cloud_sql_proxy -instances="myApp:europe-west1:myApp-instance"=tcp:3306 # # See https://cloud.google.com/sql/docs/mysql-connect-proxy DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'myApp', 'USER': 'myApp', 'PASSWORD': 'myApp', }} When I want to run myApp locally I must run first on terminal this command: ./cloud_sql_proxy -instances="myApp:europe-west1:myApp-instance"=tcp:3306 and it's very annoying... there is a way to integrate it inside my code? For example I would put something in my setting that automatically run the command, immediately after the 'else:' But I don't know what I have to write... any idea? Is it possible? -
Tunneling/SSH On digital ocean to improve development process
I don't really know how to phrase my question. I am student developer and working with a non-profit group on my campus. Objective: try to make the development process smoother. Technologies Used: Django, Docker, Front-end techs, other techs Description: I will try to make it as abstract as possible. The software we have has web interface and a mobile app. It has the ability to communicate to the mobile app and prompt: "accept or decline". And it works fine when I host it up on Digital Ocean. Problem: While developing, you can't really test out the communication cuz i am developing on localhost (question 1: how to achieve this on a test server? and for multiple people developing it?). Second is I have to start docker every time I want to develop + push to github + go into docker bash... (question 2: is there a way to automate this? sorta like how you would be able to do react development in real-time?) Sorry if this is a noob question. But any pointers? Anything I can google would be of help. Thanks in advance. -
How to fix "more than one foreign key" Django
I am new to Django (using version: 2.1.5)(Python 3.6) and trying to mess around with some models. I am building a chess database. This relies on 3 models, the players, the game and the moves comprising the game. For each game there is a white player and a black player, both of the class player. This raises an error: : (admin.E202) 'chessengine.Game' has more than one ForeignKey to 'chessengine.Player'. I tried using reference names which removed an earlier related error but will not deal with the one above. //models.py class Player(models.Model): name = models.CharField(max_length=200) birth_date = models.DateField('birthday') def game_count(self): return Player.objects.filter(Games__white_player=self.name).count() + Player.objects.filter(Games__black_player=self.name).count() class Game(models.Model): number = models.IntegerField() date = models.DateField('date played') moves = models.IntegerField() white_player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='white_player') black_player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='black_player') result = models.CharField(max_length=8) //admin.py class GameInline(admin.TabularInline): inlines = [MoveInline] model = Game class PlayerAdmin(admin.ModelAdmin): fieldsets = [ ('Player Information', {'fields': ['name', 'birth_date']}), ('Game Information', {'fields': ['date', 'player_white', 'player_black', 'result'], 'classes': ['collapse']}), ] inlines = [GameInline] list_display = ('name', 'birth_date', 'game_count') list_filter = ['name'] -
OneToOneField attribute is linking ID instead of CharField
I have these two models linked by OneToOneField "Father" class: from django.db import models class EmpresaManager(models.Manager): def create_empresa(self): empresa = self.create() return empresa class Empresa(models.Model): codigo = models.CharField(max_length=3, null=False, default='000') nombre = models.CharField(max_length=100, null=False, default='Sin nombre') email = models.EmailField(null=False, default='email@empresa.com') direccion = models.CharField(max_length=100, null=False, default='Sin direccion') localidad = models.CharField(max_length=100, null=False, default='Sin localidad') codDgi = models.SmallIntegerField(null=True) docDgi = models.CharField(max_length=13, null=True) sIva = models.CharField(max_length=1, null=True, default='1') mesCierre = models.IntegerField(null=True, default=0) fecIni = models.DateField(null=True) ruca = models.IntegerField(null=True) novedad = models.CharField(max_length=50, null=True, default='') fecNovedad = models.DateTimeField(null=True) ultVersion = models.CharField(max_length=20, null=True, default='') logo = models.ImageField(null=True) habilitado = models.CharField(max_length=1, null=True, default='S') codEmpresa = models.CharField(max_length=3, null=True) codComp = models.CharField(max_length=3, null=True, default='') def __str__(self): return "%s" % self.nombre objects = EmpresaManager() And the other class: from django.db import models from Empresa.models import Empresa class UsuarioManager(models.Manager): def create_usuario(self): usuario = self.create() return usuario class Usuario(models.Model): empresa = models.OneToOneField( Empresa, on_delete=models.CASCADE, primary_key=False, ) codigo = models.CharField(max_length=10, null=False, default='Sin cod') nombre = models.CharField(max_length=50, null=True) puesto = models.CharField(max_length=50, null=True) password = models.CharField(max_length=100, null=True) rol = models.CharField(max_length=15, null=True, default='') habilitado = models.CharField(max_length=1, null=True, default='S') def __str__(self): return self.nombre objects = UsuarioManager() The problem: I'm trying Usuario.empresa to inherit the value from Empresa.nombre (which is a CharField, for example 'McDonalds'), but it is inheriting …