Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update custom user model with a form Django
I have a custom user model I made, I am trying to make a form that will update it when submitted. I have looked at other answers on SO and have tried their solutions, even if my code is almost identical it will not work properly. I am getting no errors at all when I run this. The form shouldn't create a new UserAddress, but it should update its field. models.py class UserAddress(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_address') your_address = models.CharField(max_length=300, blank=True, default=' ') #used in sign up @receiver(post_save, sender=User) def create_user_address(sender, instance, created, **kwargs): if created: UserAddress.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_address(sender, instance, **kwargs): instance.user_address.save() forms.py class YourAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ('your_address', ) views.py @login_required() def settings(request): if request.method == 'POST': form = YourAddressForm(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponse('Awesome, I added it!') else: return HttpResponse("Not added") else: form = YourAddressForm(instance=request.user) return render(request, 'details/settings.html', {'form': form}) -
Django recursive model
I'm making my own "cloud server" with django, for my projects and files. I'm trying to create tree file structure, but I cant figure out the way to do it. And how I can make username based URL, like (username/root/home/Documents/...)I'm also interested of some good links and examples of authentication and django style cloud server solutions. models.py class BasicFile(models.Model): file_name = models.CharField(max_length=80) last_edit = models.DateTimeField(default=datetime.now, blank=True) sub_folders = models.IntegerField() sub_files = models.IntegerField() def __str__(self): return self.file_name views.py class IndexView(LoginRequiredMixin, ListView): template_name = 'cloud/index.html' context_object_name = 'project_file' def get_queryset(self, *args, **kwargs): return ProjectFile.objects.all() urls.py re_path(r'^(?P<username>)/$', views.IndexView.as_view(), name='index'), re_path(r'^(?P<username>/f1/f1_child)/$', views.IndexView.as_view(), name='index'), -
Score in ListView in title
i have problem and don't know how do that. I wanna add average from another model to model in ListView in django(1.9) It's my model class Anime(models.Model): title = models.CharField(max_length=200) content = models.TextField(max_length=2000,default='',blank=True) class Score(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.ForeignKey(Anime, on_delete= models.CASCADE, related_name='anime') And in my View.py i have def get_context_data( self, *args, **kwargs): context = super(TweetListView, self).get_context_data(*args, **kwargs) print(context) context["another_list"] = Anime.objects.all() context["Oceny_list"] = Score.objects.aggregate(Avg('ogolna')).values() print(context) return context But where is Score.objects i want filter to title from another_list, because right now i have average for all title as same Any suggesion how do that ? PS. Im sorry for my english :) -
Django extend UTF-8
I just started learning Django few days ago, and something is a bit weird. I actually use Visual Studio 2017 with the extension for Django. I created new project with the Visual studio template. My problem is that the UTF-8 works only on my layout.html when I extend it on other pages, here is some code : Layout.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> <title>{{ title }} - My Django Application</title> <!-- Titre de la page modifiable dans /template/app/views.py --> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> </head> <body> <!-- Barre de navigation --> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header" id="red"> <!-- Menu format mobile/petite page --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Titre du site --> <a href="/" class="navbar-brand">Site de test</a> </div> <!-- Barre de navigation : Selection des pages --> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'home' %}">Présentation</a></li> <li><a href="{% url 'about' %}">A propos</a></li> <li><a href="{% url 'contact' %}">Me contacter</a></li> </ul> {% include 'app/loginpartial.html' %} </div> </div> </div> <!-- Contenu de la page --> <div … -
Delete object ID and enumerate new column
friends. In my django admin i have a TabularInLine class. In picture each element of this class numerate with itself ID. How i can delete text circled by red colour on picture ? And how I can create a new numbered column (from 1 to amount elements in table)? This TabularInLine class have a foreign key to other class (class Part). How I can to numerate that for each FK the numbering (my_id) started from 1 like on picture below? In other words, I want to make the sequence number for each line -
Searching PostgreSQL with Django and passing a null or empty string value
I'm searching Postgres as follows: search_term = self.request.GET.get('search') queryset = Package.objects.filter(package_description__search=search_term) How do I make this return all objects if search_term is None or an empty string? I've tried setting search_term to None or an empty string. -
heroku and django: server doesn't load staticfiles
settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'myapp/static/myapp/'), ] STATIC_URL = '/static/' My project structure myproject |___ myapp |___ static |___ myapp |___ css |___ js |___ img all my static loaded as well when offline, but after push to heroku its not loaded properly. -
Open Edx problems
I have installed open edx and successfully deployed and run it. But the problem is with the CMS. When I sign in into the CMS, it just redirects to the landing page, giving no errors or not logged in (still shows the sign up and sign in button in the nav bar) But I checked the cookie after submitting login info, it creates the cookie in the browser states that I am logged in. But I can not access authorized urls (which required login) What is the problem -
Issue deploying django app on heroku / module not found error
I know that there are so many topics on this problem but i didn't find those helpful. I am trying to push my django app on heroku but during the transfer I receive a: ModuleNotFoundError : No module named 'dashboard_app.settings' It happens when the build is trying to run the : python manage.py collecstatic I renamed the app directory but changed everything in the settings. Everything works great on a local side, even the collectstatic command (You can see the staticfiles on the picture below). I have been trying to fix this all the afternoon but without any success... Some more informations there: manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dashboard_app.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) settings.py # Static files if os.environ.get('PRODUCTION') == 'True': PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') # Extra places for collectstatic to find static files. STATIC_DIRS = ( os.path.join(PROJECT_ROOT, 'static') ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] if os.environ.get('PRODUCTION') … -
Django mapping user to model
On Django 1.9, I can create users through a user form view. When the user submits the form to create a profile,the submission can be seen in the admin under "Users" and is logged in fine. I want the user to only be able to view the models they have uploaded. As such I need to map them together, however the user model is not defined in models.py. I have tried to link them in models.py in my model with: user = models.ForeignKey(User) However, this error is thrown: NameError: name 'User' is not defined Is this due to not having the user as a model in my models.py? Request that creates user: def post (self, request): form = self.form_class(request.POST) if form.is_valid(): #creates an object from the form #being stored locally as of now user = form.save(commit=False) #cleaned data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) #Saved to the DB after it's shown in the correct format user.save() models.py: class Clean(models.Model): name = models.CharField(max_length=100, blank = False) #User doesn't see when creating model cv = models.TextField(max_length=10000, blank = True, null = True) cvfile = models.FileField(validators=[validate_file_extension]) #User doesn't se when creating model cvscore = models.IntegerField() spellerrors = models.CharField(max_length=100, blank = False) *** … -
How can I implement html views for django-oauth-toolkit?
I am following the basic tutorial in Django OAuth Toolkit . Do I have to create the html files for the views (eg login.html, loggout.html)? My thought is that there is a default "out of the box implementation" for these files. I get the following error when I try to access oauth2 urls: django.template.loaders.app_directories.Loader: ...\lib\site-packages\django\contrib\admin\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: ...\lib\site-packages\django\contrib\auth\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: ...\lib\site-packages\rest_framework\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: ...\lib\site-packages\oauth2_provider\templates\registration\login.html (Source does not exist) -
How do I return a potentially large custom SQL query using StreamingHttpResponse?
I have a potentially large queryset that I don't want to load into memory. It's a custom SQL statement: with connections['mydb'].cursor() as cursor: cursor.execute("SELECT * FROM foobar;") django.http.StreamingHttpResponse takes an iterator (generator) argument, but cursor.fetchall().iterator() doesn't work, as fetchall returns a list of tuples, rather than a queryset. Is there any way I can stream this queryset without loading the whole thing in memory? My db is postgres, if that makes a difference. -
xhtml2pdf not applying css while creating pdf (html to pdf)
Conversion: html = template.render(context) resultFile = open(filepath, "w+b") pdf = pisa.CreatePDF(html.encode('utf-8'), dest=resultFile,encoding='utf-8', link_callback=link_callback) link_callback def link_callback(uri, rel): sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT mUrl = settings.MEDIA_URL # Typically /static/media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path I have created pdf using xhtml2pdf. The file is created but css is not at all applied to it. I have checked the path which is returned from link_callback, its correct but in pdf there is no css applied at all. css: #page_1 {position:relative; overflow: hidden;margin: 64px 0px 65px 0px;padding: 0px;border: none;} #page_1 #p1dimg1 {position:absolute;top:0px;left:20%;z-index:-1;width:600px;height:870px;} #page_1 #p1dimg1 #p1img1 {width:600px;height:870px;} #page_2 {position:relative; overflow: hidden;padding-left: 100px;border: none;height: 854px;} #page_2 #p2dimg1 {position:absolute;left:27%;z-index:-1;width:490px;height:669px;} #page_2 #p2dimg1 #p2img1 {width:490px;height:669px;} css path which i got: /Users/mypc/project/project/static/css/lender_borrower.css -
Django Restframework _ custom login
this is my custom login and authentication backend in Django Restframework. this view works and login will be successful. and Django Rest framework loges in.but when url changes in Django Restframework , authentication and log in resets . class LoginView(APIView): serializer_class = ActivateUserSerializer def post(self, request, format=None): data = request.data phonenumber = data.get('phonenumber', None) first_token = data.get('first_token', None) try: user = User.objects.get(phonenumber=phonenumber) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if user is not None: if first_token == user.first_token.token: if user.is_active: login(request, user) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_404_NOT_FOUND) and this is my main urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('blog.urls')), path('api/', include('rest_framework.urls', namespace='rest_framework')), ] and this is my blog urls.py : urlpatterns = [ re_path(r'^users/$', views.UserListView.as_view(), name='user-list'), re_path(r'^login/$', views.LoginView.as_view(), name='login'), ] so how can I disable default login system and tell Django only use my custom login? -
with "error during template rendering"
I have some problems about template in django. Following the instruction of Django2.0 document, i am facing with this problem. Error during template rendering Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['main_app\/(?P[0-9]+)\/$'] results.html <h1>{{question.question_text}}</h1> 2 <ul> 3 {% for choice in question.choice_set.all %} 4 <li>{{ choice.choice_text }} -- {{ choice.votes }} vote {{ choice.votes|pluralize }}</li> 5 {% endfor %} 6 </ul> 7 8 <a href="{% url 'main_app:detail' question.id %}">Vote again!!</a> detail.html <h1>{{question.question_text}}</h1> {% if error_message %} <p> <strong> {{error_message}} </strong> </p> {% endif %} <form class="" action="{% url 'main_app:votes' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{choice.id}}"/> <label for="choice{{ forloop.counter }}">{{choice.choice_text}}</label><br/> <!-- forloop.counter indicates how many times the for tag has gone through its loop--> {% endfor %} <input type="submit" name="" value="Vote"/> </form> main_app/views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from .models import Question,Choice from django.urls import reverse # Create your views here. def index(request): lastest_question_list = Question.objects.order_by('pub_date')[:5] context={'lastest_question_list':lastest_question_list} return render(request,'main_app/index.html',context) def detail(request,question_id): question = get_object_or_404(Question,pk=question_id) context = {'question':question} return render(request,'main_app/detail.html',context) def results(request,question_id): question = get_object_or_404(Question,pk=question_id) context = {'queston':question} return render(request,'main_app/results.html',context) def votes(request,question_id): question=get_object_or_404(Question,pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return … -
The advantage of classonlymethod over classmethod for class View
in views.generic.base.py of Django, it define class View class View: """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) @classonlymethod # my question def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) Within … -
Dropdown menu not working html
I am trying to create a website but when i add the navigation bar (This is The one i'm using https://www.w3schools.com/css/tryit.asp?filename=trycss_dropdown_navbar ) It works fine but as soon as i do {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} It doesn't work anymore I'm using Django 2.0 and bootstrap 3 And i already looked it up in google and all the answers reffer to a problem in javascript But i'm not using any -
Django Url not matching?
I want to match the following dynamic url in django : http://localhost:8000/gif/1/this-is-tests am trying following code : ^gif/(?P<image_id>\w{0,50})/(?P<image_title>\w{0,500})/$ it is error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/gif/1/this-is-tests what am doing wrong ? -
How to extend an admin view in Django?
I would like to extend the admin view used to create a new entry in the database. For example I can create new books with their author, their categories, their date etc... When I create a new book I want to send a notification to all users whose the book's author is one of their favorite authors. The notification system is already working thanks to django-notifications So, I just have to add this kind of stuff just after the book.save() in the admin view : writer = <the_author_selected_in_the_form> # writer ID profiles = Profile.favorites_authors.through.objects.filter(authors_id=writer) for profile in profiles: notify.send(profile.profile_id, recipient=profile.profile_id, verb='New book, called <book_title>, from <author_name>') Thank you -
Data migration using multithreading
I need to populate database with initial data from csv file. As data in csv file is very large, I am trying to use multi-threading in data migration. But I am constantly getting errors in doing so. I have tried catch block and locks, but nothing seems to be doing thing in my favour. This is my migration file. from django.db import migrations import csv from django.db import transaction # from multiprocessing import Pool import threading import time def process_data(data,State,District,Region,Pincode): for row in data: state=row['statename'] district=row['districtname'] region=row['officename'].split(' '+row['officetype'])[0] pincode=row['pincode'] try: state_object = State.objects.get(name=state) except State.DoesNotExist: state_object = State.objects.create(name=state) try: district_object = District.objects.get( name=district, state=state_object ) except District.DoesNotExist: district_object = District.objects.create( name=district, state=state_object ) try: pincode_object = Pincode.objects.get( value=pincode, district=district_object ) except Pincode.DoesNotExist: pincode_object = Pincode.objects.create( value=pincode, district=district_object ) try: Region.objects.get( name=region, district=district_object, pincode=pincode_object ) except Region.DoesNotExist: Region.objects.create( name=region, district=district_object, pincode=pincode_object ) def add_data(apps, schema_editor): State = apps.get_model('locations', 'State') District = apps.get_model('locations', 'District') Region = apps.get_model('locations', 'Region') Pincode = apps.get_model('locations', 'Pincode') thread_list = [] filename = 'All_India_pincode_data_26022018.csv' file_data = csv.DictReader(open(filename,'r',errors='ignore')) count=0 rows=[] for row in file_data: rows.append(row) count+=1 if count==10000: thread_list.append(threading.Thread(target=process_data, args=(rows,State,District,Region,Pincode))) rows=[] print(rows,len(thread_list)) count=0 if count>0: thread_list.append(threading.Thread(target=process_data, args=(rows,State,District,Region,Pincode))) for thread in thread_list: thread.start() for thread in thread_list: thread.join() print('Number of … -
adding badges to user for doing tasks in django
Hi Djangonauts, How is everyone today, I am new to Django so please forgive any silly mistakes in logic or code. I have a user, a User_Profile and a posts model. I want to give the user badges for the number of posts the user posts. Example if the user posts 3 posts he/she gets a beginner badge and so on... Below is my user Profile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(default='', blank=True, null=True) badge_image = models.ImageField(default='', blank=True, null=True)#maybe default can be "static/images/beginner_image.jpg" but it does not work posts models.py User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() Now I want to achieve something like this: user = User.objects.get(username=request.user.username) if user.post.count >= 3 : badge_image = '<img src="some image">'# I don't know how to make a image variable in views and models. I know how to use it in Django templates with {{image.url}} elif user.post.count >= 20 : badge_image = '<img src="some image">' else: badge_image ='<img src="beginner_image">' Where do I write this code in the models, in the views? I am sorry if my questions are too basic. None of the projects I learned … -
how to make django HttpResponse return faster than 1 second
I am running Django on localhost using the Django development server. I have a view that just returns HttpResponse("hello world"). def simpleview(request): return HttpResponse("hello world") I make a GET request with jquery to that view. Looking in the browser, it shows that this takes 1.3 seconds to return which is very slow. Is there any way to check what is going on? I am trying to use this for autocomplete, and a waiting time of 1.3 seconds for a virtually empty response is unusable. -
How can we create seggregate database for single user in django?
How to create dynamic database in django? While creating a new user, can we able to create a new database for respective user? The concept is needed for SaaS application. Need help!!! -
problems using string split python
I created a function to split a string containing date and time: def split_time(time_string, string): #'2018-03-17T05:20:00+01:00' if string == 'date': date = time_string.split('T')[0] return date elif string == 'time': pre_time = time_string.split('T')[-1] time = pre_time.split('+')[0] return time the comment displays what string i get i use [0] and [-1] because for some reason the the array fills up in the negative direction (i already created a question because of that which gave me the workaround of using [-1], if needed i will link the question) here i call the function: end_event_time = split_time(end, 'time') test = end_event_time.split(':') h = test[0] m = test[1] print(end_event_time, h, m) test displays ['05', '20', '00'] h gives me 05 while m raises the error list index out of range [-1] displays 00 My problem is that not only do i need to call the variales with negative indexes, i can only access the first and the last variable I´m using the django environment but these tests are displayed on the console Any help would be appreciated! -
Django - creating a main page without an extension with request processing (not direct to template)
I'm very new to Django, while going through the tutorials how to start different apps inside of a project is clear to me, but not setting up the index page of the entire website. Inside of my project folder it looks something like: Projectname App1 App2 App3 What I want to do is create a url with path looking something like this from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('index.urls')), #Homepage url path('App1/', include('App1.urls')), path('accounts/', include('django.contrib.auth.urls')), path('App2/', include('App2.urls')), path('App3/', include('App3.urls')), path('admin/', admin.site.urls), ] So that you can visit http://127.0.0.1:8000/ (or website.com) and see an index page with a corresponding view that I can use to show content from a database. Maybe its as simple as creating an index-app and setting the path to (''), but I haven't been able to accomplish that.