Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the most secure & powerful programming language for back-end in 2019?
Please help me by. I have to start my project so I need a quick answer of u. -
Forcing password on login with IAP and restrict domain
I've set up a Django/python web application running on Google Cloud Platform's Kubernetes Engine pods, and secured by GCP's Identity-Aware Proxy. It all works great, but there are two things I'm not sure how to accomplish. 1) How can I restrict the users to a specific domain, just like the hd=my_domain.com URL parameter does on OAuth2 logging in? That makes the sign-in page only show emails with that domain in the list to click on. 2) How can I enforce that the user logs in with a password, instead of just simply clicking on the account? This is just like when you go to admin.google.com, or security.google.com and even though you're logged in, it forces a password. I know how to go to /gcp/clear_login_cookie to enforce a new login session when I want to log them out, but not sure how to enforce a password is entered. This I believe is called the "user presence test." Any help is greatly appreciated, I've poured through documentation and have searched various ways on Stack Overflow to no avail. -
TypeError: __init__() got an unexpected keyword argument 'as_attachment' for reportlab django
Was following this here: https://docs.djangoproject.com/en/2.1/howto/outputting-pdf/ The code from there above I have in my views.py def test_report_lab(request): theBuffer = io.BytesIO() p=canvas.Canvas(theBuffer) p.drawString(100, 100, "Hello World") p.showPage() p.save() return FileResponse(theBuffer, as_attachment=True, filename='hello.pdf') And got the error: TypeError: __init__() got an unexpected keyword argument 'as_attachment' Not sure why, FileResponse should be totally happy with an as_attachment? https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.FileResponse -
Chained dropdown issue with django-smart-selects
I'm at my wit's end. I've scoured the stackoverflow for similar issues to no avail and eventually gave up on resolving the issue. I've built a pet project in django that uses an input form to search a SQLite database to convert lunar dates into gregorian dates and vice versa. Everything has worked properly so far, but now I'm trying to build chained dependencies where the day field dropdown only lists the appropriate number of days for the selected month. I'm using the django-smart-selects module to try to accomplish this. However, the Month dropdown now lists every single date (the table's primary key) from my table in the form of: The Month dropdown should only list months 1 - 12. I've tried removing the primary key field, but then I get the following error message: django.db.utils.OperationalError: no such column: Converter.id where Converter is the name of the table in my model. Can someone please shed some light on this? models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey MONTH_RANGE_CHOICES = [(i, i) for i in range(1, 13)] DAY_RANGE_CHOICES = [(i, i) for i in range(1, 32)] YEAR_RANGE_CHOICES = [(i, i) for i in range(1901, 2101)] class Month(models.Model): name = models.IntegerField('Lunar … -
Apache permission conflict with PHP and Django in same host
I'm trying running php and django under apache2 in same host (ubuntu). Fist I've the django_app.conf (it's works). <VirtualHost *:80> ServerName siteindjango .com.br ServerAlias www.siteindjango.com.br LoadModule wsgi_module "/home/example /imob/env/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" ErrorLog /home/example /imob/error.log CustomLog /home/example /imob/access.log combined Alias /favicon /home/example/imob/framework/static/favicon.ico Alias /static /home/example/imob/framework/static Alias /media /home/example/imob/framework/media <Directory /home/example/imob/framework> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/example/imob/framework/media/> Require all granted </Directory> <Directory /home/example/imob/framework/static/> Require all granted </Directory> WSGIDaemonProcess imob processes=2 threads=5 display-name=%{GROUP} python-path=/home/example /imob/framework/:/home/example /imob/env/lib/python3.6/site-packages WSGIProcessGroup imob WSGIScriptAlias / /home/example /imob/framework/framework/wsgi.py </VirtualHost> and the PHP virtuahost not woking with other vhost together. If a put the same PHP vhost in other host it's work. php_app.conf ServerName siteinphp.com.br ServerAlias www.siteinphp.com.br #ServerAdmin siteinphp@example.com DocumentRoot /home/phpsite/radio #ErrorLog /home/phpsite /radio/error.log #CustomLog /home/phpsite/radio/access.log combined <Directory /home/phpsite/radio> AllowOverride All Allow from All Require all granted </Directory> error log: You don't have permission to access / on this server. apache error log: [Mon Jan 28 18:15:02.707809 2019] [authz_core:error] [pid 1599] [client 60.217.72.16:59870] AH01630: client denied by server configuration: /home/example/imob/framework/framework/wsgi.py Apparently the django application are blocking php permission in .wsgi script -
Django - Filter view by category from two models
i extendet my post models and now my post_list_by_category function shows ugly lists.It shows 2 or more different categories where only posts from one category should be displayd. This app uses 2 types of post models, so somehow i need to get them together but filterd by the categories they both belong too. Any idea? Old working with one Model: def post_list_by_category(request, pk): category = Category.objects.get(pk=pk) list_posts = Post.objects.get_queryset().order_by('-pk') paginator = Paginator(list_posts, 10) # Show 10 Posts per page page = request.GET.get('page') posts = paginator.get_page(page) return render(request, 'MyProject/post_list_by_category.html', {'posts': posts, 'category': category}) New not working with two models: def post_list_by_category(request, pk): category = Category.objects.get(pk=pk) list_posts = list(chain(Post.objects.get_queryset().order_by('-pk'), Post_Extra.objects.get_queryset().order_by('-pk'))) paginator = Paginator(list_posts, 10) # Show 10 Posts per page page = request.GET.get('page') posts = paginator.get_page(page) return render(request, 'MyProject/post_list_by_category.html', {'posts': posts, 'category': category}) Kind regards, -
Can a Django project be hosted in Firebase? If yes, give me an idea
I know to host my Django projects in pythonanywhere or something else. But, I need to know is that possible to host a Django project in Firebase Hosting Services. -
Django models, 2 foreign keys, object logic
(Capitalized the objects within the process). Is this considered legal, my goal is to have 3 individual objects (the reasoning behind this is to allow me to assign a specific school + major to specific professors). When a user is to select a SCHOOL, I want my website to pull the MAJORS that specifically correspond to that SCHOOL, and when they select a MAJOR, I want the specific PROFESSORS to display. Logical connection between the objects below (business rules) The SCHOOL needs to be a many-to-many relationship with MAJOR: One SCHOOLS can have MANY Majors One Major can have MANY SCHOOLS The PROFESSOR a PROFESSOR can work at ONE SCHOOL, and teach ONE MAJOR a Major can be taught by MANY PROFESSORS, at MANY SCHOOLS So my difficulty is writing out the logic of the models to ensure all conditions are met, the information set before the rules is the experience I want my users to have when it comes to information pulled from the database to the website, and the logic below it. from django.db import models class Professor(models.Model): School = models.ForeignKey(School , on_delete=models.CASCADE) Major = models.ForeignKey(Major , on_delete=models.CASCADE) class Major(models.Model): Major = models.CharField(max_length=30) School = models.ForeignKey(School , on_delete=models.CASCADE) … -
How to pass the context from a view and access the context data in javascript in Django?
I am passing some data in a dictionary in django view and I want to access the dictionary data in my javascript code to display the data in my html. But whenever I print the passed context, it just prints 'success' on my console and not the actual data. Here is my dictionary structure: context['search_successful'] = "some string" I am passing this dictionary to my success function after making an ajax call to the view. For the time being I am just passing the HTTPResponse('true', context). After collecting the data in my javascript code, I just want to print the data of my context which will give 'some string' on my console but it gives success everytime. Here is my view: def daily_object_search(request): context = {'search_successful': "No"} if request.method == 'POST': object_name = request.POST['search_object_name'] print("The query for search :", object_name) if len(object_name) <= 2: print("The length of the object name :", len(object_name)) return HttpResponse('invalid_query') my_cursor = mydb.cursor() sql = "select * from education_fruits where tag = '" + object_name + "'" my_cursor.execute(sql) result = my_cursor.fetchall() print(result) if my_cursor.rowcount <= 0: print("No object found") return HttpResponse('false') context['search_successful'] = "Yess" return HttpResponse('true', context) Here is my template: <script type="text/javascript"> $(document).on('submit', '#search_object', function(e){ … -
Python - special characters reading from URL parameter
I am reading URL parameter from the below URL http://exaple.com/api/v1/get_example/?fruits_name=[apple%20+%20banana] fruits = urllib.unquote(request.GET.get('fruits_name', None)).decode('utf8') print fruits my output is: [apple banana] in between apple and banana I am getting three spaces but not '+' symbol in my output. the original string is [apple + banana] I need output as [apple + banana]. Can anyone suggest where I am doing wrong?? -
Is there a better way to delete all the .py and .pyc files in a given subdirectory?
I wrote a script to delete all the .py and .pyc files in a given sub-directory called "migrations". The end goal is to remove all migration files from my django project, so there are multiple sub-folders called "migrations" and I would like to remove all .py and .pyc (except init.py) from these folders. The script I wrote below works but I am new to python and figure there has to be a better way then all the nested loops. Any suggestions? This is a windows system which complicates things for me. import os import sys def delete_py(path, subfolder): try: if os.path.exists(path): for (root, dirs, files) in os.walk(path): for dir in dirs: if dir == subfolder: goto = os.path.join(root, dir) for (root, dirs, files) in os.walk(goto): for file in files: if (file.lower().endswith('.py') | file.lower().endswith('.pyc')) and file != '__init__.py': print('file: ', file) # will change to os.remove once finsihed except: print('Unable to delete files') if __name__ == "__main__": current = os.getcwd() delete_py(current, 'migrations') -
Pyinstaller with Django on Windows - "environment can only contain strings"
I'm writing a script that is a simple gui wrapper around the manage.py runserver utility of my django set-up. I have been able to package the whole thing together with PyInstaller on OSX just fine; however, when creating the relevant executable on Windows, I get the following error: TypeError: environment can only contain strings After diving into some of the utilities that PyInstaller called to hit this bug, I have revealed that two environment variables have been set to unicode strings: the DJANGO_SETTINGS_MODULE and PYTHONPATH environment variables. I could feasibly modify one of the PyInstaller scripts to attempt to re-encode these variables, before they hit the underlying Popen that is throwing the error; however, that does not seem tremendously portable. Is this an issue anyone has encountered before? Are there spec settings, or some other such thing, that I should change? Thanks! -
Is it possible in django form to check for validation while user input in the form?
while the form input from the user is it possible to check for validation during fills the entry in Django forms. -
limit access to some functions with a flag in python
I have a Django project that calls webservice for login and if the login information was valid, the webservice returns a flag. I want to use that flag and if it is True, let the user see other pages and if it was false, return to login page. in the beginning, the login database was on my side and I used Django user_passes_test, in the new style, I made a simple decorator simple decorator that returns True or False, and it seems that doesn't work that way, and I searched for some Django feature and found nothing. def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') flag = LoginWebservice(username=username,password=password) request.session['flag'] = flag if user_login_reasult == True: return redirect(reverse('basic_app:HomePage')) else: return redirect(reverse('basic_app:login')) def login_ws_check(request): try: if("flag" in request.session): return True else: return False except Exception as e: messages.info(request, e) return False @login_ws_check def HomePage(request): return render(request , 'basic_app/HomePage.html') @login_ws_check def OtherPage(request): return render(request , 'basic_app/OtherPage.html') i expect if the login flag is True , let me in and if not , redirect me to login page. and none of the ways I've tried working -
django ordered_by reverses distinct
I got following szenarion class Course(models.Model): name = models.Charfield(max_length=255) class CourseDay(models.Model): course = models.ForeignKey(Course) date = models.DateField() Now I did a filter which looks like this: courses = Course.objects.filter(models.Q(courseday__date__gt=date_filter) | models.Q(courseday__isnull=True)) If I do following: courses = Course.objects.filter(models.Q(courseday__date__gt=date_filter) | models.Q(courseday__isnull=True)).distinct() I get my queryset of courses without any duplicates. Now I wanted to order this queryset by the date of the related CourseDays I have to options. First one is: courses.order_by("courseday__date") Secound one is to edit the Course class and add a Meta class with the condition. Both are sorting my queryset as I want it to be, but they remove the distinct() option. If I have a 2 Day course and add 2 course days, it should only take the first day, can I do this with order_by or the Meta class or do I have to make my custom sorte function -
Position a link in HTML, using attributes
I am building a website, using django, CSS, HTML. I have posted some parts from an html file I am dealing with currently. I am a newbie in CSS/HTML. So I have problems with positioning the links which you can see below, using attributes top, left, right. The attributes margin-top, margin-left do not work either. Can you give advice on how to do this? {% extends "base.html" %} {% block style %} div{ margin-top:1px; float:right } .button1{ color:White; background-color:SaddleBrown; padding:5px; font-family:Comic Sans MS; font-size:20px; display: inline-block; cursor: pointer; border: none; border-radius: 12px; } {% endblock %} {% block body %} <a href="{%url "steak"%}" class="button1" top="100px" right="110px">STEAKS</a> <a href="{%url "salad"%}" class="button1" top="570px" left="150px"> SALADS</a> <a href="{%url "drink"%}" class="button1" top="830px" left="400px">DRINKS</a> {% endblock %} -
Is there a way in Django to combine to queries of a single model with different parameters?
I'd like to be able to display a table with a stores current value, as well as the value from last year. Right now I query all the stores, and then for each store I loop through and get the value from the comparison date and time. But this ends up taking 60+ queries. Here are my models. All of the data lives in the ShowroomData model class Stores(models.Model): storeid = models.IntegerField(default=0, primary_key=True) location = models.CharField(max_length=128) class ShowroomData(models.Model): store = models.ForeignKey(Stores, db_column="storeid", default=0, on_delete=models.CASCADE) date = models.DateField(db_index = True) # Field name made lowercase. time = models.IntegerField() # Field name made lowercase. sales = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. tax = models.DecimalField(max_digits=10, decimal_places=2) # Field name made lowercase. My views.py for store in current_data: comparison_data = ShowroomData.objects.filter(store=self.store, date=comparison_date, time=self.time) if comparison_data: for record in comparison_data: store.compare_amount = record.sales + record.tax I'd like to be able to store all of these in one query set, and then loop over it in the templates instead of having to loop through in the beginning to re append the query. If at all possible to have the data from the second query in a seperate field in the query set? Thank you! -
Increment object count using same form
I am trying to increment an object every time I create it using a fomr. One user can then have multiple instances of an object, which I can call accordingly in an html template. Basically, the form creates an object the first time, which it is currently doing, and then when the form is submitted again, it checks if there already exists and object, and if so creates an increment of it. HTML <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.instrument }}</p> <p class="date">{{ goals.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.goal }}</p> </div> </div> </div> </div> <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals1.instrument }}</p> <p class="date">{{ goals1.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals1.goal }}</p> </div> </div> </div> </div> models.py class Goals(models.Model): user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE) goal = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) goal_date = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.goals @receiver(post_save, sender=User) def create_user_goals(sender, instance, created, **kwargs): if created: Goals.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_goals(sender, instance, **kwargs): instance.goals.save() class GoalsForm(ModelForm): class Meta: model = Goals exclude = ('user',) views.py def goal_creation(request): if request.method == 'POST': form = GoalsForm(request.POST, instance=request.user.goals) if form.is_valid(): goals = form.save(commit=False) goals.user … -
Data rendering on Django Channels from Python websocket
I am trying to send data from my python websocket client to Django Channels server. I am using the python web socket client. my-websocket.py def on_message(ws, message): print (message) def on_error(ws, error): print ("eroror:", error) def on_close(ws): print ("### closed ###") # Attemp to reconnect with 2 seconds interval time.sleep(2) initiate() def on_open(ws): print ("### Initiating new websocket connectipython my-websocket.pyon ###") def run(*args): for i in range(30000): # Sending message with 1 second intervall time.sleep(1) ws.send("Hello %d" % i) # ws.send(json.dumps("Hello %d" % i)) time.sleep(1) ws.close() print ("thread terminating...") _thread.start_new_thread(run, ()) def initiate(): websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:8000/ws/power/room/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever() if __name__ == "__main__": initiate() My consumer of Django Channels is consumer.py class EchoConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'power_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket … -
How to filter ForeignKey set icontains?
models.py class AModel(models.Model): content = models.TextField(max_length=20) class BModel(models.Model): a_model = models.ForeignKey(AModel, on_delete=models.CASCADE, null=True, blank=True) text = models.TextField(max_length=20) Let say I have AModel object: a_object And also I have BModel objects: {'a_model': a_object, 'text': '111'}, {'a_model': a_object, 'text': '222'}, {'a_model': a_object, 'text': '333'} views.py a_models = AModel.objects.filter(Q(bmodel__text__icontains=search_word))[:10] The problem is that if search_word is '111', It seems to be working well but search_word is '222' or '333', then it cannot find a_object. I think that bmodel__text__icontains=search_word means 'only one' bmodel__text__icontains=search_word, not 'all' bmodel__text__icontains=search_word. How can I do filter 'all' bmodel__text__icontains=search_word? -
Django Add methods to all models
I'm creating multiple Django apps. I want to add to every model a function, exist. Can I add this function to the built-in model or do I have to use a proxy model? -
Django - Pytest setup crash after deleting model
After deleting an old Model in my Django micro-service, pytest fails to setup the test DB. The migrations fail to execute correctly. However, the migration generated after the model deletion works well on my staging DB. The problem is only impacting new DBs and in this case, the one created by pytest. What I did to delete my model: Remove all use cases of my model Delete my model Makemigrations Migrate The pytest DB-creation step is replaying the migrations history. It should: Create my model Define constraints Delete my model as I want to delete it The error makes me think the creation of the model is deferred as Django see that it is deleted later, and so the model constraints seem to be executed before the creation of the model. self = <django.db.backends.utils.CursorWrapper object at 0x114590198> sql = 'ALTER TABLE "catalogue_productoffer_competitors" ADD CONSTRAINT "catalogue_productoff_competitor_id_99767623_fk_categorie" FOREIGN KEY ("competitor_id") REFERENCES "categories_competitor" ("id") DEFERRABLE INITIALLY DEFERRED' django.db.utils.ProgrammingError: relation "categories_competitor" does not exist Thanks for your help ! -
Django vs packages compatibility
I see several similar questions on SO but about specific packages. I would like to know if there is a generic solution. I am reviving several Django applications abandoned for several years. The lists of requirements (in setup.py or requirements.txt) are incomplete, so I have to install several missing required packages. The problem is: those earlier Django versions are incompatible with the current versions of the required packages. So, my questions: Given a Django version and a specific package name (or even better a list of package names), is there a way to get the latest compatible version of the package (e.g. which debug_toolbar is compatible with Django 1.8.3)? That would be useful to have correct env setup for a given Django version If package still exists but has been renamed (e.g. truncate_words -> Truncator, or django.core.urlsresolvers -> django.urls) or restructured (e.g. django.contrib.contenttypes.generic). Is there a way to get this info, from pip or anywhere dynamically? That would be useful if some day in the future I decide to bite the bullet and upgrade everything and then fix the code (but it's not an option for now). Thank you. -
How to prepopulate the form for editing a comment
There are lots of answers about this issue, but still I can't sort it out. In my app, a user can write, edit or delete their comments. Everything works smoothly with the exeption of prepopulating the form with an existing comment text in edit mode (an empty form is shown). I tried to use initial=, but it didn't work. What should I do to prepopulate the edit form? models.py: class Comment(models.Model): text = models.TextField(blank = False) forms.py: class CommentForm(ModelForm): class Meta: model = Comment fields = ['text',] views.py: if request.method == 'POST': comment_id = request.POST.get('comment_id') comment = Comment.objects.get(pk=comment_id) form = CommentForm(request.POST, instance=comment) if form.is_valid(): edited_comment = form.save() return HttpResponseRedirect(reverse(<...>)) in the template: <form class="edit" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="edit_button" value="Save changes"> </form> -
search bar add as a base template into one class views Django
views.py class BookList(ListView): model = Book context_object_name = 'book_list' template_name = 'books/book_lists.html' paginate_by = 12 extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } def get_queryset(self): query = self.request.GET.get('q') if query: object_list = self.model.objects.filter( Q(name_of_the_book__icontains=query) | Q(author__first_name__icontains=query) | Q(category__name__icontains=query) ) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() context.update(self.extra_context) return context class BookDetails(DetailView): model = Book template_name = 'books/book_details.html' extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() context.update(self.extra_context) print(context) return context base.html <form class="example" action="" style="margin:auto;max-width:300px"> <input type="text" name='q' placeholder="Search..."> <button type="submit" value='{{ request.GET.q }}'><i class="fa fa-search"></i></button> </form><br> Here, BookList view is my homepage and when I'm searching from here then it's working good but when I'm going to Detail page then it doesn't work. Cause from BookDetailView I didn't send any kinds of a query in the base.html template. So, in this case, How can I send a query from DetailView or is there any built-in decorator for DetailView or can i use just one Class that will work for searching dynamically all template? Thanks