Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
coding style, use return as break in python/django methods
From other programming languages I am very much used to do something like that: def doit(bikes): if type(bikes) is not list: return False # do something with bikes list But in most python code I have seen, its much more done like def doit(bikes): if type(bikes) is list: # do something with bikes list So is my way not really "pythonic" ? I don't know if this really sets an example, but what I want to express is, that I always try not to put the code I want to run within a statement but to break the method when something is running wrong. This also might look like def runbikes(bikes): if type(bikes) is not list: return False if len(bikes) < 1: return False if 'tandem' not in bikes: return False return [bike.run() for bike in bikes] does this meet python coding guidelines? -
Redirecting user if condition is not met
I have a page where the user can report a post. If they have already reported that particular post, then they are not allowed to access this page. I am using a DetailView with the post id as the slug so it looks like this: /report/p/3/ Here's what I have so far: class ReportPostView(LoginRequiredMixin, DetailView): login_url = '/login/' template_name = 'core/report-post.html' model = Post slug_field = 'id' def get(self, request, *args, **kwargs): if Report.objects.filter(actor=self.request.user, post={{ slug_id_should_be_here, but I don't know how to get it from the slug }}).exists(): return HttpResponseNotFound("You have already reported this Post") else: return How can I check for this condition and redirect the user? -
django model does not save the uploaded image
I am trying to upload/update images that users upload using django/ajax/jquery. my front-end code seems to be working. But the django model does not upload/save the passed image. here is my profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{ self.user.username } Profile' and the forms for updating the user info: from django.db import models from django import forms from django.contrib.auth.models import User from .models import Profile class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] and this is my view function for updating the image: @login_required def update_profile_image(request): #print(request.FILES) if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) print(p_form) if p_form.is_valid(): p_form.save() context = {'None': 'none'} return JsonResponse(context) else: return HttpResponse('None') when I print the p_form, that is what it prints on the command window: <tr><th><label for="id_image">Image:</label></th><td>Currently: <a href="/media/profile_pics/profile_pic.jpg">profile_pics/profile_pic.jpg</a><br> Change: <input type="file" name="image" accept="image/*" id="id_image"></td></tr> I have added enctype="multipart/file-data" to my form so that is not the problem. and this my ajax call which as I said seems to be working fine: $(document).on('submit', '#profile_edit_form', function(event){ event.preventDefault(); //method = $(this).attr('method'); var … -
Add foreign key related entities in the same Django admin page
I'm working on a Django app wich will manage some quizes. Those quizes are formed by a question and some possible answers, which I've defined as different models. There is an OneToMany relationship between them, which as far as I know, should be modeled with a foreign key, in this case, in the answer entity. However, while managing the data from the Django administration site, this is quite inconvenient, because I've to define first my question, and later, while adding the answers, look for the question in order to fill the foreign key field. Would be somehow possible, to define all the answers while adding the question, in a similar way as if it was a ManyToMany relationship (the box with the + symbol, etc)? -
Django view give ''int' object has no attribute'' when in shell gives object from model
I got this error when I'm trying to obtain data from models in my view.Thing is, I understand clearly what this error is,but I am very confused why it is happening.It is becouse when I run following code in django shell i'm getting what i want. In django shell: In [2]: from ep.models import * In [3]: a = PreventionProgramCenter.objects.all() In [4]: a.values_list('center',flat=True) Out[4]: <QuerySet [1, 2, 3]> In [5]: b=a[0] In [6]: b Out[6]: <PreventionProgramCenter: PreventionProgramCenter object (1)> In [7]: b.center.zip_code Out[7]: '53-334' In [8]: for i in a: ...: print(i) ...: PreventionProgramCenter object (1) PreventionProgramCenter object (2) PreventionProgramCenter object (3) It is all good.I can get list of object from my model,iterate over it and calls methods. But in my view.py zip_codes = [] zip_codes_obj = PreventionProgramCenter.objects.all() zip_codes_obj = zip_codes_obj.values_list('center',flat=True) for zip_code in zip_codes_obj: print(zip_code) zip_codes.append(zip_code.center.zip_code) zip_code is just int,not object of PreventionProgramCenter.How,what I'm missing? -
Celery is connecting to amqp://guest**@localhost instead of Redis. Heroku deploy
I have read simillar topics and done everything there was being suggested, but the problem remains. I am deploying my app to Heroku. Locally everything was working fine, but during deploy after specyfying every setting I could think off to specify the celery worker sends following error: :22:50.722826+00:00 app[worker.1]: [2018-10-21 18:22:50,722: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. I tried switching from CloudAMQP to Redis. And the problem remains. Here are my config files: Django's settings.py: try: CELERY_BROKER_URL = os.environ['REDIS_URL'] except KeyError: CELERY_BROKER_URL = 'amqp://admin:admin@localhost:5672/admin_host' try: CELERY_RESULT_BACKEND = os.environ['REDIS_URL'] except KeyError: CELERY_RESULT_BACKEND = 'amqp://admin:admin@localhost:5672/admin_host' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' django_heroku.settings(locals()) celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from . import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'file_upload.settings') app = Celery('file_upload', broker_pool_limit=1) app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from the package containig celery.py and settings.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] and the os.environ['REDIS_URL'] does return a url, I checked … -
django boolean in form always returns true
learning django, and trying to make a todo list. A task is created first with only a task.name. Then I go to a taskdetail.html, with a form for task.detail, task.duedate, and task.done. The latter is a boolean that is true if the task is completed. I have the following in my template: <input type="hidden" name="done" value=0 /> <input type="checkbox" name="done" value=1 {% if task.done %} checked {% endif %}> In my views.py, I have: def taskdetail(request, task_id): task = Task.objects.get(pk=task_id) if request.method == 'POST': form = DetailTaskForm(request.POST) if form.is_valid(): task.name = form.cleaned_data["name"] task.description = form.cleaned_data["description"] task.done = form.cleaned_data["done"] task.duedate = form.cleaned_data["duedate"] task.save() ... Strange enough, task.done alsways ends up true. It's default is false, and I have verified that it is indeed false before task.done = form.cleaned_data["done"] I read that somewhere that value=0 is the same as false, but that doesn't seem to work for me. I also tried <input type="hidden" name="done" value="" /> but then my form.is_valid returns false. What could be the problem here? (I am working with Django 2.1 and python 3.7) -
Is it possible to turn cached pages off after a user logs out?
I know how to cache pages and all that. I currently do it from url patterns like cache_page(60*720)(views.post_list). But my current problem is turning cached pages off after a user logs out. Example of problem: Assume every template inherits from base.html, and that template has the following: {% if user.is_authenticated %} <h1>Hi, {{ request.user }}!</h1> {% endif %} Now assume that EVERY page is cached, except a logout/ page. Also assume that the user went straight to the login page without viewing any other page. So after logging in, a user goes to blog/, home/, contact/, and a special_login_page_viewable_only_by_login/, and so on, so they get the special Hi, user_name message visible on every page. Then the user goes to logout/ page, and they successfully logout. Now when the users goes to any page they just visited, even though logged out, they still see the Hi, user_name message on every page they visited, because of the cached pages. Caching makes the server far faster, but doesn't look right if the person logged out, and decided to browse the site some more. My current solution: Make pages that require a login to inherit from a different template that has the above if … -
Adding slug id in query
I have a DetailView which contains a get function. This get function checks if a certain condition holds true, if it does then throw an error. However, I'm having difficulty getting the slug id inside query where post= How can I add the slug id here? class ReportPostView(LoginRequiredMixin, DetailView): login_url = '/login/' template_name = 'core/report-post.html' model = Post slug_field = 'id' def get(self, request, *args, **kwargs): if Report.objects.filter(actor=self.request.user, post={{ slug_id_should_be_here }}).exists(): return HttpResponseNotFound("You have already reported this Post") else: return -
Adding data from two models into one table in Django?
I'm trying to add data from two models into one table. They are linked via a Foreign Key. I have searched the forum but cannot find a method that works with my data. At the moment, I can display a single models data in the table but not the other. Im using MySQL as my database. My models.py file: class location(models.Model): loc_room = models.CharField(max_length=20, blank=True, null=True) loc_block = models.IntegerField(blank=True, null=True) loc_shelf = models.CharField(max_length=4, blank=True, null=True) class box(models.Model): box_contents = models.CharField(max_length=300, blank=True, null=True) project_assigned_to = models.ForeignKey('project', null=True) location_id = models.ForeignKey('location', null=True) My views.py file: def all_assets(request): box_data = box.objects.all() return render(request, 'main_app/all_assets.html', { "box_data":box_data }) My table: <thead> <tr> <th>Assets</th> <th>Project</th> <th>Room</th> <th>Block</th> <th>Shelf</th> </tr> </thead> <tbody> {% for item in box_data %} <tr> <td>{{ item.box_contents }}</td> <td>{{ item.project_assigned_to }}</td> <td>**Here I need to add data from ROOM**</td> <td>**Here I need to add data from BLOCK**</td> <td>**Here I need to add data from SHELF**</td> </tr> {% endfor %} I hope somebody can help me with this. I've been trying out all the solutions on the forum but non work with my data. The closest I got was Django query to join records of two tables But again, I couldn't get it … -
Django - Can't get models.ForeignKey to self reference
I've been trying to show a list of people in a class that's pickable in a form, so I chose to have a foreignkey reference itself so the names would be the choices, that left me with this piece of code: class Student(models.Model): """Model representing the student. It has their name and classroom for now.""" name = models.TextField(max_length="200",help_text="Digite o nome do aluno.") class_number = models.ForeignKey(Classroom, on_delete=models.CASCADE, null=True) name_for_delete = models.ForeignKey('self', on_delete=models.CASCADE) def get_absolute_url(self): return reverse("student-detail", args=[str(self.id)]) def __str__(self): return self.name Where the relevant bit is name_for_delete = models.ForeignKey('self', on_delete=models.CASCADE), since I want to delete a person's name from the database. But whenever I try to execute the code I get this error: no such column: classroom_student.name_for_delete_id I tried to add an id but there's name conflicts. I don't even know if my solution to the problem is the correct one, is this the way I would delete a name using this view, and if it is, how do I fix this problem? -
How to load a static file in django2.0
I am having difficulty loading static files in django2.0 (coming from django1.4). Here is what I have so far: # urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # settings.py TEMPLATES = [ ... 'builtins': [ 'django.contrib.staticfiles.templatetags.staticfiles', ], ] STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = [ os.path.join(SITE_ROOT, "static"), ] And I have one image located at: [my_project_root]/static/img/image.png Now if I go directly to the url, I get a 404: http://localhost:8000/static/img/image.png What do I need to add here to serve the static files? -
dropdown is not working on web browser mode but it is working on mobil device mode
I have a problem my header html. When I use dropdown on nav, it is not extending items on web browser mode but it is extending items on mobile device mode.I tried to fix overflow but it is not solved problem. Thank you for your help. my html code: <header> <div class="container-fluid position-relative no-side-padding"> <a href="#" class="logo"><img src="{% static 'img\logo2.jpg'%}" alt="Logo Image"></a> <div class="menu-nav-icon" data-nav-menu="#main-menu"><i class="ion-navicon"></i></div> <ul class="main-menu visible-on-click" id="main-menu"> <li><a href="{% url 'index' %}">Anasayfa</a></li> <li class="dropdown"> <a id="drop1" href="#" role="button" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> <li><a tabindex="-1" href="#">Action</a></li> <li><a tabindex="-1" href="#">Another action</a></li> <li><a tabindex="-1" href="#">Something else here</a></li> <li class="divider"></li> <li><a tabindex="-1" href="#">Separated link</a></li> </ul> </li> <li><a href="#">Hakkında</a></li> {% if request.user.is_authenticated %} <li><a href="{% url 'article:dashboard' %}">Kontrol Paneli</a></li> <li><a href="{% url 'logoutUser' %}">Çıkış</a></li> {% else %} <li><a href="{% url 'LoginUser' %}">Yazar Girişi Yap</a></li> {% endif %} </ul> <div class="src-area"> <form> <button class="src-btn" type="submit"><i class="ion-ios-search-strong"></i></button> <input class="src-input" type="text" placeholder="Type of search"> </form> </div> </div> </header> -
how to extract images for every single post in django
I have two different models. One is for posts and other one is for images. what I want is to display all images for every single post. Here is the file for models: class Cars_Posts(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) post_city = models.ForeignKey(City, on_delete=models.CASCADE) post_title = models.CharField(max_length=256) post_detail = models.TextField(max_length=65536) price = models.PositiveIntegerField() def __str__(self): return "%s %s %s %s %s"( self.user.id, self.post_city, self.post_title, self.post_detail, self.price,) class Images_Cars(models.Model): post = models.ForeignKey(Cars_Posts, on_delete=models.CASCADE) car_images = models.ImageField(upload_to='car_images', blank=True, null=True ) def __str__(self): return "%s %s " % (self.post_id, self.car_images, ) Here is the view FUNCTION FOR SEARCH (QUERY DATA BASE): def search(request): template = 'path/to/template.html' # get all cities in data base all_p_cities = City.objects.all() #get the exact city selected by user and passed through the variable h_qc query_c = request.GET.get('h_qc') # get posts under the selected city result = Cars__Posts.objects.filter(Q(post_city__city_name__iexact=query_c) # get posts IDs of the result object p_id=[] for item in result: p_id+= [item.id] # print(p_id) #get all images under each single post all_images=[] for item in p_id: images = Images_Cars.objects.filter(post_id = item) all_images+=[images] # print (p_id) # print(result) print(all_images) context = { 'post_city' : query_c, 'result': result, 'all_images':all_images, } return render(request, template, context ) both files run with no error. … -
how to start a new project in django in virtualenv
I just installed virtualenv and in it I installed django. However, when I go to the django-admin terminal in the bin file, I wrote django-admin startproject mysite I thought that would start a new project but it just returned Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). -
How can I implement built in signals, for my app?
I have a project myappointments, with two apps appointments and clinic in it. Objective: When a user logins, details should be entered in the database. appointments/models.py: class Event(models.Model): id=models.AutoField(primary_key=True, unique=True) type=models.CharField(max_length=60) description = models.CharField(max_length=150) time = models.DateTimeField(default=timezone.now) appointments/init.py: default_app_config = 'appointments.apps.AppointmentsConfig' appointments/apps.py: from django.apps import AppConfig class AppointmentsConfig(AppConfig): name = 'appointments' def ready(self): import appointments.signals # noqa appointments/signals.py: from django.contrib.auth.signals import user_logged_in from django.dispatch import receiver def record_loggedin(sender, user, request, **kwargs): ev = Event(type="Login", description = 'User logged in: {}'.format(request.user.id)) ev.save() print("User has logged in. Saved event to DB.") user_logged_in.connect(record_loggedin) What other modifications do I need to do this? -
AppRegistryNotReady: Apps aren't loaded yet. when using UserCreationForm
I have looked high an low for someone with a similar issues as to mine. When I use djangos built-in UserCreationForm I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I've tried commenting out apps in INSTALLED_APPS in settings and still nothing. This only becomes and issues when I import UserCreationForm Here is my code from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'registration/signup.html', {'form': form}) Here is the error I'm receiving Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Python\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked … -
Django List View with AJAX
I am trying to send a json value to ajax from django class based view and the data i am sending will be appended in html through ajax. but i am not able to send value from back end to front end successfully. class DetailView(TemplateView): template_name = 'list.html' def get_context_data(self,*args, **kwargs): context = super(DetailView,self).get_context_data() list_view = GetList().get_data(self.request) movie_list = list.json() context['list']= movie_list print(movie_list) return context So this code is sending only template value to the ajax data, when i do the console.log(data) on success call it shows me whole html data of the 'list.html' in both alert and console.log . But it prints all the values in cmd console. cclass DetailView(TemplateView): template_name = 'list.html' def get(self,request): list_view = GetList().get_data(self.request) movie_list = list.json() return HttpResponse(json.dumps(movie_list)) this code prints all the values on respective html, but doesnt call ajax function.so no values showing in console.log. this is my ajax call,first i am trying to just see weather i'm successfully getting the values on success call or not. <script> $(document).ready(function(){ $.ajax({ method :'GET', url: '/detail', success: function(data){ alert(data) console.log(data) }, }) }) </script> So, how can i achieve my desired result? I want to get value in ajax call so i cal show … -
How to design models for relationships of user-to-user, user-to-company, company-to-user and company-to-company in django?
In my django app I have the models User and Company. A User can have relationships with Companys and also with other Users. And Companys can have relationships with other Companys and with Users as well. Can I just add ManyToManyFields related_users and related_companies to both models? Or is there a better way to design this? -
Transfer heroku input data for oython model processing in setting
I want to deploy one django python project in heroku, but have troubles in the transfer and application of the inputs data from the visitors. The web contains the topic and entries section for visitors to give inputs. I want to acquire every entries grouped by topics. The function of button_view will provide such function to transfer the data to the start() function of another uploaded python application. But the format has to be as a list. For example, the visitors may gave three topics: "fruit", "car", "human". The respective entries are: fruit: apply, pear, banana; car: BMW, Honda; human: asian, american. I need to acquire such data in the button_view function and transfer into a list like [[(u'apple',), (u'pear',), (u'banana',)], [(u'BMW',), (u'Honda',)], [(u'asian',), (u'american',)]] for processing in start(). Currently, entry_values = [[entry for entry in topic.entries.all()]for topic in Topic.objects.filter(owner=request.user).order_by("date_added")] (assisted by others Django acquire data from different layer not work. Can anyone help me? Thanks! def button_view(request): import sys entry_values = [[entry for entry in topic.entries.all()]for topic in Topic.objects.filter(owner=request.user).order_by("date_added")] results_list = start(entry_values) results_list2 = [s for l in results_list for s in l] context = {"topics": topics} return render(request, "learning_logs/topics.html", context) -
Django error : 'NoneType' object has no attribute 'find'
picture of the code that led up to the error message For Some reasons I keep getting this error: 'NoneType' object has no attribute 'find'. Then it points me to line 182 as seen in the picture I put here. All that is on line 182 is this: -
how to debug cache related code in django
I am trying to apply cache in my Django project using memcache. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } I am applying per view cache as below: from django.views.decorators.cache import cache_page url(r'^(?P<slug>[\w-]+)/default/$', cache_page(60 * 15)(default_view), name='default_view') I am trying to dedug the code in my IDE. I found the following function at lib/python3.6/site-packages/django/views/decorators/cache.py def cache_page(timeout, *, cache=None, key_prefix=None): return decorator_from_middleware_with_args(CacheMiddleware)( cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix ) I tried to create a stop at return line. But I found when i refresh the url the code does not stop at this line. -
i add a ssl cer and redirect http to https but now all url are 404
this is my nginx conf for project please say me why it doesn't work upstream django { server 127.0.0.1:8037; } server { server_name ; listen :80; return 301 https://www. $request_uri; } server { listen 443 ssl; ssl_certificate /etc/nginx/ssl.crt/server.crt; ssl_certificate_key /etc/nginx/ssl.key/server.key; server_name ; charset utf-8; server_tokens off; access_log /etc/nginx/log/access.log; error_log /etc/nginx/log/error.log; location /static/ { alias /home/app/public_html/Vishka/env/repo/project/Vishka/static/; } location / { include uwsgi_params; uwsgi_pass django; } } in uwsgi log there is no request all of my requests will be lose enter image description here -
Django Rest Framework - Best way to add authentication
I have two separate django websites, let's call them A and B. regular users sign up in website B, and administrators use website A. website A sends some info to website B using django rest framework (in the A side, it's just a simple post request, api is implemented in website B) so website B users have nothing to do with the api, and admins who send the info to B, are NOT users of website B. what do you think is the best way to add authentication to this api? so that regular users cannot send garbage requests? -
In python/django best way to create a list of objects method output
I have this code: objects = Object.objects.all() datalist = list() for object in objects: datalist.append(object.data()) return datalist Is there any better way to create this datalist? There is the values_list() method for queryset, but it only works with object fields and not with methods. So I wonder, if there is any better pythonic way that can create the datalist maybe in a single line rather in 3 lines?