Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django masks running time errors and discontinues to run remaining code?
Django won't report errors. 2 recent examples here: First, in console: In [23]: if 'a' in page: ...: print(1) TypeError: a bytes-like object is required, not 'str' Second, I forgot to define cate here gi = Info(dept, cate, title, link, pub_date) gi.save() ... In both cases, no error report when running my django code. and the code below was not run. -
Building a ScrumBoard to learn Django Part 2
I am currently learning Django via Youtube, Udemy, and PluralSight so that I can make programs for our non-profit foundation. I'm running into a slew of issues from the stuff I started with from PluralSight. I have encountered yet another problem: queryset = List.objects.all() NameError: name 'List' is not defined I do believe the issue is similar to the other problems, with either another import missing, or maybe this: How can I retrieve a list of field for all objects in Django? For which the solution was: User.objects.all().values_list('username', flat=True) I tried looking up import django, list as well as import django.generic.view, no dice. Im not exactly sure why the flat=True would be required, or if I would need to add a values_list to my code at all, or what a "tuple" is. Can anyone show me where the imports are for django, as well as any advice on a better way to learn the language. Books, online videos, anything that doesnt require me to fix another bug every step would be amazing. -
Django: lazy loading installed_apps
I'm upgrading a project which I'm working on to Django 1.11 from 1.9. It uses a custom register app which inherits from django-registration-redux package. The django-registation-redux package is not inside the installed_apps as adding it tries to install models and fails since the models are installed by the custom register already. Is it possible to prevent apps installing it's models? -
Make Django query with .extra
My aim is to create a query which calculate the absolute value of my field and calculate the average of them as well. I have read about it and I tarted to use the .extra possibility in Django but I couldn't achieve my goals. I attach my attempt ant the desired SQl query too. Thank you in advance. The desired result would be equeal the reult of this PosreSql query: SELECT time_stamp, AVG(ABS(ddt)) FROM tropo WHERE time_stamp BETWEEN '2018-01-16 8:00' AND '2018-01-17 8:00' GROUP BY time_stamp ORDER BY time_stamp My attempt is in Django: Table.objects.all().filter(time_stamp__range=(2018-01-16 8:00, 2018-01-17 8:00)) .extra(select={"ddt_abs": "abs(field)"}) .values('time_stamp') .annotate(avg_field=Avg('field')) How can I reach that my Djanogo query works? -
Django model - dynamically decide which table to user according to model field
I have a Django model, for the example, I will call it Book: class Book(Model): class Meta: db_table = 'book' i need dynamically to change 'db_table' according to book instance attribute for example: when id>100 choose 'book_new' table so for query: Book.objects.get(id=200) 'book_new' will be used. also when creating a new Book (for 'new' attribute): Book(name='ff', new=True).save() a new record is added to 'book_new' (and not 'book') NOTE: i dont want to create new class, i need to use the same class, but to use a Manager(?) or Router(?) in order to choose the right db. -
wkhtmltopdf get CalledProcessError under uwsgi environment
I get a CalledProcessError under uwsgi environment, while I can run it in django normal runserver-mode ,and can run this command directly in command line correctly. here is my environment: Environment: Request Method: GET Request URL: http://x/api/sheet/?order=1784285260 Django Version: 2.0.1 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wkhtmltopdf', 'rest_framework', 'django_crontab', 'backend', 'api', 'website'] Installed 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'] Traceback: File "/www/env/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/www/env/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 158. response = self.process_exception_by_middleware(e, request) File "/www/env/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 156. response = response.render() File "/www/env/local/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/views.py" in rendered_content 78. cmd_options=cmd_options File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/utils.py" in render_pdf_from_template 186. cmd_options=cmd_options) File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/utils.py" in convert_to_pdf 124. return wkhtmltopdf(pages=filename, **cmd_options) File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/utils.py" in wkhtmltopdf 110. return check_output(ck_args, **ck_kwargs) File "/usr/lib/python3.6/subprocess.py" in check_output 336. **kwargs).stdout File "/usr/lib/python3.6/subprocess.py" in run 418. output=stdout, stderr=stderr) Exception Type: CalledProcessError at /api/sheet/ Exception Value: Command '['/usr/local/bin/wkhtmltopdf.sh', '--dpi', '300', '--encoding', 'utf-8', '--margin-left', '20', '--margin-top', '10', '--orientation', 'Landscape', '--page-size', 'A4', '--print-media-type', '--quiet', '--zoom', '0.88', '/tmp/wkhtmltopdf0fjtzvle.html', '-']' returned non-zero exit status 126. and my uwsgi configuration: [uwsgi] vhost = true plugin = python36 socket = /tmp/site.sock master = true enable-threads = true processes = 4 virtualenv = /www/env/ home … -
How to Save a blob in django and Ajax
I have a blob file that I want to save on the backend using Ajax but I keep getting a 404 error and I have no idea what is the issue. This code is in views.py @csrf_exempt def upload(request): if request.method == 'POST' and request.FILES['blob']: audio = request.FILES['blob'] fs = FileSystemStorage() filename = fs.save(audio.name, audio) file_url = fs.url(filename) return render(request, 'upload.html', {'file_url': file_url}) And this is my Ajax request $.post("/main/upload/", { filename: blob.value, }, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); console.log(blob); } Your help will be appreciated :) -
Trying to display a profile edit form for different user types in Django
So I have two account types: student and teacher. I have two forms which hold the information to be updated for each case. Now, student and teacher have different form fields. I want that a student or a teacher could be able to update their profiles, problem is that I need to display different forms for students and teachers. For teacher my view and form work properly, but for student, instead of the student edit form, the teacher form is displayed again.. I tried something but now I get an error like: local variable 'form' referenced before assignment Please have a look here: @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user.email == teacher.email: if request.method != 'POST': form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') else: form = TeacherEditForm(instance=teacher) elif user.email == student.email: if request.method != 'POST': form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') else: form = StudentEditForm(instance=student) context = { "form": form, } return render(request, "registration/profile_edit.html", context) I used email field, because it is unique and is stored in both Student/Teacher and User models. -
Django Forms - dynamic choice field filtering
I am trying to dynamically filter which choices are displayed in a form. the form fields are generated from model. Currently all choices are being displayed without any filters applying. in the view I get the currents site_type then pass this to the form, to filter the subnets that also have the same site_type, or this is whats supposed to happen anyway. can anyone see why the filter would not be applying? forms.py class AutoSubnetForm(forms.Form): subnet_type_data = SubnetTypes.objects.all() def __init__(self, *args, **kwargs): self.site_type = kwargs.pop("site_type") # get site type if set and filter against it if self.site_type: self.subnet_type_data = SubnetTypes.objects.filter(related_sites=self.site_type) super(AutoSubnetForm, self).__init__(*args, **kwargs) # create list for types subnet_types = [] for stype in subnet_type_data: # add tuple for each type subnet_types.append((stype.id,stype.subnet_type)) subnets = forms.MultipleChoiceField( choices=subnet_types, widget = forms.CheckboxSelectMultiple( attrs = {'class': 'form-control'} ) ) views.py @login_required @user_passes_test(lambda u: u.has_perm('config.add_subnet')) def auto_gen_subnets(request, site_id): #generate_subnets(site_id) from config.models import SubnetTypes site_data = get_object_or_404(SiteData.objects.select_related('site_type'),pk=site_id) subnets = None if request.method == 'GET': form = AutoSubnetForm(site_type=site_data.site_type) else: # A POST request: Handle Form Upload form = AutoSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnets = form.cleaned_data['subnets'] return render(request, 'sites/generate_subnets.html', { 'data': subnets, 'form': form, … -
Django - NoReverseMatch - Select form
I have a select form that is supposed to take the user to different program pages. Urls.py url(r'^program_page/(?P<id>\d+)$', views.program_page, name = 'program_page') This is my form HTML <form action= "{% url 'project:program_page' id= *****THIS IS WHAT I NEED HELP WITH. I DO NOT KNOW WHAT GOES HERE FOR THE ROUTE*** %}" method='post'> {% csrf_token %} <br> <select id=options name="function_program"> <option>Choose From List</option> {% for function_program in function_programs %} <option value="{{function_program.program.id}}">{{function_program.program.title}}</option> {% endfor %} </select><br> <input type="hidden" name="id" value="{{function_program.program.id}}"> <input type="submit" value="Go To page"> </form><br> I think that what I need help with is with the action expression. <form action= "{% url 'project:program_page' id= %}" method='post'> I tried <form action= "{% url 'project:program_page' id=function_program.program.id %}" method='post'> amongst several other things but keep getting the reverse no match error. How do I pass the id from the selection to the form action? -
django-registration-redux confirmation email not working
I've been trying for hours to make my django application send confirmation emails after registering but so far have had no luck with various errors. Below is my settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')u#-6zt#-1s_-n_1=w%u8dke8-7$n9qkqagu08(--toc#y27+%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # 'django.contrib.sites', 'lollipop', 'pinpop', 'sweet', 'registration' ] # If True, users can register REGISTRATION_OPEN = True # One-week activation window ACCOUNT_ACTIVATION_DAYS = 3 # If True, the user will be automatically logged in REGISTRATION_AUTO_LOGIN = True # Successful login arrival page LOGIN_REDIRECT_URL = '/index/' # Page not-logged in users are redirected to if trying to access stuff that @login_required LOGIN_URL = '/accounts/login/' # Host for email EMAIL_HOST = 'smtp.gmail.com' # Port for email EMAIL_PORT = 567 # Host user EMAIL_HOST_USER = 'xxxx@gmail.com' # … -
axios.post reactjs Django Restframework
I am posting login throw my django backend with axios.here is my structure in Login.js: class Login extends Component { constructor(props) { super(props); this.state = { username: '', email: '', password: '' } } handleClick(event) { var apiBaseUrl = "/api/login/"; axios.post(apiBaseUrl, { "username": this.state.username, "email": this.state.email, "password": this.state.password } ) .then(function (response) { console.log(response.status); console.log(response); if (response.status === 200) { console.log("Login successfull"); alert('Login Successfull'); } else if (response.status === 204) { console.log("Username password or email do not match"); alert("username password do not match") } else if (response.status === 400) { console.log('noo!!!!!') } else { console.log("Username does not exists"); alert("Username does not exist"); } }) .catch(function (error) { console.log(error); }); }; render() { return ( <div> <MuiThemeProvider> <div> <AppBar title="Login" /> <TextField hintText="Enter your Username" floatingLabelText="Username" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField hintText="Enter your email" floatingLabelText="Email" onChange={(event, newValue) => this.setState({ email: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> </div> ); } } const style = { margin: 15, }; export default Login; so the problem is if the username and email and … -
Django page refresh page on new postgres entry to provide realtime updates to user
I want to automatically refresh / reload the django webpage in the users webbrowser when a new entry is found in the database. Currently i use a meta refresh as a temporary solution. I have installed and am using pgpubsub. So i can get a notification when there is a new item in the database. But how can i trigger django to reload the website? import pgpubsub pubsub = pgpubsub.connect(host="localhost",database="somedb",user="somebody") pubsub.listen('pg_news'); for e in pubsub.events(): print(e.payload) any ideas are welcome -
Heroku and Django - relation does not exist
I have launched an app on Heroku running Django 2.0.1 with a Postgres resource provisioned. My Procfile, after a few iterations, looks like this: Procfile release: python manage.py migrate sites --noinput && python manage.py migrate --noinput web: gunicorn app.wsgi --log-file - When I deploy from GitHub (not from the command line... I haven't deployed from the command line before as it is critical to me that the GitHub deploy works) everything works fine. The migrations run like they should, and the logs confirm that there are no errors when migrating. In fact, there are no errors at all. When I launch the site (forcing it into DEBUG mode to see the errors) I get this error on the front page: ProgrammingError at / relation "posts_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "posts_post" INNER JOIN "u... A similar error exists when trying to load the admin site: ProgrammingError at /admin/login/ relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ I followed the advice in Django: relation "django_site" does not exist to migrate sites first, but that did nothing. Also, this issue on GitHub is related, but was not helpful. To clarify, the app is … -
How to build a xmpp server with Jingle protocol implementation for Audio streaming from an android device within my Python django project
I already have a django based server with exposes a REST API using which my Android app is communicating through POST requests. But now I am exploring a way to stream audio from the android device MIC to my server for further processing to be done on the server. So for this, after a bit of exploration I found about XMPP protocol and it's Jingle protocol extension, which has been used for Vo-IP before, for implementing a audio-streaming to the server. However I am unable to find any library with proper documentation or guide for implementing this XMPP-Jingle stack in my Python server. So I am here, what should I use to implement this? I found this question in SO: XMPP server for Python, which is 1. Dated, and 2. Seems to suggest from what i was able to gather, using some non-python server like 'ejabberd' or 'openfire' and somehow bridging with my server code for my implementation? I haven't worked with this kind of technology before, so if that indirect implementation is my only recourse, then how to do that? I would require documentation/guide for that. Ofcourse, I would highly prefer a way to directly implement this in Python … -
Building a ScrumBoard to learn Django
I am currently learning Django via Youtube, Udemy, and PluralSight so that I can make programs for our non-profit foundation. I'm running into a slew of issues from the stuff I started with from PluralSight. The current problem is I keep getting an error: path(r'^scrumboard/', include('scrumboard.urls')), NameError: name 'include' is not defined Directory: /djangular (the project folder) /djangular/djangular (where my scrumboard directory/manage.py sits) /djangular/djangular/djangular (where urls.py, the file throwing the error sits) The code: from django.contrib import admin from django.urls import path urlpatterns = [ path(r'^admin/', admin.sites.urls), path(r'^scrumboard/', include('scrumboard.urls')), ] So far I have followed the directions to the t, and ran into countless problems, I am assuming this is another one. It initially wanted me to use the word "url" instead of path, which caused failures immediately. Is this another one of those situations, and are there other resources I can use to learn django? This one isnt panning out for me so well, but I really do want to be able to write my own code, and I love the language and the features. Im just not a professional coder. I dont expect my work to be pretty, but I do want to get the job done. I … -
modelformset_factory Raising ImproperlyConfigured Despite Appearing Correct
I'm using python 3.6 and Django 2.0. I have the following model defined: class IncidentInvolvedParty(models.Model): incident = models.ForeignKey(Incident, on_delete=models.CASCADE) officer_signed = models.ForeignKey(Officer, null=True, on_delete=models.CASCADE) party_type = models.CharField(max_length=7, choices=PARTY_TYPE_CHOICES) juvenile = models.BooleanField(default=False) home_address = models.ForeignKey(Address, null=True, on_delete=models.CASCADE, related_name="incident_party_address", blank=True) date_of_birth = models.DateField(null=True, blank=True) sex = models.CharField(max_length=1, choices=SEX_CHOICES) race = models.CharField(max_length=50, choices=RACE_CHOICES) height = models.IntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) hair_color = models.CharField(max_length=20, null=True, choices=HAIR_COLOR_CHOICES, blank=True) eye_color = models.CharField(max_length=20, null=True, choices=EYE_COLOR_CHOICES, blank=True) drivers_license = models.CharField(max_length=100, null=True, blank=True) drivers_license_state = models.CharField(max_length=2, null=True, choices=STATE_CHOICES, blank=True) employer = models.CharField(max_length=200, null=True, blank=True) employer_address = models.ForeignKey(Address, null=True, on_delete=models.CASCADE, related_name="incident_employer_address", blank=True) build = models.CharField(max_length=25, null=True, blank=True) tattoos = models.TextField(null=True, blank=True) scars = models.TextField(null=True, blank=True) hairstyle = models.CharField(max_length=30, null=True, blank=True) and this view function: def create_incident(request, *args, **kwargs): VictimFormset = modelformset_factory(IncidentInvolvedParty, exclude=('id', 'incident', 'party_type')) SuspectFormset = modelformset_factory(IncidentInvolvedParty, exclude=['id', 'incident', 'party_type']) if request.method == 'POST': print(f"request.POST: {request.POST}") victim_formset = VictimFormset(request.POST, prefix="victims") suspect_formset = SuspectFormset(request.POST, prefix="suspects") incident_form = IncidentForm(request.POST) print(f"Victim formset: {victim_formset}") print(f"Suspect formset: {suspect_formset}") print(f"Incident Form: {incident_form}") if incident_form.is_valid() and victim_formset.is_valid() and suspect_formset.is_valid(): incident = incident_form.save() victims = victim_formset.save() suspects = suspect_formset.save() return redirect(f"/cases/{incident.id}") else: print(incident_form.errors) else: incident_form = IncidentForm() victim_formset = VictimFormset(prefix="victims") suspect_formset = SuspectFormset(prefix="suspects") context = {'form': incident_form, 'victim_formset': victim_formset, 'suspect_formset': suspect_formset} return render(request, "cases/create_incident.html", context=context) and this … -
Django Postgresql Heroku : Operational Error - 'FATAL too many connections for role "usename"'
I am running a web application using Django and Django Rest Framework on Heroku with a postgresql and redis datastore. I am on the free postgresql tier which is limited to 20 connections. This hasn't been an issue in the past, but recently I started using django channels 2.0 and the daphne server (switched my Procfile from gunicorn to daphne like this tutorial) and now I have been running into all sort of weird problems. The most critical is that connections to the database are being left open so as the app runs, the number of connections keep increasing until it reaches 20 and gives me the following error message: Operational Error - 'FATAL too many connections for role "usename"' Then I have to manually go to shell and type heroku pg:killall each time, this is obviously not a feasible solution and this is production so my users cant get access to site and get 500 errors. Would really appreciate any help. I have tried: Adding this to my different views in different places from django.db import connections conections.close_all() for con in connections: con.close() I also tried doing SELECT * from pg_activity and saw a bunch of stuff but have … -
Dynamically object creation Django get_or_create()
I am new to Django. So I was exploring it a little bit where I find a method get_or_create() for a model. I am wondering if it is possible like in the Django form. I have a field name category and it is just an input field like Charfield. So whenever user writes a new article I want the suggestions from the previous categories and if it is not there then it should make a new one on the basis of current one. Can anyone suggest me some logic or example. -
Get a list of users along with there group membership?
I want to get a queryset along with their group membership to avoid expensive additional database hits and to make managing stuff in the template much easier. Initially I tried to prefetch the groups a user belongs to: def get_queryset(self): User.objects.filter(is_active=True).prefetch_related('groups') But then it makes it difficult to show and hide things in the template based on the groups: {{ user.groups.all }} gives <QuerySet [<Group: Managers>]> Then I though perhaps an annotation may be better with a is_manager and is_head eg: def get_queryset(self): '''Return both active and inactive users for managers Annotate with is_manager = True/False ''' query = When(groups__name__in=[MANAGER_GROUP_NAME, ], then=Value(1)) return self.model.objects.all().annotate( is_manager=Case( query, default=Value(0), output_field=BooleanField() ) ) Which worked okay but gave me an error: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'my_site.auth_group.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by But would be easy to use in the template with: {% if user.is_manager %} Manager {% else %} Normal user {% endif %} Is there an easier way to do it? -
how to runserver django in window10 subsystem ubuntu?
I command this way. (ubuntu bash in window10 subsystem) $ pip install virtualenv $ cd ~ $ virtual venv $ source venv/bin/activate (venv) $ pip install django (venv) $ django-admin startproject mysite (venv) $ cd mysite (venv) $ python managy.py makemigrations (venv) $ python managy.py migrate (venv) $ python managy.py runserver ... Starting development server at http://127.0.0.1:8000/ ... (in window10) open web-brower enter code here typed in url : http://127.0.0.1:8000/ ... no response.... Is there I miss something? this video show success. https://godjango.com/123-django-with-bash-for-windows/ but my case, Is not work..] -
Form's initial data not being passed through correctly
The form is a single BooleanField, and it lives on a ProfileDetailView, but is split off into its own FormView. I believe I'm passing the initial data by overriding the get_initial method, but it isn't passing through. What am I doing wrong? The field in the Profile model: class Profile(models.Model): public = models.BooleanField(default=False, verbose_name='Public') Here's the DetailView that passes the form through its context: class ProfileDetailView(DetailView): template_name = 'user_profile/profile_detail.html' def get_context_data(self, **kwargs): context = super(ProfileDetailView, self).get_context_data(**kwargs) context['public_toggle_form'] = PublicToggleForm return context And the related FormView which overrides the initial data(the booleanField is the public var): class PublicToggleFormView(AjaxFormMixin, FormView): form_class = PublicToggleForm success_url = '/form-success/' template_name = 'user_profile/profile_detail.html' def get_initial(self): profile = Profile.objects.get(user__username=self.request.user) public = profile.public initial = super(PublicToggleFormView, self).get_initial() initial['public'] = public return initial Here's my forms.py: class PublicToggleForm(forms.Form): public_toggle = forms.BooleanField(required=False) def clean_public_toggle(self): public_toggle = self.cleaned_data.get("public_toggle") if public_toggle is True: print("im True") else: print("public is false here") return public_toggle the profile_detail.html template which includes the form: {% if request.user == object.user %} Make your profile public? <form class="ajax-public-toggle-form" method="POST" action='{% url "profile:public_toggle" %}' data-url='{% url "profile:public_toggle" %}'> {% include 'includes/bs4_form.html' with form=public_toggle_form %} </form> {% endif %} I have since tried changing the form to a modelForm: class PublicToggleForm(ModelForm): … -
Django atomic block don't roll back all changes
I've probably misunderstood how rollback works when using with transaction.atomic() context manager in Django (1.11). In the following example the operation2 method raise an IntegrityError, but being operation2 called from an atomic transaction block all changes performed within the block should be rolled back. See the example (largely simplified from my actual code): class MyClass(object): def operation1(self, items): for item in items: item.ohlala = True def operation2(self, items, value): for item in items: item.value = value item.compute_other_value() # Create association. This block can raise Integrity Error line = item.line # OTO rel. line.net_amount = item.other_value line.save() def do_things(self, form): items = get_items() try: with transaction.atomic(): self.operation1(items) self.operation2(items, 200) except IntegrityError as e: return False What happens instead is that all changes performed in operation2 are rolled back but not those performed in operation1. I would have expected all operations updating the db to be rolled back. In the django documentation it once says that when raising from within an atomic block then all changes will be rolled back. But later on in the same section it says "You may need to manually revert model state when rolling back a transaction." Am I misinterpreting what Django should do or am I … -
how to create hook from python to send data to mixpanel using dev token
I want to create a hook from my python code to send user data to mixpanel from signals.py in login and logout. Seen examples using api key and secret keys but I have only the dev auth token. Also i want to retrieve data from that hook later on -
Edit profile for 2 different user types in Django
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for student, the same form as for teacher is displayed... a student has different attributes so it has a different form I need to show. @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user == teacher.user: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif user == student.user: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context)