Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms form.is_valid() replacement
Hi i have a form with 3 input fields Researcher (input text) Study (input text) IRB file (file field) When I submit the form with all the 3 input fields filled the form gives me the correct output on the template page( basically prints the input text of Researcher and Study on the template page and uploads a the IRB file ) But when I only submit the form with 2 input fields filled like researcher and study and keeping the IRB file field empty the post data doesnt work. I know its the form.is_valid() this that if its false it just skips the part inside it. I dont know how to go about it further. My form <form class ="form-group" action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form" enctype="multipart/form-data"> {% csrf_token %} <label>Researcher Name(s):</label> <input type="text" name="researcher" required><br><br> <label>Study Summary</label> <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study" required></textarea> <br><br> <label>Upload your IRB approval letter:<br> We accept PDFs or Word documents</label> <input type ="file" class="file_input" name="irb_file"> <br><br> <input type = "submit" value="Submit" class="btn btn-primary" /> </form> form.py from django import forms class AboutHelp(forms.Form): researcher = forms.CharField(max_length=100) study = forms.CharField(max_length=500) irb_file = forms.FileField(required=False) views.py def about_experiment(request, ex_link_name): researcher = None study … -
Is there a best way to create a custom user model and extend to Profile for production in django? Because I keep getting these error in production
Hi can anyone please highlight the best way to extend a custom user model to a profile or explain what I am doing wrong. I created a custom user model, and extended it to a profile app which all works fine and passes in development. However in production on heroku I kept running into server errors when I click on profile, so I turned debug to True and it saw this traceback; ProgrammingError at /u/profile/ can't adapt type 'MyUser' So I figured, hey probably it's complaining about passing in the whole model instead of the object in the model. However, the filter in my views specifies the object been retrieved be the object related to the requested user. Here's my view below: User = get_user_model() class ProfileUserView(View): def get(self, request, *args, **kwargs): if request.user.is_authenticated(): user = get_object_or_404(User, username=request.user) post_list = Post.objects.filter(author__username__iexact=user).order_by('-submission_time') paginator = Paginator(post_list, 10) page = request.GET.get('page') try: post = paginator.page(page) except PageNotAnInteger: post = paginator.page(1) except EmptyPage: post = paginator.page(paginator.num_pages) profile = Profile.objects.get(user=request.user) template = 'profiles/profile_user.html' context = { 'profile': profile, 'post': post } return render(request, template, context) else: return HttpResponseRedirect(reverse('account_login')) Any help/explanation with regards to what I am doing wrong with retrieving associated data from the profile … -
In Django, is there a better alternative to using "include" 100+ times in the same document?
I made a Django site that lets users search a database and then display results. Each result is an article and for each article you see the title, author, publication date, etc. This information for each result appears in a box I created with CSS to make the result look nice. Since I may alter the look of the box in the future, I want to use it as a template and then "include" it in my results page. But because there could be over 100 results and each result will display the box, I would need to "include" the box over 100 times with code like the following: {% for article in article_results %} {% include 'result_box.html' %} {% endfor %} Is this ok? Is there a better way to do this? -
How to get read committed view of data with Django and Postgres using transaction.atomic()
I am using Django 1.9 with a PostgreSQL database. I am trying, and failing, to use transaction.atomic() to perform a query that sees only data that was committed prior to the beginning of the transaction. For example, in a boiled down case, I do this: Process 1, starts at time t=0 seconds: with transaction.atomic(): time.sleep( 20 ) foo = DeviceRecordProcessed.objects.filter( record_guid = '3' ).first() print foo Process 2, starts at time t=1 seconds: with transaction.atomic(): foo = DeviceRecordProcessed.objects.filter( record_guid = '3' ).first() print foo drp_db = DeviceRecordProcessed( record_guid = '3', device_id = -1 ) drp_db.save() print drp_db Here is what I think should happen: Time 0 - Process 1 starts a transaction - any queries in that transaction should only see data present before time 0 Time 1 - Process 2 begins it's work Time 1.5 - Process 2 creates a record with record_guid '3' and commits it Time 20 - Process 1 performs a query looking for records with record_guid '3' - since no such record existed at time t=0, 0 results should be returned What actually happens: Process 1 sees the record created by process 2 even though that record was created after process 1's with transaction.atomic() block … -
Search functionality django
I've been following the tango with django book and I came across the search chapter using Bing's Search API. I tried to use it but it seems like Bing no longer offers those services. Now I want to make the search functionality local so that it could just search through my categories in the rango app but I don't know how to do this without the Bing search API. Anyone who could help me with a way around it if there is. Thanks in advance. -
Django table rows are being magically hidden from ORM when I set a 'deleted' flag
Working in an inherited codebase. I have a table with 2 objects when I look at it from the API or from the admin site, but it has 3 objects when I do a select * in PostgreSQL. name | created | deleted -------+-------------------------------+------------ Sweet | 2017-07-21 16:31:28.556949-05 | t qwer | 2017-07-21 16:36:03.096954-05 | t asdf | 2017-07-21 16:35:15.585589-05 | f (3 rows) There is a 'deleted' flag in that table which appears to be an automagic soft-deletion flag. If I set the flag true through SQL, it's visible to ORM. If I set the flag false through SQL, it's hidden from ORM. This particular type of automagic is extremely unhelpful and I want to disable it, but I'd like to understand how this works in Django before I go removing the column. I am not using anything special to support this behavior. I have found articles which describe how to achieve soft deletion by subclassing special models that support it, but I'm doing none of that. This is just a vanilla subclass of models.Model. I have Googled and searched through the Django docs and I don't see anything that would indicate that just having a "deleted" column gives … -
How to know what queries django orm is creating while saving data?
I'm new to django and dont know much about sql. I have made a model and its working fine. I'm saving data through django admin with no issues. However I have to save lots of data one by one. Is there a way to know what queries djano is creating when I click save button on django admin? I can dublicate that query and attach data with it. I have installed django_debug_toolbar but even that is not showing sql queries when I save the data. Is there a way to see django orm sql queries WHILE saving the data? Can I log it into the terminal? I'm using postgresql. -
DRF nested serializers - Filtering data on child serializers
I am trying to use nested serializer. How do I use the root serializer to filter data on the grandchild serializer? School and Program have a many to many relationship So that any school can subscribe to any program. Each school has classes and those classes are part of a program, that's why PClass has foreign keys to both School and program. When I call my api .../api/school/1 I want to get all the programs that school subscribes to and which classes are available in each program (in that school) class School(TimeStampedModel, SoftDeletableModel): name = models.CharField(max_length=40) slug = models.SlugField(max_length=40, default='', blank=True) class Program(TimeStampedModel, SoftDeletableModel): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50,default='',blank=True, unique=True) description = models.CharField(max_length=100, blank=True) school = models.ForeignKey(School, blank=True, null=True, related_name="programs") class PClass(TimeStampedModel, SoftDeletableModel): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50,default='',blank=True) description = models.CharField(max_length=100) program = models.ForeignKey(Program, related_name="classes") school = models.ForeignKey(School, related_name="classes") and the following serializers: class SchoolSerializer( serializers.ModelSerializer): programas = ProgramSerializer(source='get_programas',many=True,read_only=True) class Meta: model = Unidade fields = '__all__' lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } class PClassSerializer(serializers.ModelSerializer): class Meta: model = Turma fields = ('name','slug') class ProgramaSerializer(serializers.ModelSerializer): school = serializers.SlugRelatedField(queryset=School.objects.all(), slug_field='name', required=False) classes = PClassSerializer(many=True,read_only=True) class Meta: model = Programa exclude = ('id',) lookup_field = … -
'_TaggableManager' object has no attribute id (is there a way to get the id?) - django
I am currently using django-taggit library for django. I have read the documentation of django-taggit and it does output the name and slugs but is there is a way I can get it to output both name and id at the same time? without going through another query to find it one by one myself Thanks in advance for any help. -
I want to delete the session token generated by uuid for logout feature in python and I am using DJango framework
a function to generate access token for current user `def create_token(self): self.session_token = uuid.uuid4()` this is how its being saved `token = SessionToken(user=user) #SessionToken is model name token.create_token() token.save() response = redirect('feed/') #feed is template name response.set_cookie(key='session_token', value=token.session_token)` -
Docker nginx 502 or 503 error and certbot 404
I am trying to setup a server with cookiecutter-django template and docker on ubuntu sever 16.04. The problem is that I either get a 502 when using www.domain.com and 503 when using domain.com as my domain and the certbot for Let’s Encrypt gets a 404. everthing is behind a nginx-proxy docker container. This is the production.yml: version: '2' volumes: postgres_data: {} postgres_backup: {} services: nginx-proxy: image: jwilder/nginx-proxy:latest ports: - "80:80" environment: - DEFAULT_HOST=cert.local volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - /vagrant/logs/proxynginx:/var/log/nginx postgres: build: ./compose/postgres volumes: - postgres_data:/var/lib/postgresql/data - postgres_backup:/backups env_file: .env django: build: context: . dockerfile: ./compose/django/Dockerfile depends_on: - postgres - redis command: /gunicorn.sh env_file: .env nginx: build: ./compose/nginx depends_on: - django - certbot environment: - MY_DOMAIN_NAME=www.mydomain.nl volumes: - /etc/letsencrypt:/etc/letsencrypt - /var/lib/letsencrypt:/var/lib/letsencrypt certbot: image: quay.io/letsencrypt/letsencrypt command: bash -c "sleep 6 && certbot certonly -n --standalone -d www.mydomain.com --test --agree-tos --email mymail@mail.com --server https://acme-v01.api.letsencrypt.org/directory --rsa-key-size 4096 --verbose --keep-until-expiring --preferred-challenges http-01" entrypoint: "" volumes: - /etc/letsencrypt:/etc/letsencrypt - /var/lib/letsencrypt:/var/lib/letsencrypt ports: - "80" - "443" environment: - TERM=xterm redis: image: redis:3.0 .env file: # PostgreSQL POSTGRES_PASSWORD=testPW POSTGRES_USER=tester # General settings # DJANGO_READ_DOT_ENV_FILE=True DJANGO_ADMIN_URL= DJANGO_SETTINGS_MODULE=config.settings.production DJANGO_SECRET_KEY=mf~+9BiI,LCeJ2Q|L4o55e{_gU>@a=NG;Umt{xMBgR=g&[,m%~ DJANGO_ALLOWED_HOSTS=37.97.203.190 VIRTUAL_HOST=www.mydomain.com # AWS Settings DJANGO_AWS_ACCESS_KEY_ID= DJANGO_AWS_SECRET_ACCESS_KEY= DJANGO_AWS_STORAGE_BUCKET_NAME= # Used with email DJANGO_MAILGUN_API_KEY= DJANGO_SERVER_EMAIL= MAILGUN_SENDER_DOMAIN= # Security! Better to use DNS for … -
Add new record to another field/table in django-autocomplete-light
I have a model with foreign to User(select the user using django-autocomplete-light), and I want to accept names unregister in the databases, but I don't want create a new user, only save the name. How I could implement this? I think have a extra field varchar hided, but I don't know. Sorry for my english, I am not native speaker. Thanks in advance. -
Django will not log until the root logger is used
I have set logger as is commonly suggested in each module: logger = logging.getLogger(__name__) I have a script that is being run through ./manage.py runscript (using django-extensions). I'm not certain if the Django parts are relevant here. I've found that none of the logger instances will log unless I add at least one logging call at the beginning of the script. For example: logger = logging.getLogger(__name__) def run(): logging.getLogger().level = logging.DEBUG # logging.info("START") logger.info("LOGGER START") In this state, nothing logs in the whole system, but if I uncomment the logging.info line, then all modules log. Is there a requirement to "tickle" the root logger this way? -
Cannot override save_model django admin?
I do not understand what I am doing wrong. I want a user to only add the title and description of the Annoucement Model and the rest should be filled automatically. Here is my model: class Annoucement(models.Model): username = models.ForeignKey(User, on_delete=None) title = models.CharField(max_length=500, default="") description = models.TextField(max_length=5000, default="") datetime = models.DateTimeField(default=datetime.now) def __str__(self): return self.title + " " + self.username.username And this is admin.py file. from django.contrib import admin from .models import Profile, Activity, View, Annoucement # Register your models here. class AnnoucementAdmin(admin.ModelAdmin): fields = ['title', 'description'] def save_model(self, request, obj, form, change): obj.username = request.user print("yes") super(AnnoucementAdmin, self).save_model(request, obj, form, change) admin.site.register(Profile) admin.site.register(Activity) admin.site.register(View) admin.site.register(Annoucement) Also, the print("yes") is also not coming on the terminal once I save the model from the admin panel. HELP! -
Error when building Django Website through Visual Studio 2017
I am trying to build a django application in Visual Studio 2017 Enterprise, however I am getting this error... The item metadata "%(FullPath)" cannot be applied to the path "**pathtostatic**\static It is caused by this line in the file Microsoft.PythonTools.Django.targets <DestinationRelativePath>$([MSBuild]::MakeRelative($(QualifiedProjectHome), %(FullPath)))</DestinationRelativePath> I know why the error is happening, but I was wondering if there is a workaround for it. I am using a Microsoft OneDrive folder that has an illegal character (a comma) in the path, as the storage for the code. I tried to rename the company through the Microsoft Admin panel on Office 365 but that did not rename the folder. Any solution to this would be great! Thank you. -
How to get request.user to filter data in django forms?
I have this code: # forms.py channels = Channel.objects.filter(company=user) channel = forms.ChoiceField( choices=channels, widget=forms.Select(attrs={'class': 'form-control'}) ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(MyForm, self).__init__(*args, **kwargs) def clean_channel(self): channel = self.cleaned_data.get('channel') if self.user: return channel But user is not deffined. How to get request.user to filter data in forms? -
Django using many-to-one relationships
I'm completely new to Django web development and I'm having some issues using many to one relationships. I'm trying to complete a coding exercise in which I must develop a database for a game club where there will be a member list and a match list. the member list will store information pertaining to the member (eg. name, date they joined the club, matches won, matches lost, average score) and the match list will store data about each recorded match (eg. who player 1 and player 2 are, what date the match took place and what each players score was). What I was going to do was to use the many to one relationship to link multiple matches to a member and then have the match outcomes be information used to calculate Member information. members/models.py: from django.db import models class Member(models.Model): name = models.CharField(max_length=30) match_wins = models.IntegerField() match_losses = models.IntegerField() date_joined = models.CharField(max_length=10) average = models.IntegerField() high_score = models.IntegerField() matches/models.py: from django.db import models from members.models import Member class Match(models.Model): player1 = models.ForeignKey(Member, on_delete=models.CASCADE) player2 = models.ForeignKey(Member, on_delete=models.CASCADE) p1_score = models.IntegerField() p2_score = models.IntegerField() winner = ???(models.Member_id maybe?) loser = ??? date = models.CharField(max_length=10) As an example, how would I … -
Django and Jquery Grabbing Wrong Data from Model
I'm working on an app that is using Jquery to add totals to two different divs programmatically when a user drops a container into a special div. However, the counter is adding the totals from the wrong container. In my test data I have two draggable containers that look similar to the following: container1: pallets:10 weight:5 container2: pallets:20 weight:1265 But when I drop container1 into the div, it reports pallets of 20 and a weight of 1265. container2 has the reverse. I'm sure the problem is in my jquery, but I can't figure it out. Here is my template code. <div id="wrapper"> <div id="origin" class="fbox"> {% for freight in freight_list %} <span class="freight draggable" data-content=" Pickup Customer: <br/> {{ freight.pu_customer }} <br/> Pickup Datetime: <br/> {{ freight.pu_appt_time|date:'D M d Y @ h:m a' }} <br/> Time Until Pickup: <br/> {{ freight.pu_appt_time|timeuntil }} <br/> Pickup Address: <br/> {{ freight.pu_location }} <br/> Number of Pallets: {{ freight.pallet_count }} <br/> Total Weight: {{ freight.weight }} <br/> Delivery Customer: <br/> {{ freight.del_customer }} <br/> Delivery Address: <br/> {{ freight.del_location }}, {{ freight.del_city }}, {{ freight.del_state }} "> <p>{{ freight.pu_customer }}</p> <p>{{ freight.pu_appt_time|date:'D M d Y @ h:m a' }}</p> <p>{{ freight.pu_appt_time|timeuntil }}</p> <p class="pallet">{{ … -
Crispy forms MultiForm
Is there a way to use django crispy forms with django-betterforms MultiForm which lets you use multiple forms as one big form? I tried defining the layout on each form and then aggregating this into the main MultiForm's layout but this didn't work since it says the MultiForm has no attribute add_prefix. Not sure how to do this or if it's possible. -
i can't store data in database.. Please guide me..
customers_form.html <form> <fieldset class='text-center'> <legend>Create your Account</legend> <div> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token%} {% include 'registration/form-template.html' %} <div class="form-group"> <div align="center" > <input type="submit" class="btn btn-success" value="submit"/> <input type="hidden" name="next" value="{{ next }}" /> </div> </div> </form> </div> <br> <a href="forgot_password.html">Forgot password?</a> </fieldset> </form> form-template.html {% for field in form %} <div class="form-group"> <div class="col-som-offset-2 col-som-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label >{{ field.label_tag }}{{ field }}</label> </div> {% endfor %} app/urls.py from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views app_name = 'registration' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='registration'), url(r'^customer/add/$', views.UserFormView.as_view(), name='customer-add'), ] proj/urls.py from django.conf import settings from django.contrib.auth import urls from django.conf.urls.static import static from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('registration.urls')), url(r'^accounts/', include('django.contrib.auth.urls')) ] views.py from django.views import generic from .models import customers from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.views import View from .forms import UserForm from django.contrib.auth.decorators import login_required class IndexView(generic.ListView): template_name = 'registration/home.html' def get_queryset(self): return customers.objects.all() class UserFormView(View): form_class = UserForm template_name = 'registration/customers_form.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, … -
Adding Methods to a Django Model
I'm building my first GraphQL mutation. Initially I built it using sample code I found. But now I'm refactoring it to be better structured. While the code seems to work fine, as I'm relatively new to Django, I'm not sure the approach I'm using is the best practice for Django/Python. Here's my relevant code: #models.py class Workflow(models.Model): name = models.CharField(max_length=30) description = models.TextField(blank=True, null=True) def __str__(self): return "{}".format(self.name) @classmethod def create(cls, name, description): new_workflow = cls( name = name, description = description ) new_workflow.save() return new_workflow # mutations.py class Workflow(DjangoObjectType): class Meta: model = WorkflowModel interfaces = (relay.Node, ) @classmethod def get_node(cls, id, context, info): node = get_workflow(id) return node class CreateWorkflow(relay.ClientIDMutation): class Input: name = graphene.String() description = graphene.String() workflow = graphene.Field(Workflow) success = graphene.Boolean() errors = graphene.String() @classmethod def mutate_and_get_payload(cls, input, context, info): name = input.get('name') description = input.get('description') try: workflow = WorkflowModel.create(name, description) return CreateWorkflow(workflow=workflow, success=True) except Exception as e: success = False return CreateWorkflow(workflow=None, success=False, errors=str(e)) class Mutation(graphene.AbstractType): create_workflow = CreateWorkflow.Field() My primary question has to do with the way I introduced def create into the Django Workflow model. Is this the proper way to do it? Robert -
How do I display all values of a Django Model record?
In rails I am able to say: painting = Painting.first painting.attributes And this will automatically display all the model's values. Is there an equivalent in Django to do this? -
Django ORM not storing inside try/except block
I have a problem with Django storing objects. When I try to do something inside a try/except block, if everything goes OK, my object is persisted. But if an exception is raised (not because of the object's .save()), nothing is stored. An example: def my_function(raise_exc): MyModel.objects.create(name='name') if raise_exc: raise Exception() return OK case: raise_exc = False try: my_function(raise_exc=raise_exc) except Exception: pass KO case: raise_exc = True try: my_function(raise_exc=raise_exc) except Exception: pass Only in the OK-case, MyModel object is persisted. I can see, by debugging, that in both cases the object is created in RAM memory (MyModel.objects.all() contains it) but not in the database. And if an exception is raised, it looks like it makes a transaction rollback (I am not using transaction blocks. Just in case). I don't know if this is the desired behavior of the ORM. If it is, what can I do to store objects inside a try block, even if after I save them an exception is raised? (let's say that I shouldn't remove that try/except wrapper) -
Django with Apache : Global variable in view.py
please I need some help, I have a web application with classic functionalities for users management (account creation, login,...). my problem is that I am trying to creat an instance of an object "UserObject" (not serializable object) for each user when he connects (login), this object will be used to process user requests in some views, so the object must be accessible from any view, for that i have a global dictionary "users_objects" in view.py that contains all users objects (the dictionary key is the user name and the value is the "UserObject" object), so view.py look lik this : from user_object import UserObject users_objects = {} def login(request): //login control and creation of session and context ...... ...... global users_objects user_name = request.session['name'] users_objects[user_name] = UserObject() return render(request, 'mySite/home.html', context) def request_view(request): param = request.GET.get('parameter', None) global users_objects user_name = request.session['name'] obj = users_objects[user_name] res = obj.process(param) return HttpResponse(str(res)) This approach work fine with django dev-server, but when I configure django with a real production server (apache) the content of the global dictionary "users_objects" disappear and I get an empty dictionary. please, did anyone know why does this happen ?? and what is the best solution to use a … -
How do I turn on Django SQL logging at a specific point in the code?
I want to keep Django SQL logging off, generally, because it's so verbose. But sometimes I want to see the result of a specific section of the code. How do I turn it on and off programmatically?