Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to trigger an action after model and related m2m (groups) fields are saved?
How to do something after a Django user model save, including related changes to m2m fields like django.contrib.auth.models.Group? Situation I have a custom Django user model and want to trigger some actions after a user instance is - with related changes such as m2m group memberships - successfully saved to the database. The use case here is a Wagtail CMS where I create ProfilePages for each user instance. Depending of the group memberships of the user instance, I need to do something. Problem In a custom model save() method, I'm not able to reference the changed group memberships, as m2m's are saved after the saving of the user instance. Even if running my custom function after the super().save() call, new group memberships are not yet available. But I need to get the new group memberships in order to do something depending of the new groups for that user. What I've tried Custom model save() # file: users/models.py class CustomUser(AbstractUser): super().save(*args, **kwargs) do_something() Signal post_save As the above simple save() method did not do the trick, I tried the post_save signal of the user model: # file users/signals.py @receiver(post_save, sender=get_user_model()) def handle_profilepage(sender, instance, created, **kwargs): action = 'created' if created else … -
Pass Arrays form views to template and access them
I passed two arrays from views.py to templates. Those arrays are: uploaders = ['mjadidi', 'jaykaron', 'CIDCO'] batchtes = [{'start_time': datetime.datetime(2017, 12, 11, 18, 37, 7, 68000), 'end_time': datetime.datetime(2017, 12, 11, 18, 53, 26, 68000), 'id': 1}, {'start_time': datetime.datetime(2017, 4, 10, 16, 58, 52), 'end_time': datetime.datetime(2017, 4, 10, 20, 38, 35), 'id': 2}, {'start_time': datetime.datetime(2018, 10, 12, 14, 7, 27, 68000), 'end_time': datetime.datetime(2018, 10, 12, 19, 45, 11, 68000), 'id': 3}] What I can do is to access the contents like {% for batch in batches %} {{ batch.id }} {% endfor %} or {{ uploaders.1 }} How can I access the uploader for the specific batch? It should be something like: {% for batch in batches %} {{ uploaders.(batch.id) }} //Needs help here {% endfor %} -
Why I have redirect/refresh with Ajax
I try use Django with XMLHttpRequest, try submitting without refresh page. But I have refresh and don't understand what I doing wrong. This my form > name, email, address, text order_create.html <h2>Create order</h2> <form method="POST"> {% csrf_token %} {{form.as_p}} <button id="button">Submit</button> </form> After I try use Javascript with XMLHttpRequest var button = document.getElementById('button'); button.onclick = function() { var xhr = new XMLHttpRequest(); var body = 'name=' + name + "&email=" + email + "&address=" + address + "&text=" + text; # this code don't work/haven't any alert, only redirect with "{}" xhr.onload = function() { if (this.status == 200) { alert('SUCCES'); # here will be code with innerHTML } else { alert('ERROR'); } } xhr.open('POST', '/order/', true); xhr.send(body); } urls.py urlpatterns = [ url(r'^order/$', views.order_create, name='order_create') ] views.py def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) response_data = {} if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity'] ) cart.clear_session() return JsonResponse(json.dumps(response_data), content_type="application/json", safe=False) else: form = OrderCreateForm() return render(request, 'orders/order_create.html', {'cart':cart, 'form':form}) Server return "POST /order/ HTTP/1.1" 200 and order create, but I have redirect /order/ empty page with "{}". I need output ssucces code without refresh/redirects, but how? -
Django: How to conditionally filter on foreignkey
Suppose I have some classes as follows: from django.db import models APPROVED = '1' REJECTED = '2' REVIEW_STATUS_CHOICES = ( (APPROVED , 'Approved'), (REJECTED, 'Rejected'), ) class Publication(models.Model): name = models.CharField() class Article(models.Model): publication = models.ForeignKey(Publication) content = models.TextField() class Review(models.Model): date = models.DateTimeField() article = models.ForeignKey(Article) status = models.ChoiceField(choices=REVIEW_STATUS_CHOICES) Suppose we want to highlight "really good" publications, which we're defining as ones where any article was immediately approved upon review. How can I get a count of Publications where any of the first (ie earliest value for Review.date) reviews for an article was status Approved? -
Creating routers for multiple database in Django
I am developing a Django application in which I need several databases, one for each user of the system. For this I defined the databases like this: DATABASES = { 'default': {}, 'primary': { 'NAME': 'primary', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'pass', }, 'user1': { 'NAME': 'user1', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'pass', }, 'user2': { 'NAME': 'user2', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'pass', }, } In which the database user1 and user2 are replicas of the structure of primary. Let's say I created two superusers, with the logins 'superuser1' and 'superuser2'. How do I define that when 'superuser1' is logged the data is changed in the database 'user1' and when 'superuser2' is logged the data in the database 'user2' is changed? -
Start Celery worker on production. Using Django/Python on Azure/linux app service
I have a website with an API that customers can send their API-post-calls. These API's have attachments in form of a PDFs or similar that gets stored in a folder /MEDIA/Storage/. The app is written in Django. The API-call gets stored in a model through DRF and serializers. After the data is stored some logic is done, emails os sent, lookups and storing in data-tables etc. Since this takes so much time. I implemented Celery (Azure Cache for Redis as Broker) in my app, so that only the first storage in model is done as usual. The rest us queued up through Celery. This works well on my local machine (mac os). But not on production (Azure/Linux). I have tried git hooks, but i cannot get it working. I have tried some terminal through ssh on the azure VM, but no luck... settings.py CELERY_BROKER_URL = 'redis://:<password>=@<appname>.redis.cache.windows.net:6379/0' CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hapionline.settings') app = Celery('hapionline') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) views.py class ProcSimpleList(generics.CreateAPIView): # Endast Create för att skapa en proc serializer_class = ProcSimpleSerializer permission_classes = (IsAdminOrReadOnly,) lookup_url_kwarg = 'proc_id' def perform_create(self, serializer): … -
Which library is used for importing RadioInput (widgets) in forms.py in Django?
I am using radio buttons for user input in forms.py.I have the following fields: from product.models import Rating from django.forms import forms from django.forms.fields import ChoiceField from django.forms import ModelForm from django import forms class RatingForm(forms.ModelForm): class Meta: model = Rating fields = ('product', 'user', 'rating') widgets = forms.ChoiceField(widget=forms.RadioInput(), required=True) Model.py class Rating(models.Model): CHOICES = ( ('5-stars', '5-stars'), ('4-stars', '4-stars'), ('3-stars', '3-stars'), ('2-stars', '2-stars'), ('1-stars', '1-stars'), ) product=models.ForeignKey(Product,null=True,blank=True, on_delete=models.PROTECT) user=models.ForeignKey(User,null=True,blank=True, on_delete=models.PROTECT) rating=models.ChoiceField(choices=CHOICES, max_length=128) I didn't find any library for importing this widget. Below is the error i am facing: AttributeError: module 'django.forms' has no attribute 'RadioInput'? Please if any one can help? Or suggest any other way to do this? -
How to update model's table using a dicitonary in Django
I can't seem to update the Results table in Django using a dictionary, it may be that i need to include the username as the key, but i dont know how to do this? in func.py from django.contrib.auth import authenticate from django.contrib import messages from django.views.decorators.csrf import csrf_protect from .forms import SignUp from .models import Table, Results from django.contrib.auth.models import User from .serializers import TableSerializer, SessionAvgSerializer, ResultsSerializer curArr=[GBP,EUR] def calc(curArr, user_results, username): results = {} specs = {'GBP': 1,'USD': 2, 'EUR': 3} for item in curArr: if item in specs: results[item] = specs[item] for (key, value) in results.items(): setattr(Results, key, value) Results.save() return(results) in models.py class Results(models.Model): Currency = models.CharField(max_length=32) Value = models.IntegerField() Units = models.CharField(max_length=4) user = models.ForeignKey(User, on_delete=models.CASCADE) To see the Results table updates with: Username | Currency | Value | Units| GBP 1 EUR 3 but i get this instead: Results.save() TypeError: save() missing 1 required positional argument: 'self' -
How do you run multiple django wsgi sites in apache?
I see similar questions have been posted, but nothing seems to fix my problem. I can get multiple virtual hosts running but when I set my site to debug=False, the other sites attempt to use the previous site settings. So it appears my daemon mode is not working. I have multiple virtual envelopes for each site. Here is my virtual host setting: <VirtualHost *:80> # Admin email, Server Name (domain name), and any aliases ServerAdmin me1@gmail.com ServerName <project>.org ServerAlias www.<project>.org # Index file and Document Root (where the public files are located) DocumentRoot /var/www/webapps/<project> # WSGIApplicationGroup %{GLOBAL} # WSGIScriptAlias / /var/www/webapps/oh_joy/oh_joy/application.wsgi WSGIScriptAlias / /var/www/webapps/<project>/<project>/wsgi.py <Directory /var/www/webapps/<project>> Require all granted </Directory> # Log file locations LogLevel warn ErrorLog /var/www/webapps/<project>/log/error.log CustomLog /var/www/webapps/<project>/log/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =www.<project>.org [OR] RewriteCond %{SERVER_NAME} =<project>.org RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost *:443> # Admin email, Server Name (domain name), and any aliases ServerAdmin me1@gmail.com ServerName <project>.org ServerAlias www.<project>.org # Index file and Document Root (where the public files are located) DocumentRoot /var/www/webapps/<project> WSGIApplicationGroup %{GLOBAL} # WSGIScriptAlias / /var/www/webapps/oh_joy/oh_joy/application.wsgi WSGIScriptAlias / /var/www/webapps/<project>/<project>/wsgi.py WSGIDaemonProcess <project>.org python- home=/usr/local/venvs/<project>-env python-path=/var/www/webapps/<project> WSGIProcessGroup <project>.org <Directory /var/www/webapps/<project>> Require all granted </Directory> # Log file locations LogLevel warn ErrorLog /var/www/webapps/<project>/log/error.log CustomLog /var/www/webapps/<project>/log/access.log combined … -
What is the difference between graphene.Node and graphene.relay.Node?
I try to understand Graphql in django and use graphene and graphene_django. My frontend will probably be built with Vuejs and Apollo client. All the tutorials on the internet are about wether classic Graphql or Relay. Relay with its Nodes and Edges seem to be advised (is it ?) But Node and Edges are available in django with wether graphene.Node or graphene.relay.Node. Is there any difference between these two ? I'd like to ask another question : Is it a good practice to use node and edges, even though I wont use Relay/React ? Apollo docs are all about classic Graphql. Regards -
Getting 403 when trying to launch a django test site with nginx
I have a django site that resides in the following directory: /home/sgoodman/insta and configured the /etc/nginx/sites-available/insta the following way. server { listen 80; root /home/sgoodman/insta; index index.html; server_name 192.168.236.149; } Since I am in testing things out phase I set permissions to 777 in both /var/www and /home/sgoodman/insta I am currently getting a 403 when I try to launch the page. Django automatically uses port 8000 when I do python manage.py runserver but when I try to running with python manage.py runserver 80 it says port already in use. How do I launch a django app with nginx? I was trying to follow this tutorial. https://linuxconfig.org/how-to-setup-the-nginx-web-server-on-ubuntu-18-04-bionic-beaver-linux -
Django Q Query Combination
I have a Django-ORM filter that reduces a set of entries by an entered name in a name field from a web form using the get method. from django.db.models import Q residents = residents.filter( Q(first_name__contains=request.GET.get('name')) | Q(last_name__contains=request.GET.get('name')) ) This works perfectly fine if a user enters either a first or last name, but if they enter the full name of someone, naturally this search would fail, how do I amend for this? For example, let's say I have a person named John Smith in my DB. Apart from changing the way my form works to have both a first and last name field, how do I alter my query to provide the correct result when I search for John Smith? -
Accessing URL parameters with python requests in an i-framed app
I am developing an Django app that that needs to consume a third party restful-API. The app itself is accessible after authentication from a portal where is exposed within an i-frame. When you select the app in the portal it redirects to the app url and appends a url parameter "?tokenid". This needs to be retrieved in order to use the third party API which needs to include the tokenid parameter as a cookie. In my app there is a services.py module where I build all API methods to access this third party API, for instance: url='https://www.fooapp.com' token = request.get(url, 'tokenid') cookies = {'session': token } when clicking in the app link from within the main portal the response appends the tokenid parameter: ''https://www.fooapp.com/?tokenid=.eJwty8FqhDAQANB_mbMs2axmjKf-x1JkdCYyEGNxDK0s---V0uM7vBcoSzn0OGF4wb5lMRieMFXNrGUZVyq0yA6fDRznl8AA1S42UJUv5Kq26lIl36ZMRWwXO7bzo1RdKH_TeVOBdwNGax4LrTL-NXSRXJq4jeERKUjybY9eZMZpZu87xIgxCcP_NDHTrVz559rjTI-AQVzXchdSdM57h3Pn7yR9knvLGCj1kSnA-xcnjUmc.XNmOdg.hbtMmT5BkmOkhklP3JqgksDijhc'' then one of the functions to use one the API method is: def get_foo(): url = 'https://thirdparty.com/api/v0/foo/' r = requests.get(url, params=cookies) data = r.json() foos_dict = {foo['name']:foo['id'] for foo in data if 'name' in foo and 'id' in foo} return foo_dict then in my views I call this function etc: class Foo(generic.TemplateView): def get(self, request): foo_dict = services.get_foo() return render(request, 'foo.html', foo_dict) I get this HTTPSConnectionPool(host='wwww.foo.com', port=443): Max retries exceeded with url: /?tokenid (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection … -
Rendering list of forms in Django
I am trying to create a basic personality test in Django as a proof-of-concept at work. I'm new to Django (and python in general), coming at it from a C# .NET background. I am trying to make a list of form objects (populated with information pulled from question objects stored in the database), then display them in the HTML. This is only partly working; I can render the form attributes individually in a for loop (by calling, for example, question.pk) but nothing renders with the standard Django {{ form }} tag, and trying to submit the list of forms breaks the whole thing. I'm pretty sure it's an issue with handling a bunch of form objects populated inside one larger html , but I'm not sure how to go about resolving it. Thanks in advance! DISCQuestionForm in forms.py: class DISCQuestionForm(forms.Form): # create new form object from database question object def __init__( self, pk, disc_query, dom_answer, infl_answer, stead_answer, con_answer, ): super().__init__() self.pk = pk self.disc_query = disc_query self.dom_answer = dom_answer self.infl_answer = infl_answer self.stead_answer = stead_answer self.con_answer = con_answer self.disc_response = forms.DecimalField( max_value=4, widget=forms.NumberInput ) disc_create method in views.py # Create a new DISC assessment for current user def disc_create(request, pk): … -
Database doesn't exist error when trying to connect AWS RDS database to Heroku app in production
I have a Cookiecutter Django app deployed on Heroku. Now I want to use AWS RDS as a database in production. I've set up everything using this question https://stackoverflow.com/questions/35247347/point-heroku-application-to-aws-rds-database and another blog.. So db is created on AWS RDS, root certificate is in my root folder and the heroku variables are set. SSL is enabled on my instance and security groups are set. When I push to Heroku it deploys fine, yet the release command fails throwing this error: django.db.utils.OperationalError: FATAL: database "mydatabasename" does not exist I have tried to troubleshoot this, but couldn't solve it thus far. When I run heroku config --app myapp you can see my variables: DATABASE_URL: postgresql://myusername:mypass@mydatabasename.ce4s6szy2j0h.eu-central-1.rds.amazonaws.com/heatbeat-test2?sslrootcert=rds-combined-ca-bundle.pem DJANGO_ALLOWED_HOSTS: example.de,example.herokuapp.com DJANGO_DEBUG: False DJANGO_SETTINGS_MODULE: config.settings.production POSTGRES_DB: mydatabasename POSTGRES_HOST: mydatabasename.ce4s6szy2j0h.eu-central-1.rds.amazonaws.com POSTGRES_PASSWORD: mypass POSTGRES_PORT: 5432 POSTGRES_USER: myusername PYTHONHASHSEED: random So, I know for sure that the db exists. Si I figured it must be the POSTGRES_DB or the DATABASE_URL that is not correct. I also tried to use postgresas value for the POSTGRES_DB, because the docs say that this is the default name. Yet same error and in fact I set the name of the db to mydatabasename so that should be the correct setting. Or maybe I have … -
Display filtered queryset from ListView
I read that is not feasible to display filtered queries in template cause some logic issues so I decided to use generic ListView insted of simple request rendering. I want to display in td all filtered telephone numbers assigned to the person and his email in next td in main.html template. I just only know that the biggest problem is to write proper return from get_queryset func. That's my code already: models.py class Osoba(models.Model): imie = models.CharField(max_length=40) nazwisko = models.CharField(max_length=50) def __str__(self): return "%s %s" % (self.imie, self.nazwisko) class Telefon(models.Model): osoba = models.ForeignKey(Osoba, on_delete=models.CASCADE, editable=False) telefon = models.CharField(max_length=50) def __str__(self): return self.telefon class Email(models.Model): osoba = models.ForeignKey(Osoba, on_delete=models.CASCADE, editable=False) email = models.EmailField(max_length=100) views.py from .models import Osoba, Telefon, Email from django.views import generic class AddressView(generic.ListView): model = Osoba template_name = 'address_book/main.html' context_object_name = 'osoby_list' def get_context_data(self, *, object_list=None, **kwargs): context = super(AddressView, self).get_context_data(**kwargs) context.update({ 'telefony_list': Telefon.objects.order_by('osoba_id'), 'email_list': Email.objects.all(), }) return context def get_queryset(self): return Telefon.objects.filter(osoba_id='osoba.id') # def main(request): # return render(request, # "address_book/main.html", # {"osoby": Osoba.objects.all, "telefony": Telefon.objects.all, "emaile": Email.objects.all}, # ) main.html <table id="addressTab"> <thead> <tr> <th style="width:50px">ID</th> <th class="thName">Imię</th> <th class="thLastName">Nazwisko</th> <th>Telefon</th> <th>Email</th> <th>Akcje</th> </tr> </thead> <tbody> {% for osoba in osoby_list %} <tr> <td>{{osoba.id}}</td> <td>{{osoba.imie}}</td> <td>{{osoba.nazwisko}}</td> {% … -
Django annotate Count on m2m with condition on m2m fields
Django - 1.11 I need to annotate the count of particular m2m fields of a queryset. Basically - class Message(models.Model): big_model = models.ForeignKey(BigModel, related_name='messages') sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='messages') read_at = models.DateTimeField(null=True, blank=True) I have a BigModel queryset say qs. I want to count the messages which are not read till now and their sender is not the current user. I was trying something of the sort - qs.annotate(unread_messages=Sum( Case( When(messages__sender=user, then=Value(0)), When(messages__read_at__isnull=True, then=Value(1)), default=Value(0), output_field=PositiveIntegerField() ) ) ) But I realized that this is wrong. Any suggestions on how can I annotate unread_messages? -
In Django Forms, how to add a filter to a SelectedMultiple control?
I'm working with Django Forms. In my model, i have a ManyToMany relationship between class X and class Y and Django shows a very annoying MultipleChoice control to edit this relationship. I would like to add a filter so editing the X object the user can filter the Y objects by name while he writes the name to finally select them Some idea about how to do this in Django? -
Reverse for 'register' with keyword arguments '{'billing_cycle': 0, 'pk': ''}' not found. 1 pattern(s) tried:
I am getting the error in the subject line. I have this piece of html code below which I include in 2 templates (i.e. using {% include 'prices.html' %}) in my project. For some reason it works just fine in one template but not the other. When I trying opening the other webpage I get the error in the subject line. <div class="container p-5 row"> <table class="table table-responsive mt-3 w-100"> <thead> <tr> <td scope="col"></td> <td scope="col">Features</td> <td scope="col" class="text-center">X6 Months</td> <td scope="col" class="text-center">X12 Months</td> </tr> </thead> <tbody> <tr> <td class="package-name" scope="row" style="color: #CD7F32;">Bronze</td> <td> <ul class="list-tick text-muted"> <li>Unlimited Search Keywords for Email Alerts</li> <li>1 Email recipient</li> <li>1 Province tenders</li> </ul> </td> <td> <div class="package-price text-center"> <span style="font-size: 22px; color: blue;">R{{ bronze.sixMonthPrice }}</span><span>/Month</span><br> <a class="btn btn-success btn-sm" role="button" href="{% url 'register' billing_cycle=0 pk=bronze.package_id %}">select</a> </div> </td> <td> <div class="package-price text-center"> <span style="font-size: 22px; color: blue;">R{{ bronze.annualPrice }}</span><span>/Annum</span><br> <a class="btn btn-success btn-sm" role="button" href="{% url 'register' billing_cycle=1 pk=bronze.package_id %}">select</a> </div> </td> </tr> <tr> <td class="package-name" scope="row" style="color: #C0C0C0;">Silver</td> <td> <ul class="list-tick text-muted"> <li>Unlimited Search Keywords for Email Alerts</li> <li>5 Email recipient</li> <li>3 Provinces</li> </ul> </td> <td> <div class="package-price text-center"> <span style="font-size: 22px; color: blue;">R{{ silver.sixMonthPrice }}</span><span>/Month</span><br> <a class="btn btn-success btn-sm" role="button" href="{% … -
django migrate error, sqlite version in python3
i'm try to python django tutorial in linux centos7 server. i installed python3, pip, django, virtualenv, sqlite # virtualenv -p python3 venv # source venv/bin/activate (venv) # pip3 install django Successfully installed django-2.2.1 pytz-2019.1 sqlparse-0.3.0 (venv) # django-admin startproject firstdjango # cd firstdjango # python3 manage.py runserver ... LookupError: No installed app with label 'admin'. # python3 manage.py migrate ... django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). problem1. sqlite3 version i already installed latest sqlite3. version is 3.27.2 # sqlite3 --version 3.27.2 # sqlite3.7 --version (backup initial sqlite3) 3.7.17 but in python3, sqlite3 version is still 3.7.17 # python3 -c "import sqlite3; print(sqlite3.sqlite_version);" 3.7.17 how can i resolve this problem? if you need additional information about my centos7 configuration, please reply. thank you. OS Centos7 # python3 --version Python 3.7.3 # pip3 --version pip 19.1.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7) # pip3 list virtualenv Package Version ---------- ------- Django 2.2 pip 19.1.1 pysqlite3 0.2.1 pytz 2018.9 setuptools 40.8.0 sqlparse 0.3.0 virtualenv 16.4.3 # python3 -c "import django; print(django.VERSION);" (2, 2, 0, 'final', 0) # sqlite3 --version 3.27.2 2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0f6d7 # sqlite3.7 --version (backup initial sqlite3) 3.7.17 2013-05-20 00:56:22 118a3b35693b134d56ebd780123b7fd6f1497668 # python3 -c "import sqlite3; print(sqlite3.sqlite_version);" 3.7.17 # python3 … -
Custom Formset :- Assigning foreign key value and inputting a field only once [ Logged in User ]
I have a modelformset to populate the timetable model. Models class Timetable(models.Model): day = models.ForeignKey('Day',on_delete=models.CASCADE) start = models.IntegerField() end = models.IntegerField() period = models.CharField(max_length=12) classteacher = models.ForeignKey('Class_teacher',on_delete=models.SET_NULL) class Class_teacher(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) empid = models.CharField(max_length=10) email = models.CharField(max_length=30) Views class Timetableadding(CreateView): model = Timetable success_url = '/dashboard' form_class = Timetableform template_name = 'newtest.html' def get_context_data(self, **kwargs): context = super(Timetableadding, self).get_context_data(**kwargs) context['formset'] = TimetableFormSet(queryset=Timetable.objects.none()) return context def post(self, request, *args, **kwargs): formset = TimetableFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) def form_valid(self, formset): formset.classteacher = get_object_or_404(Class_teacher, email=self.request.user.email) formset.save() # return super().form_valid(formset) return HttpResponseRedirect('/dashboard') Forms class Timetableform(ModelForm): class Meta: model = Timetable fields = ( 'start', 'end', 'period') TimetableFormSet = modelformset_factory(Timetable, fields=('start', 'end', 'period'),extra=8,) While populating the Timetableform using the createview view the fields start end period in Timetable model is done like a general form. Requirements The webapp has a login feature . When the user ( classteacher ) login they can add timetable. What I want is classteacher field in Timetable(model Form ) should be automatically set as user which is the classteacher. ( Classteacher ) and should be saved in the db after creating the timetable. Classteacher model is updated with respective required fields . I tried passing … -
question about save(update_fields) method nuances , Django
Quick question. Cant find it in documentation or rather there are contradictory information. Does method: save(update_fields = somefields) works by the same principal as method: SomeModel.objects.update(somefields here) in terms that both methods work on the DB level without triggering SAVE method in the model? UPDATE works on a DB level, that's clear What about save(update_fields = somefields)??? Thank you and sorry for rather abstract question -
How to transform a prefetch_related query into database using panda
I would simply like to transform a prefetch_related query into a Panda database with all the information from the two models below. This should be very simple but somehow nothing works. I get a 'Capture_set is not defined' with the code below. Any idea ? class Capture(models.Model): species_name = models.CharField(max_length=50) total_capture = models.IntegerField() class Species(models.Model): species_name = models.ForeignKey(Capture, on_delete=models.DO_NOTHING) length = models.IntegerField() weight = models.IntegerField() data = pd.DataFrame(list(Species.objects.all().prefetch_related(Capture_set))) -
Fresh python 3.7 / django 2.2.1 installation not recognising that mysqlclient is installed
I have a brand new django 2.2.1 project I have just installed into a python 3.7 virtualenv on OS X (10.14.4). After some frustrations I got mysqlclient to install but when I run the django dev server it doesn't recognise that it is installed: Here are the steps I've taken so far: brew install mysql pipenv --three pipenv install django==2.2.1 pipenv install mysqlclient brew uninstall mysql brew install mysql-connector-c pipenv install mysqlclient brew unlink mysql-connector-c brew install mysql django-admin startproject <projectname> Now, the only change I have made to the out-of-the-box django installation is to change the default database backend to django.db.backends.mysql and when I run the django server I get the following: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? However, going back to the virtualenv and doing "pip install mysqlclient" gives: Requirement already satisfied: mysqlclient in /Users/<username>/.local/share/virtualenvs/<projectname>-KrUE_JNo/lib/python3.7/site-packages (1.4.2.post1) Any ideas why django can't see the mysqlclient installed in the virtualenv? I can confirm that all of the above has been run in the virtualenv. I suspect it has something to do with the faff that OSX makes you go through to install it but I'm not sure how to pick it apart. I have also tried to … -
category filed dont appear in api create form
im playing with django rest framework and my problem was category and tags fileds dont appear in api create form or update form, im using ModelSerializer, How can i fixes that please. Hi, im playing with django rest framework and my problem was category and tags fileds dont appear in api create form or update form, im using ModelSerializer, How can i fixes that please. serializers.py # -*- coding: utf-8 -*- from django.utils.safestring import mark_safe from markdown import markdown from users.models import * from rest_framework import serializers from articles.models import * class UserModelSerializer(serializers.ModelSerializer): class Meta: model = Ouser fields = ('id', 'username', 'first_name', 'last_name', 'avatar') class TagModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tag exclude = ['updated_at', 'created_at'] extra_kwargs = { 'url': {'view_name': 'tag-api', 'lookup_field': 'slug'}, } class CategoryModelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category exclude = ['updated_at', 'created_at'] extra_kwargs = { 'url': {'view_name': 'category-api', 'lookup_field': 'slug'}, } class ArticleModelSerializer(serializers.ModelSerializer): author = UserModelSerializer(read_only=True) content_as_markdown = serializers.SerializerMethodField() date = serializers.SerializerMethodField() url = serializers.HyperlinkedIdentityField( view_name='article-api', lookup_field='slug' ) category = CategoryModelSerializer(read_only=True) tags = TagModelSerializer(read_only=True, many=True) class Meta: model = Article exclude = ['updated_at', 'created_at'] def get_date(self, obj): return obj.published_at.strftime("%b %d, %Y") def get_content_as_markdown(self, obj): return mark_safe(markdown(obj.content, safe_mode='escape'))