Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run code on first Django start
I have a Django application written to handle displaying a webpage with data from a model based on the primary key passed in the URL, this all works fine and the Django component is working perfectly for the most part. My question though is, and I have tried multiple methods such as using an AppConfig, is how I can make it so when the Django server boots up, code is called that would then create a separate thread which would then monitor an external source, logging valid data from that source as a model into the database. I have the threading code written along with the section that creates the model and saves it in the database, my issue though is that if I try to use an AppConfig to create the thread which would then handle the code, I get an django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. error and the server does not boot up. Where would be appropriate to place the code? Is my approach incorrect to the matter? -
Dganjo URL pattern mattching
I have been staring at this issue for a while now and while I am sure its silly mistake, I can't seem to find a solution. Pattern matching URL's in Django 1.9 Here are the URL patterns: urlpatterns = [ url(r'^$', guidy.views.index), url(r'^events/$', guidy.views.topLevelView, name='topLevel'), url(r'^events/(?P<activity>[a-zA-Z]+)/(?P<genre>[a-zA-Z]+)/$', guidy.views.events, name='events'), url(r'^events/(?P<activity>[a-zA-Z]+)/$', guidy.views.subLevelView, name='subLevel') ] and the Template: {% extends "base.html" %} {% load staticfiles %} {% block content %} <section id="portfolio" class="portfolio"> <div class="container"> <div class="row"> <div class="col-lg-10 col-lg-offset-1 text-center"> <h2>Events</h2> <p>{{ activity }} </p> <p>{{ catorgories }} </p> <hr class="small"> <div class="row"> {% for cat in catorgories %} <div class="col-md-6"> <div class="portfolio-item"> <a href="{% url 'events' cat %}"> <p>{{ cat }} </p> </a> </div> </div> {% endfor %} </div> <!-- /.row (nested) --> <a href="#" class="btn btn-dark">View More Items</a> </div> <!-- /.col-lg-10 --> </div> <!-- /.row --> </div> <!-- /.container --> </section> {% endblock %} This is the error that I am getting: Reverse for 'events' with arguments '('Blues',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['events/(?P<\activity>[a-zA-Z]+)/(?P<\genre>[a-zA-Z]+)$'] When accessing {% url 'sublevel' cat %} on the previous page, it works fine, its just when diving deeper does the error happen. Also, when typing directly into the address bar, Django … -
(django) getting the primary key form a submitting form and use it for redirection
I have a django model called "post" and I want that when adding a post with the url: url(r'^newpost/', views.PostFormView.as_view(), name='add'), it redirects me to the detail page of the added post with the url: url(r'^(?P<pk>[0-9]+)/$', PostDetailView, name='detail'), where pk is the id (primary key of the added post) My post model is as following: class Post(models.Model): person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) domain = models.ForeignKey(Domain, on_delete=models.CASCADE) speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE) level = models.ManyToManyField(Level) date_post = models.DateTimeField() title = models.CharField(max_length=200) description = models.CharField(max_length=1000) is_deleted = models.BooleanField(default=False) date_delete = models.DateTimeField() My PostFormView view to add a new post is: class PostFormView(View): form_class = PostCreationForm template_name = 'posts/new_post.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): post = form.save(commit=False) post.person_id=request.user.id post.save() if post is not None: return redirect('posts:detail', post.id) and my submitting form is as follow: <form class="form-horizontal" role="form" action="{% url 'posts:detail' pk=1 %}" method="post"> {% csrf_token %} {% include 'form-template.html' %} <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-success"> Add the post </button> </div> </div> </form> if i put an empty action "" or I change the url to another view or I remove the pk in the form I get … -
Django ORM and displaying many to many fields in template
I am having trouble displaying data from a many-to-many field on my template. My models looks like so: class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() password = models.CharField(max_length=255) class Secret(models.Model): message = models.TextField(max_length=1000) posted_by = models.ForeignKey(User) all_likes = models.ManyToManyField(User, related_name="all_users") objects = SecretManager() When a user clicks a like button, the user is associated with the secret via the all_likes field. In my template, I am displaying all secrets, then a "delete" button if the session ID is equal to the posted_by user ID. Now all I'm trying to do is add the text "you liked this" if the secret's all_likes contains the user, but nothing i'm doing is right. <table> {% if secrets %} {% for secret in secrets %} <tr> <td>{{secret.message}}</td> <td>{{secret.created_at}}</td> {% if request.session.id == secret.posted_by.id %} <td>You posted this</td> <td> <form action="{%url 'secrets:delete_secret' id=secret.id %}" method="POST"> {% csrf_token %} <input type="submit" name="delete" value="delete"> </form> {% endif %} {% if request.session.id != secret.posted_by.id %} <td> <form action="{%url 'secrets:create_like' user_id=request.session.id secret_id=secret.id %}" method="POST"> {% csrf_token %} <input type="submit" name="Like" value="Like"> </form> {% endif %} ////HERE I WANT TO ADD LOGIC TO DiSPLAY "YOU LIKED THIS" IF REQUEST.SESSION.ID IS EQUAL TO SECRET.ALL_LIKES.USER.ID//// </td> </tr> {% … -
Is it okay to use patch for full update instead of put?
I am using Django and DRF for APIs. Suppose I have an object with three fields (name, password, email). When a user wants to update his name, password and email at the same time, is it okay for me to send a PATCH request instead of a PUT request? What are the downfalls? I feel this is more convenient than checking if the user is updating all fields, and if he is, using a PUT request, but if he's not, using a PATCH. Checking if the object exists is already taken care of, and when creating objects, I use CREATE / POST instead of PUT because it is more convenient for me. -
Xam.Plugin.Media convert to uploadable type
I'm trying to upload image from mobile device to server(django server) using RestShap. what i am stuck at is how i can convert Xam.Plugin.Media result as an uploadable type. on option is converting to byte array. just to be clear i'm using PCL and cannot use System.IO.File ~ would it be just possible to pass MediaFile(from xam.plugin.media)type through RestSharp? would it manage is itself? just tell me your thoughts. -
Proper way to set aggregation and annotation in model.py and admin.py
I'm using annotation for the simplest case possible - counting objects. I want to be able to sort by those annotated fields as well as access them directly. My code is models.py: class ClientGroupManager(models.Manager): def get_queryset(self, *args, **kwargs): qs = super(clientGroupManager, self).get_queryset( *args, **kwargs ) return qs.annotate( client_count=models.Count('clients') ) class ClientGroup(models.Model): objects = ClientGroupManager() name = models.CharField(max_length=128) in admin.py: class ClientGroupAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'client_count') # def client_count(self, instance): # return instance.client_count # client_count.admin_order_field = "client_count" When it's run as is it breaks on The value of 'list_display[3]' refers to 'client_count', which is not a callable It works only when I uncomment the code which is currently commented. Is there a better way of doing this ? Commented part seems a little redundant, especially when clientgroup.client_count with clientgroup as a example ClientGroup, works just fine. -
Method Not Allowed (POST) - code 405 and blank page
I create login page with html form: <form method="post"> {% csrf_token %} <input type="text" name="loginInput" id="loginField" placeholder="Login" required="required" class="form-control"/><br/> <input type="password" name="passwordInput" id="passwordField"maxlength="30" placeholder="Hasło" required="required" class="form-control"/><br/> <input type="submit" value="Zaloguj się" class="loginbtn btn-primary btn-lg btn-block"/><br/><br/> </form> and with forms.py: from django.contrib.auth.models import User from django import forms class AuthForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] and of course views.py: class UserFormView(View): form_class = AuthForm template_name = 'music/registration_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('users:index') But when click submit button app return blank page with this: Method Not Allowed (POST): / [05/Mar/2017 00:15:55] "POST / HTTP/1.1" 405 0 Anybody can help me find where I do make mistake? Thanks -
Same value from the interactive shell
def unittest(execute=False): with timetravel(datetime(2017,03,01)) as now: loan2 = compute_loan(user, {'product_id': 1, 'frequency': '1week', 'first_debit_date': now }) if not execute: print('You are wrong') pass else: field_list = CustomerProduct._meta.get_fields() mylist = [] exclude = ['id','contract', 'actor_actions', 'locked', 'description', 'target_actions', 'action_object_actions', 'created', 'modified', 'request', 'withdrawal_first_date', 'deposit_date'] table = Texttable(max_width = 6000) for field in field_list: if field.name not in exclude: mylist.append([field.name, getattr(loan2.request.customer_product, field.name)]) table.add_rows(mylist) print(table.draw()) With this function, I created a list of list containing field.name and getattr(loan2.request.customer_product, field.name). For example, +----------------------------------------------------+---------+ | debit_frequency | 1week | +----------------------------------------------------+---------+ | broker_pmt | 17.865 | +----------------------------------------------------+---------+ | broker_pre_withdrawal_daily_interest_rate | 0.001 | +----------------------------------------------------+---------+ | broker_total_post_pre_withdrawal_interest_amount | 139.908 | +----------------------------------------------------+---------+ The problem is I prefer something like +----------------------------------------------------+-----------------+ | debit_frequency | u'1week' | +----------------------------------------------------+-----------------+ | broker_pmt | 17.865903434 | +----------------------------------------------------+-----------------+ | broker_pre_withdrawal_daily_interest_rate | 0.0014348934 | +----------------------------------------------------+-----------------+ | broker_total_post_pre_withdrawal_interest_amount | 139.9083498304 | +----------------------------------------------------+-----------------+ In fact, those values are the same when I query the database with something like In [7]: loaner.request.customer.sum_new_pmt Out[7]: 56.000121522936645 I would like the returning value from the interactive shell. Could anyone help me with this issue? What could I modify in the code? -
Django private messages notification
How this real time notification works? Something like notification in Facebook. I have a webpage in Django. And user A send a message to User B. And this works in my project but user B see the message notification (You have a message) onlny when he refreshes the page. How to do this in real time? User A send a message, user B has opened webpage and when message has been sent User B automaticaly see that he has new message (without refresh the page). I can send a ajax request every second from client to server to 'ask' server that does client have a new message. But I think - this is not much efficient and there is a best way to do this. -
Django won't serve my static files
In settings.py, part of my code sets the static url. STATIC_URL = '/static/' My static files and folders are at /home/myLinuxUsername/myApp/static/interactive-preview-dependencies. That has the folders containing CSS, JS and images. It has the folders images, scripts and stylesheets. My urls.py's urlpatterns is like this: urlpatterns = [ # .. SOME CODE HERE .. url(r'^interactive/$', interactive), ] My views.py is like this: def interactive(request): t= get_template('interactive/index.html') return HttpResponse(t.render()) And here's an example of how I try to load CSS on interactive/index.html: <link rel="stylesheet" href="{% static "interactive-preview-dependencies/styles/main.css" %}"> When I run python manage.py runserver and go to localhost:8000/interactive, the terminal gives me this error: "GET /static/interactive-preview-dependencies/styles/main.css HTTP/1.1" 404 1757 How do I fix this so Django finds and loads the CSS? -
django.db.utils.OperationalError: (1054, "Unknown column 'questionmodel_ptr_id' in 'field list'")
I'm using django with mariadb and I'm trying to save entries into database through ajax and with test model that doesn't use inheritance it works fine but with the models I've created that use inheritance it doesn't let me create any and my ajax request returns an error. In logs it says: django.db.utils.OperationalError: (1054, "Unknown column 'questionmodel_ptr_id' in 'field list'") Here's my model: class QuestionModel(Model): objects = InheritanceManager() class MCQQuestionModel(QuestionModel): title = CharField(max_length=500, blank=False) answers = ListCharField(max_length=255, correct = CharField(max_length=255, blank=False) score = PositiveIntegerField() My function in views: def validate(request): a1 = request.GET.get('a1') list = request.GET.get('list') t = request.GET.get('title') m = MCQQuestionModel.objects.create(answers=list,correct=a1,title=t); data = { 'is_taken': 'okay' } return JsonResponse(data) This is from migrations: migrations.CreateModel( name='MCQQuestionModel', fields=[ ('questionmodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='app.QuestionModel')), ('title', models.CharField(max_length=500)), ('answers', django_mysql.models.ListCharField(models.CharField(max_length=255), max_length=255, size=None)), ('correct', models.CharField(max_length=255)), ('score', models.PositiveIntegerField()), ], Am I creating the objects in the wrong way or is there something missing? -
Django creating a new variable from an existing model field entry
This is a small example for what I'm trying to do. Let's say I have a charField in my model name = models.charField(max_length=50) What do I do if I want to create a new variable called lowercase_name, from the text entered in name. Obviously lowercase_name = name.lower() in the model doesn't work, because it is a field and not a string yet. Would I do this in the view then? If so how? Say there are 100 instances, so 100 different names, I also want a lowercase_name that corresponds with each name, without having to fill out a field. I'm new to Django and trying to figure this out. It would eventually have to be passed to a template so I could access both Person.name and Person.lowercase_name -
How to store a null value in mongodb via mongoengine?
I'm using django with mongoengine and here is the point that confuses me: How do I achieve {name: null} to be stored in mongoDB. It's easily doable via mongo shell, however I can't find the way of doing this via mongoengine models. Moreover, class Person(Document): name = StringField(null=True) seems like null argument doesn't do anything. 1. model: class Person(Document): name = StringField() usage: person = Person() person.save() result in mongoDB: { "_id" : ObjectId("...") } 2. model: class Person(Document): name = StringField(null=True) usage: person = Person(name=None) person.save() result in mongoDB: { "_id" : ObjectId("...") } 3. model: class Person(Document): name = StringField(null=True, required=True) usage: person = Person(name=None) person.save() result in mongoDB: ValidationError (Person:None) (Field is required: ['name']) Question: What's the role of null argument parameter? And how to achieve storing a null value in mongoDB via mongoengine? -
Calculating Model Fields from
I would like to ask a user for a single piece data in a single field inside a CreateView and from that field calculate the values of the remaining model fields. So instead of asking them for all the data, I can just ask for one thing and calculate the rest. A basic example: Model.py class EggCount(models.Model): crates = models.IntegerField() cartons = models.IntegerField() eggs = models.IntegerField() Views.py class EggCountCreateView(generic.CreateView): model = models.EggCount fields = ['crates'] template_name = 'egg_form.html' The associated math that I want to use to fill out the 'cartons' and 'eggs' fields in the model. cartons = crates * 50 eggs = cartons * 12 Where does this math go in Django? In the model? As part of the form_valid function in the view? Should I keep it separate somehow call it from the model or the view? Sorry but I am completely lost and having a hard time finding a clear answer to the best approach for this. -
PythonAnywhere WSGI error
in spite of my best efforts in the past weeks I've been stuck at deploying the WSGI file on Pythonanywhere while trying to set up a django framework. There are similar topics on here, but none were adoptable to my case. I'm following this tutorial. Here's my WSGI file: import os import sys path = '/home/iamcsongor/my-first-blog/firstweb' # use your own PythonAnywhere username here if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(get_wsgi_application()) I've taken a few screenshots of the code, if you could help, I'd be grateful. Thanks -
Django model variable pointing at a function not working
I have the following: class College(models.Model): url_name = create_url_name() def create_url_name(self): return self.name.lower().replace("the", "").strip().replace(" ", "_") But when I run it I get the following error: NameError: name 'create_url_name' is not defined All I'm doing is calling a function I made, how come it doesn't work? -
Returning value from the interactive shell
def unittest(execute=False): with timetravel(datetime(2017,03,01)) as now: loan2 = compute_loan(user, {'product_id': 1, 'frequency': '1week', 'first_debit_date': now }) if not execute: print('You are wrong') pass else: field_list = CustomerProduct._meta.get_fields() mylist = [] exclude = ['id','contract', 'actor_actions', 'locked', 'description', 'target_actions', 'action_object_actions', 'created', 'modified', 'request', 'withdrawal_first_date', 'deposit_date'] table = Texttable(max_width = 6000) for field in field_list: if field.name not in exclude: mylist.append([field.name, getattr(loan2.request.customer_product, field.name)]) table.add_rows(mylist) print(table.draw()) With this function, I created a list of list containing field.name and getattr(loan2.request.customer_product, field.name). For example, +----------------------------------------------------+---------+ | debit_frequency | 1week | +----------------------------------------------------+---------+ The problem is I don't want the value 1week, but rather u'1week'. I would like the returning value from the interactive shell. Could anyone help me with this issue? What could I modify in the code? -
Alternative nullif in Django ORM
Use Postgres as db and Django 1.9 I have some model with field 'price'. 'Price' blank=True. On ListView, I get query set. Next, I want to sort by price with price=0 at end. How I can write in SQL it: 'ORDER BY NULLIF('price', 0) NULLS LAST' How write it on Django ORM? Or on rawsql? -
for loop, cant get data from database, django
I have couple of jurnal edditions with corresponds to some years. To get the data from the database i have wrote a view def arkchive(request): years = {} for year in YearPub.objects.all().order_by('year_alias'): years[year.yearpub_int] = {} for vipusk in Vipusk.objects.all(): years[year.yearpub_int][vipusk.vipusk_alias] = Vipusk.objects.filter(vipusk_year=year).order_by('vipusk_alias') args = {} args.update(csrf(request)) args['years'] = sorted(years.items()) return render_to_response('arkchive.html', args) I have created a model wich looks like this: class Vipusk(models.Model): vipusk_int = models.PositiveSmallIntegerField(verbose_name='Номер випуску') vipusk_alias = models.SlugField(verbose_name='АЛИАС випуску') vipusk_year = models.ForeignKey(YearPub, verbose_name='Випуск/ГОД ') class Meta: ordering = ['vipusk_alias'] verbose_name = 'Номер випуску' verbose_name_plural = u'Номери випусків' def __str__(self): return '№ ({})'.format(self.vipusk_alias) def __unicode__(self): return '№ ({})'.format(self.vipusk_alias) And the part of the code that corresponds to visualization from the database {% for year, vipusks in years %} <div class = 'pub_year'>{{year.year_int}}</div> {% for vipusk in vipusks %} <li class='jurnal_item'><a href='/main/zmist/{{year.year_int}}/{{vipusk.vipusk_alias}}/'>№ {{vipusk.vipusk_id}}({{vipusk.vipusk_alias}})</a></li> {% endfor %} {% endfor %} But as soon as i run the application, my html template shows nothing.Please give me a hint where is my mistake -
Why PasswordChangeForm isn't valid?
As i wrote in subject. I am working on password changing by logged in user, I am Django's newbie, and I can't find any good tutorial about PasswordChangeForm usage, therefore I am asking you to tell me how to create this form's object, properly, to make it valid. Here's my code, note that I am providing proper data (I've checked and old_password is valid), old_password, new_password1, new_password2. I paste here just backbone of my password_change function. I've modified it to see better, whether form is valid and what's happening. Thanks in advance for help. @login_required(login_url="/login/") def password_change(request): if request.method == 'POST': form = PasswordChangeForm(request.POST) if form.is_valid(): return HttpResponse("TRUE") else: return HttpResponse("FALSE") else: user = request.user form = PasswordChangeForm(user=user) return render(request, 'account/password_change.html', {'form': form}) -
Dockerfile - how do I pass passwords from a file into ENV variables?
I want to store all the confidential environment variables - POSTGRES_PASSWORD, SECRET_KEY, etc, in a separate file, so that they don't get committed to github. How can I include these variables into the Dockerfile, so that I could use them to run migrations and stuff like that? -
Location database model for breadcrumb on a website using Django
I am designing a website that has a location of events as part of the information stored and displayed. The location can be a continent, country, state/department, or a city. When an event is displayed, I would like the breadcrumb to be generated for that event. For example if the event was in Paris: Europe / France / Île-de-France / Paris Each item in the breadcrumb is clickable and will bring up a list of events for that location. It will NOT bring up events for its children regions. I would like to make the database design compatible with Django and its models and admin functionality. I also do not want to load all the location tables with countries, regions, and cities that are not going to be used. I would like to add them to the database as an event is generated that needs a new location. My original thoughts were tables for each type of location and then have four columns in the event table that are nullable. The location type associated with the event would be determined by which location column is NOT NULL. Event: name varchar continent_id int NULL country_id int NULL region_id int NULL city_id … -
Django manytomany with extra field - in some cases
My db structure looks like this: Person name Group name PersonGroup id person_id group_id InvitedPersonGroup person_group_id invited_reason Person and Group has many to many relation through PersonGroup, However sometimes the relation will be unique since those people got an invite, and the relation should be through InvitedPersonGroup. How can I use through by dynamically? class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='PersonGroup or InvitedPersonGroup') def __unicode__(self): return self.name -
NoReverseMatch at /
I'm getting a NoReverse match error. I've read several posts about this to find the answer, but I'm not seeing a solution. This is a simple blog webapp for displaying posts in chronological order. The error is related to the edit_post function in "views.py." My suspicion is that the error has to do with trying to store the posts.id as an argument when modifying the post. I've tried removing the post.id in the offending line below and it will load the page. The problem is that if I do that, I cannot load the page for editing specific posts after that. I don't understand what am I missing. I've looked at a number of posts dealing with this error, and I cannot identify the problem with my specific scenario. Any help is very much appreciated. My error: NoReverseMatch at / Reverse for 'edit_posts' with arguments '('',)' and keyword arguments '{}' >not found. 1 pattern(s) tried: ['edit_posts(?P\d+)/'] Here is the offending line in the home page, "index.html": <p> <a href="{% url 'blogs:edit_posts' posts.id %}">edit post</a> </p> Index view: def index(request): """The home page for Blog.""" posts = BlogPost.objects.order_by('date_added') context = {'posts': posts} return render(request, 'blogs/index.html', context) My "urls.py": urlpatterns = [ …