Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template does not exist (Django)
I get the following message with Django. I use the instructions of Django with visual studio code tutorial of Microsoft. I don't know how to solve this enter image description here -
Which is more efficient (Django models)
initially, i have 3 games (lol, dota2, hearthstone) and game count can increase lol has team vs team based match dota 2 has team vs team based match hearthstone have player vs player based match I am modelling the database to keep match histories of these games. Which one is more efficient. If none of them are not efficiently, what should you suggest in addition, Database have the tournament and league tables class Game1(models.Model): type_tvt = 1 type_pvp = 2 type_royale=3 types = ( (type_tvt, 'Takım vs Takım Klasik'), (type_pvp, 'Player vs Player Klasik'), (type_royale,'Battle Royale Takımlar vs Takımlar'), ) gametype=models.SmallIntegerField(choices=types,verbose_name="Oyun Tipi") name=models.CharField(max_length=255,blank=True,null=True) slug = models.SlugField(unique=True, max_length=255) player1=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p1',null=True,blank=True) team1=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t1',null=True,blank=True) team1player = models.ManyToManyField(Player,blank=True,related_name='mp1') score1 = models.PositiveSmallIntegerField(null=True, blank=True) player2=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p2',null=True,blank=True) team2=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t2',null=True,blank=True) team2player=models.ManyToManyField(Player,blank=True,related_name='mp2') score2 = models.PositiveSmallIntegerField(null=True, blank=True) game=models.ForeignKey(OnlineGame,on_delete=models.CASCADE,null=True,blank=True,related_name="matchgame",verbose_name="Oyun") ... OR (GameTvT and GamePvP) class Game2(models.Model): name=models.CharField(max_length=255,blank=True,null=True) slug = models.SlugField(unique=True, max_length=255) score1 = models.PositiveSmallIntegerField(null=True, blank=True) score2 = models.PositiveSmallIntegerField(null=True, blank=True) game=models.ForeignKey(OnlineGame,on_delete=models.CASCADE,null=True,blank=True,related_name="matchgame",verbose_name="Oyun")... class Meta: abstract = True class GameTvT(Game2): team1=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t1',null=True,blank=True) team1player = models.ManyToManyField(Player,blank=True,related_name='mp1') team2=models.ForeignKey(Team,on_delete=models.CASCADE,related_name='t2',null=True,blank=True) team2player=models.ManyToManyField(Player,blank=True,related_name='mp2')... class GamePvP(Game2): player1=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p2',null=True,blank=True) player2=models.ForeignKey(Player,on_delete=models.CASCADE,related_name='p2',null=True,blank=True)... OR class lol(models.Model): .... class dota2(models.Model): .... class heartstone(models.Model): .... -
Adding forms dynamically to a Django formset
i cannot able to understand how create_book_normal() works in this code. def create_book_normal(request): template_name = 'store/create_normal.html' heading_message = 'Formset Demo' if request.method == 'GET': formset = BookFormset(request.GET or None) elif request.method == 'POST': formset = BookFormset(request.POST) if formset.is_valid(): for form in formset: name = form.cleaned_data.get('name') myuser = form.cleaned_data.get('myuser') # save book instance if name: Book(name=name,myuser=myuser).save() please explain me how this redirect works. #store:book_list return redirect('store:book_list') return render(request, template_name, { 'formset': formset, 'heading': heading_message, }) how values are getting stored in the store:book_list? if i change book to Book then it shows eror like this - NoReverseMatch at /store/book/create_normal -
How to filter django queryset with date and time?
This is my model field start = models.DateTimeField(null=True,blank=True) Let's say I have value, cmp_date = '2019-09-05 20:09:00' event_exists = Event.objects.filter(start__gte=cmp_date, end__lte=cmp_date).first() And in my database I have start as "2019-09-05 18:09:00.000000" and end as "2019-09-06 19:09:00.000000" But this returns none.. I guess the problem is with the time? May I know how to filter with date and time? -
Calling multiple functions after clicking Submit button
I am new to Django and python, I have various functions made in python which i want to run after clicking the submit button (obviously getting inputs from the form) and then show the results on similar page or maybe new page. A proper guidance and a pseudo code would help me achieve this. Thank you. -
Running Django's createsuperuser in Google Cloud Run
I'm trying to run a Django app on Google Cloud Run. The site itself works nicely, can run migrations and collect static assets via a startup script. The one thing I cannot figure out how to do is create a superuser. This requires interactively typing in a password or at least setting it via a django shell. I currently cannot figure out how to do this and it seems like it might not be possible; which would make Cloud Run unusable for Django. Has anyone been able to achieve this or have a sustainable workaround? Thanks! -
IPython/django execute history in order
I am running django shell using IPython 5.8.0. In older versions of IPython, in order to run previous commands that had been typed, I hit the up arrow X number of times, then executed the command, then hit the down arrow and it went to the next command in order so I could quickly execute a whole series of commands in order again. Now, when I up arrow X times and execute a command, it then jumps me back down to the end of the history list and nothing happens when I hit the down arrow. Is there an IPython setting somewhere to change this behavior? And, if so, how do I set that? Everything was working normally until I upgraded IPython. -
Compose up container exited with code 0 and logs it with empty
I need to containerize a Django Web project with docker. I divided the project into dashboard, api-server and database. When I type docker-compose up, it print api-server exited with code 0 and api-server container Exited (0), and I type docker logs api-server, it return empty, but other container normal. I don't know how to check problem. api-server directory structure is as follows api-server server/ Dockerfile requirements.txt start.sh ... ... Some compose yml content is as follows dashboard: image: nginx:latest container_name: nginx-dashboard volumes: - /nginx/nginx/default:/etc/nginx/conf.d/default.conf:ro - /nginx/dist:/var/www/html:ro ports: - "80:80" depends_on: - api-server api-server: build: /api-server container_name: api-server volumes: - /api-server:/webapps ports: - "8000:8000" depends_on: - db db: image: postgres container_name: Postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - "5432:5432" Some Dockerfile content of api-server is as follows FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /webapps WORKDIR /webapps RUN apt-get clean && apt-get update && apt-get upgrade -y && apt-get install -y python3-pip libpq-dev apt-utils COPY ./requirements.txt /webapps/ RUN pip3 install -r /webapps/requirements.txt COPY . /webapps/ CMD ["bash","-c","./start.sh"] start.sh is as follows #!/usr/bin/env bash cd server/ python manage.py runserver 0.0.0.0:8000 type docker-compose up result as follows root@VM:/home/test/Documents/ComposeTest# docker-compose up Creating network "composetest_default" with the default driver Creating Postgres ... … -
Is there any way to determine attribute is select/choice in django model?
Currently implementing searchbox which provides two interface - textbox if required input is not normalized, and dropdown if required input is normalized and is defined with choices param in model, and select class in form.I've currently found that I can retrieve each fields' html snippet by doing str(field), for field in form, and with beautifulsoup or other html parsing library I can find input type(is text field or dropdown(select)), and option values for dropdown. But it seems too compilcated, and I'm currently guessing that there might be some way django provides to determine such things.Looking forward, and thanks in advance for any help. -
How to join 3 models of existing database tables with specific column key?
I'm developing a web app using Django REST as the backend, and Angular as the frontend. I have a legacy database (read-only) that has 3 tables that I want to join together to get all the data I need. Basically, I'm using the result of this query to auto-populate a form. The user will enter a known meter number into the form and then click a button that will pull the other related information into the form - minimizing data entry. Simplified database tables and fields MeterNumber bi_acct bi_srv_loc_nbr bi_mtr_nbr Customer bi_acct (join to MeterNumber table) other fields I need ServiceLocation bi_srv_loc_nbr (join to MeterNumber table) other fields I need So, as you can see, these tables can all join to the MeterNumber table based on the bi_acct and bi_srv_loc_nbr fields. I want to be able to make a REST call to something like: server/meter_number/123456 And then the JSON response would be something like: { "bi_acct": 111111, "bi_srv_loc_nbr": 222222, "bi_mtr_nbr": 123456, "customer": [ { "bi_acct": 111111, "needed_field": "... " } ], "service_location": [ { "bi_srv_loc_nbr": 222222, "needed_field": "..." } ] } And this response would be used to auto-populate the form. But how do I create these joins and have … -
How I can queryset all checkboxed objects after filtered in admin change list?
I have actions add_mail_group I trying to add all selected objects in admin change list from UserProfile models into Group models subscribers field But after uenter image description herese filter (list_filter) or selected all objects, or more than 100, thats added null objects. Can somebody help me, please? class UserProfile(models.Model): first_name = models.CharField(verbose_name='Name', max_length=32) email = models.EmailField(verbose_name='E-mail', unique=True) class Group(models.Model): title = models.CharField(verbose_name=' Name', max_length=128) subscribers = models.ManyToManyField(verbose_name='Users', to=UserProfile) def add_mail_group(self, request, queryset): from mailing.models import Group import datetime now = datetime.datetime.now() today = datetime.date.today() title = 'Group from date ' + now.strftime("%d-%m-%Y") mail_group = Group(title=title) mail_group.save() mail_group.subscribers.set(queryset) messages.add_message(request, messages.INFO, f'Group was added ') return HttpResponseRedirect("../") add_mail_group.short_description = 'Create email group' -
How to return Posts author ID and username instead of just ID in DjangoREST
When I make a GET request to my /api/posts/ I recieve only author ID, but I also want author username to display it. How would I do that? I want response to be something like this: [ { // all other stuff author: { id: 1, username: "foo" } } ] This is my Post viewset: class PostViewSet(viewsets.ModelViewSet): """Handle CRUD for Posts""" serializer_class = serializers.PostSerializer authentication_classes = (TokenAuthentication,) queryset = Post.objects.all() def perform_create(self, serializer): """Set author to current user""" serializer.save(user=self.request.user) And this is what I get in response: [ { "id": 1, "title": "Welcome!", "description": "Welcome test!", "created_at": "2019-09-21T01:05:58.170330Z", "author": 1, "community": 2 } ] I want to do the same for community as well but I think I'll figure it out from the author solution. -
How to manage Java and Python apps on docker?
I have a Python app based on Django that I run over a docker container. The app browses the file system and does analysis on some XML files and extracts embedded source code and exports that into separate files. The app should run a Java jar file that does static code analysis on files generated by the Django web app. I thought of isolating both parts of the whole platform. The Python Django part is on a container, the jar file (it's an open source tool) runs on another alpine container. Now I want to continue development of the tool and make the Django app run the tool through a command on each file that's generated that contains source code. Should I create another Django wrapper on the jar file to expose some endpoints so that the first container could run it? Is there another way I could enhance this architecture? Edit: The tool I'm using: https://github.com/AbletonDevTools/groovylint -
I'm trying to implement stripe payments on django but I am getting this error
Below is the error thrown. Immediately I try to submit payments by pressing the button I get the error attributed error at //charge. AttributeError at /charge/ module 'stripe' has no attribute 'Charge' Request Method: POST Django Version: 2.2.4 Exception Type: AttributeError Exception Value: module 'stripe' has no attribute 'Charge' This is my function code: if request.method == 'POST': charge = stripe.Charge.create( amount = 500, currency = 'usd', description = 'A django charge', source = request.POST['stripeToken'] ) return render(request, 'charge.html') -
Setting a condition based redirect in a class based view (Django)
I'm (beginner) creating a simple blog app. I created a class based view to create a blog post and it has a separate URL. I want it redirect to the login page (url name = 'login') if the user isn't logged in. In a function based view all I have to do is this: def postCreateView(request): if not request.user.is_authenticated: return redirect('login') I don't know how to do this in a class based view (inherited from generic CreateView). I tried modifying the init() method like this: def redirectLogin(self): return redirect('login') def __init__(self, *args, **kwargs): if(not self.request.user.is_authenticated): redirectLogin() super().__init__() (I named the class PostCreateView) But on debugging the Exception Value was 'PostCreateView' object has no attribute 'request'. I need the correct way (The Django convention way if it exists) to set a condition based redirect in class based view. Also I'm confused why it says the view doesn't have an attribute 'request'. Every view has request. I'm sure about it because I overrode the form_valid() method to set the author of the post as the currently logged in user like this: def form_valid(self, form): form.instance.author = self.request.user return super().form_valid() And it run perfectly fine when I logged in and created a post. … -
Django model field default value same as PK
I have a django model with id as PK and another field called sub_user which I want by default to have the same value as the ID.How can I do that? sub_user = models.IntegerField(default= ? ) -
Django TypeError at /servicesurvey/8:pk
This error occurs when I try to call another page to edit the information about the main service page. TypeError at /servicesurvey/8:pk edit_survey() got an unexpected keyword argument 'int' Request Method: GET Request URL: http://localhost:8080/servicesurvey/8:pk Django Version: 2.0 Exception Type: TypeError Exception Value: edit_survey() got an unexpected keyword argument 'int' home page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- /Css --> <link rel = "stylesheet" type = "text/css" href = "../static/survey.css" /> <!-- /Css --> <title>Delta</title> <!-- /Fonts --> <link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet'> <link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900" rel="stylesheet"> <!-- /Fonts --> </head> <body> <div> <div class="absolute"> <h1 id="home_name">Delta</h1> </div> <div id="Delta" class="logoPrincipal"> <img src="../static/logo.png" alt="Delta"> </div> <div> <ul class="nav"> <li> <a href="{% url 'qrcode' %}"> <img src="../static/images.png" alt="Leia o QR Code com seu celular"> </a> </li> <li> <a href="{% url 'servicesurvey' %}"> <img src="../static/form.png" alt="Leia o QR Code com seu celular"> </a> </li> </ul> </div> <div> <section> <p>teste123...</p> </section> </div> <div> <section> <p>teste123...</p> </section> </div> </div> </body> </html> edit page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>Editar Pesquisa</h1> <form class="formSurvey" action="{% url 'edit_survey' survey.id %}" method="post"> {% csrf_token %} {{ surveyform }} <div class="row"> … -
Is it possible to extends only some part of the templates in django?
I have a blog app and in my about page I want to only extends navigation bar i don't want to extend sidebar which is present in my base templates. Is is possible to do, please explain. Because in my about page, I only want a images and some text with the navigation bar. -
Djano-viewsets. How to get the ID parameter from the path in perform_create fun
I'm trying to do a REST in Django using the VIEWSETS library. I created a Container model that works well. Container is associated with the ContainerModerator model. The endpoint should be: POST containers/{container_id}/moderators One of the fields in ContainerModerator is container_id. I would like to get it from the path. Below is what I have now. I tried in different ways to get there. I also read similar posts, usually for a library other than VIEWSETS. I am a beginner and I wonder if there is a simple, elegant solution for this case that will be easy for me to understand? Should I use other libraries like APIVIEW or GenericAPIView? models: class ContainerModerator(models.Model): moderator_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) container_id = models.ForeignKey(Container, on_delete=models.CASCADE) serializers: class ContainerModeratorSerializer(serializers.ModelSerializer): class Meta: model = models.ContainerModerator fields = '__all__' views: class ContainerModeratorViewSet(viewsets.ModelViewSet): serializer_class = serializers.ContainerModeratorSerializer queryset = models.ContainerModerator.objects.all() def perform_create(self, serializer): serializer.save() urls: router.register('v1/containers/<int:container_id>/moderators', views.ContainerModeratorViewSet) urlpatterns = [ path('', include(router.urls)) ] -
How to change Site model object in django data migration?
What I want to do is that I want to change Site display name and domain from example.com to mydomain.com . Normally, I can enter into the django admin and do this. But I want to use data migration. My code is as below: from django.db import migrations def change_site_name_from_example_to_mydomain_func(apps, schema_editor): Site = apps.get_model('sites', 'Site') site = Site.objects.get(name='example.com') site.name = 'mydomain.com' site.domain = 'mydomain.com' site.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_populate_database_createsuperuser'), ] operations = [ migrations.RunPython(change_site_name_from_example_to_mydomain_func), ] However, I get an error saying that there is no such app as sites. Te question is, how can I use Site model in a data migration? -
how to serve content of text file as raw text in Django
I am trying to serve raw text from a text file in my static directory using Django. I am able to view this text, but it is not formatted the same as the text file. It is ignoring the /n. My text file (test.txt) is formatted like this: #testscript print("hello world") another line In my view: class testUpdate(LoginRequiredMixin,TemplateView): template_name = 'testUpdate.html' login_url = 'login' def get(self, *args, **kwargs): f = open('static/updates/test.txt', 'r') file_content = f.read() f.close() return HttpResponse(file_content, content_type="text/plain") Which outputs in the browser: #testscript print("hello world") another line I have also tried .readlines() instead of .read() and this still ignores the /n -
How can a view call a function (which is not a view) in django?
Is it possible to create a view/function in django that is callable only another function I.e. the function doesn't accept get/post request. -
Online File Management
I am creating a django based website in which user can create folders and store some text (specifically urls and their 1 line description) in a hierarchical folder way .The site will contain a login option after that user can create folders and inside them subfolders and inside the sub folders, the user can store url and their description. I need help in set up of database so that whenever a user logins and click on a particular folder he/she can view his/her folders and their content and create new sub folders and delete them. I am trying to use postgresql, i am all okay with the front end but the main thing in which i need help is how to create database for each folders and how to load them in my website. PS: I am trying to keep a constraint that if a user has created folder 'A' he/she can store text but if a sub folder 'B' is created the user cannot store links in 'A'(parent folder) the links needs to be stored in the sub folders and notify to move the previously stored links to a sub folder. Same goes for the sub folders. Example now … -
How to give user a option to choose Login or Signup in python using django framework?
Hello I am creating a web app and I want to give usera option to login or signup using django . But the code was not giving the output I want . If Signin is choosen , the user will be redirected to his feed . If Signup is chosen , he need to create a new account using his email . I just Used This Code : import django import datetime def getdate(m,d,y): m=int(input("Enter Month :")) d=int(input("Enter Date :")) y=int(input("Enter Year :")) date1=datetime.date(m,d,y) return date1 print("WELCOME TO MOVIE REVIEW") asksgn=print("I Want To Sign In ") asksgnup=print("I Need To Create A Account ") sgn=input(asksgn) sgnup=input(asksgnup) if sgnup==True: class usrprofile: usrname,__pwd,dob,nick=0 def profile (self,usrname,__pwd,dob,nick): self.usrname=input("Enter Your Name :") self.__pwd=input("Enter Your Password :") self.dob=getdate() self.nick=input("Enter Your Nickname :") def __init__(self): print("Welcome To Movie Review Office") def __del__(): print("Bye Bye") -
Limiting access to objects in Django
I have a particular model and that model has finegrained access settings. Something like: class Document(models.Model): ... access = models.ManyToManyField(Group) Groups consist of particular tags, and those tags are linked to users. Long story short, one way or another the documents are only accessible by particular users. It is very important that this check does not slip through the cracks. So I can see a number of options. One is that every time I access a Document, I add the check: Document.objects.filter(access__group__tag__user=request.user) But there are two drawbacks: a) I query the documents model > 100 times in my views so I will have a LOT of repeated code, and b) it's quite likely that someone will at some point forget to add this restriction in, leaving documents exposed. So I am thinking that overwriting the objects() makes most sense, through a custom manager. That way I don't duplicate code and I don't risk forgetting to do this. class HasAccessManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(access__group__tag__user=request.user) class Document(models.Model): ... access = models.ManyToManyField(Group) objects = HasAccessManager() However, the problem becomes that request is not accessible there: name 'request' is not defined How to solve this? Or are there better solutions?