Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show values in dropdown list in Django
I want to add documents about different parts of my facility in my Django app. So, I have the following models in my models.py: class Parts(models.Model): Name = models.CharField(max_length=50) class Docs(models.Model): Date = models.DateField(default=date.today) Type = models.CharField(max_length=50) Part = models.ForeignKey(Parts) Link = models.FileField(upload_to='Docs/%Y/%m/%d') forms.py: class DocsForm(ModelForm): class Meta: model = Docs fields = ['Date', 'Type', 'Part', 'Link'] class PartsForm(ModelForm): class Meta: model = Parts fields = ['Name'] views.py: def adddocs(request): if request.method == 'POST': f = DocsForm(request.POST, request.FILES) if f.is_valid(): f.save() return HttpResponseRedirect('') else: form = DocsForm() return render( request, 'adddocs.html', {'form': form} and the following fragment in my template: <form action="{% url 'adddocs' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p> {{form.Date}} </p> <p> {{form.Type}} </p> <p> {{form.Part}} </p> <p> {{form.Link}} </p> <p><input type="submit" value="Add" /></p> </form> And everything works fine except one problem. Now I have two parts of my facility, for example 'tubes' and 'storage'. But if I want to choose them in dropdown list, I see the following variants in my browser: Parts Object Parts Object What should I change to see names of parts like this tubes storage ? -
Create a report in Django using a jaspersoft (jrxml) file
I am looking for a way to produce a report in pdf format using my jrxml file (jasepersoft) in Django. I saw this example on github: https://github.com/jadsonbr/pyreport#processing. How can I integrate this example into my django template? Is there a much simpler way to run my jrxml file in Django? Thank you -
when I update a field of a model, all the other fields are deleted
if I update f1, f2 is deleted and if update f2, f1 is deleted ... how do i keep varing the fields that are not changed? sorry for my horrible English views.py def edit_iscrizioni(request, corso_id): corsi = Corso.objects.filter( pk=corso_id) fasca = Corso.objects.get( pk=corso_id) tabella= Iscrizione.objects.filter(user=request.user) iscrizione=get_object_or_404(Iscrizione, pk=tabella) if request.method == "POST": form = IscrizioneForm(request.POST, instance= iscrizione) if form.is_valid(): iscrizione = form.save(commit=False) iscrizione.user = request.user iscrizione.published_date = timezone.now() if fasca.progressivo: if fasca.f1: iscrizione.corso1_id= corso_id if fasca.f2: iscrizione.corso2_id= corso_id form.save() return redirect('privata') else: form = IscrizioneForm(instance= iscrizione) return render(request, 'corsi/edit.html', {'form':form, 'corsi':corsi}) model.py class Corso(models.Model): titolo = models.CharField(max_length=100) progressivo= models.BooleanField(default=False) f1= models.BooleanField(default=False) f2= models.BooleanField(default=False) class Iscrizione(models.Model): user = models.ForeignKey('auth.User') corso1= models.ForeignKey('Corso', blank=True, null=True, related_name="corso1") corso2= models.ForeignKey('Corso', blank=True, null=True, related_name="corso2") -
Django Cookiecutter : package folder not found
I have created a Django Project usin the cookiecutter project. On this project I have installed django-simple-poll. All is going fine, not error message; the poll Model appears in the admin. But, there is not folder for the 'poll' app in my project. I presume that installing the package should create a folder for this new app with template subfolder and all the usual stuff. Am I missing something? -
'Your models have changes that are not yet reflected in a migration.' error
I'm trying to deploy https://github.com/codingforentrepreneurs/eCommerce.git/ on heroku and I get this error- Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. How can I fix it? -
Django-Wagtail - How to select the "Choose A Page" panel when adding a model to the content panels?
I'm not sure if I'm being really thick here but I am struggling to find this panel in the list of available panels. At first I thought it was the PageChooserPanel but it isn't. This is what I'm looking for: This panel is available when inserting links into the RichTextField. It's perfect for my needs but I can't seem to find it anywhere else. I'm trying to create a field whereby the editor can select either an existing page or link to an external URL. The URL will then feed into a ref="{{ page.my_url }}" in my template. -
Django.db.utils.DataError: value too long for type character varying (3)
Not sure why I'm getting this error as none of my fields are set to limit 3 except one, which I know will never exceed 3. I'm able to run python manage.py makemigrations without any issue, but once I migrate the error pops up. My model looks like this: class Player(models.Model): player_id = models.PositiveIntegerField() player_name = models.CharField(max_length=60) team_id = models.PositiveIntegerField() team_abbreviation = models.CharField(max_length=3) age = models.PositiveIntegerField() gp = models.PositiveIntegerField() w = models.PositiveIntegerField() l = models.PositiveIntegerField() w_pct = models.DecimalField(max_digits=4, decimal_places=3) min = models.DecimalField(max_digits=4, decimal_places=3) fgm = models.DecimalField(max_digits=4, decimal_places=3) fga = models.DecimalField(max_digits=4, decimal_places=3) fg_pct = models.DecimalField(max_digits=4, decimal_places=3) fg3m = models.DecimalField(max_digits=4, decimal_places=3) fg3a = models.DecimalField(max_digits=4, decimal_places=3) fg3_pct = models.DecimalField(max_digits=4, decimal_places=3) ftm = models.DecimalField(max_digits=4, decimal_places=3) fta = models.DecimalField(max_digits=4, decimal_places=3) ft_pct = models.DecimalField(max_digits=4, decimal_places=3) oreb = models.DecimalField(max_digits=4, decimal_places=3) dreb = models.DecimalField(max_digits=4, decimal_places=3) reb = models.DecimalField(max_digits=4, decimal_places=3) ast = models.DecimalField(max_digits=4, decimal_places=3) tov = models.DecimalField(max_digits=4, decimal_places=3) stl = models.DecimalField(max_digits=4, decimal_places=3) blk = models.DecimalField(max_digits=4, decimal_places=3) blka = models.DecimalField(max_digits=4, decimal_places=3) pf = models.DecimalField(max_digits=4, decimal_places=3) pfd = models.DecimalField(max_digits=4, decimal_places=3) pts = models.DecimalField(max_digits=4, decimal_places=3) plus_minus = models.DecimalField(max_digits=4, decimal_places=3) nba_fantasy_pts = models.DecimalField(max_digits=4, decimal_places=3) dd2 = models.DecimalField(max_digits=4, decimal_places=3) td3 = models.DecimalField(max_digits=4, decimal_places=3) gp_rank = models.PositiveIntegerField() w_rank = models.PositiveIntegerField() l_rank = models.PositiveIntegerField() w_pct_rank = models.PositiveIntegerField() min_rank = models.PositiveIntegerField() fgm_rank = models.PositiveIntegerField() fga_rank = models.PositiveIntegerField() … -
How to use Django Proxy Models from remote database
I have a Django app running on a remote server, let's call that app "masterapp". On that remote server, it is actually included in settings.INSTALLED_APPS as "toppath.middlepath.masterapp" (obviously I am changing the names to protect the innocent). This app of course has a models.py file toppath/middlepath/masterapp/models.py. I also have a second Django app running on a different server, let's call this app "childapp" and suppose it is in package "foo.bar.childapp". The settings.INSTALLED_APPS lists "foo.bar.childapp" as one of the installed apps. Now suppose that in childapp, I need to use models and data from masterapp. Specifically, I need to use the django.auth.User model, and masterapp also has some custom models that have a ForeignKey to user. Furthermore, the custom models have reverse relationships like this: class CustomThing(Model): user = models.ForeignKey(User, null=False, related_name='custom_things') name = models.CharField(max_length=255, null=False, blank=False) def __unicode__(self): return self.name class Meta: db_table = 'masterproject_custom_things' verbose_name_plural = 'Custom Things' ordering = ['name'] Here I should be able to get a user's custom things using user.custom_things.all(). What I want to do is: 1. Get access to both User and CustomThing models from masterapp and use them in childapp. Remember masterapp runs on one server with one MYSQL DB and childapp runs … -
Model bijection
I am working with the following sitation in Django. (I know the design is bad, I am working with a legacy database and cannot change the underlying tables and relationships). Class User(models.Model): user_id = models.IntegerField(db_column="UserID", primary_key=True) userdetail1 = models.CharField(db_column="UserDetail1") userdetail2 = models.CharField(db_column="UserDetail2") Class UserDetail3(models.Model): user_id = models.IntegerField(db_column="UserID", primary_key=True) userdetail3 = models.CharField(db_column="UserDetail3") Class Event(models.Model): event_id = models.IntegerField(db_column="EventID", primary_key=True) user = models.ForeignKey(User, db_column="UserID") E.g., Userdetail3 does not just have a one-to-one relationship, but a bijective relationship with the User model. I want a list of all the events objects, but I want to annotate the event objects with the details of the user which generated that event. This works great for userdetail1 and userdetail2. I do it like this: class EventSerializer(serializers.Serializer): event_id = serializers.IntegerField() userdetail1 = serializers.CharField() userdetail2 = serializers.CharField() class EventList(generics.ListAPIView): serializer_class = EventSerializer def get_queryset(self): qs = models.Event.all() qs.annotate(userdetail1=F('user__userdetail1') qs.annotate(userdetail2=F('user__userdetail2') return qs But I am not sure how I can also annotate with userdetail3. Any ideas? -
Django with PostgreSQL 10?
Does Django support PostgreSQL 10 at the moment? I tried to use pgadmin3 with the psql V10 and found, it breaks pdagmin3. Somebody has opened a ticket on django project which may be in discussion. Is there any known breaking changes in v10 compared to v9.6 for Django? (because it breaks in pgadmin3)? let me know thanks. -
WebSocket connection to 'ws://xxx' failed: Error during WebSocket handshake: Unexpected response code: 200
I am working on a django project, which includes communication functions via channels. It runs smoothly on my own MacOS (accessed via 127.0.0.1). So I move it to Ubuntu server and use Apache2 to deploy it. I have linked wsgi.py to the website configuration file. The wsgi.py links correctly to the settings.py where I set up channels correctly. Then I "service apache2 restart" to get the website running. When I open the website, all the static files are loaded correctly. But the function of discussion forum is not working. In the browser console, it says "WebSocket connection to 'ws://xxx' failed: Error during WebSocket handshake: Unexpected response code: 200". Please help! Thanks. -
Add Bootstrap to Inbulit Login View Django
I am using the default view for logging the users.So I have not made any modelForm for it.So I am not able to provide any bootstrap class to the input fields i.e username and password. So my login form is looking ugly.Is there anyway. I want to add bootstrap class form-control to the input fields username and password. Following is my HTML and URL snippets. All functions and classes used have their modules imported. urls.py url(r'^login/$', login, {'template_name': 'app/login.html'}), login.html <form class="form-signin" method="post"><span class="reauth-email"> </span> {% csrf_token %} <!--{{form.as_p}}--> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} <!--<input class="form-control" type="email" required="" placeholder="Email address" autofocus="" id="inputEmail">--> <!--<input class="form-control" type="password" required="" placeholder="Password" id="inputPassword">--> <div class="checkbox"> <div class="checkbox"> <label><input type="checkbox">Remember me</label> </div> </div> <button class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Sign in</button> </form> -
django-modeltranslation become a already exists field in translatable
I'm using django-modeltranslation to translate models in my app. I've a model wich I've sync with the db with migrate command. Also I've a lot of records for that model. class Home(models.Model): description = models.TextField() Of course, at this point, I can retrieve description field from db h = Home.objects.first() h.description # --> "This home is near to..." Now, I want to become the description field translatable using django-modeltranslation. I've follow de guide, I've registered the model for translation in the translation.py file, Finally I've executed makemigrations and migrate commands. This added to my db, in the home table, the fields description_en and description_es, as my availabe languajes are en and es, the former is the default. At this point i need to populate the description_en field wich is the default for any query, I tried Home.objects.all().update(description_en=F('description')) but it doesn't work because when it tries to access to the description field it in fact is trying to access to description_en, and it is empty: h = Home.objects.first() h.description # --> '' Empty?!!! I've check if the data still in the db and they are! My question is: if description data still in db, and h.description retrieve me in fact h.description_en, … -
Ajax send a list as a string instead of just a list
I am using jQuery to gather all the information entered on the webpage, and then using ajax to send this info to my django view. This is the code that takes care of that: var button = $("#serialise"); var JSON_content = $('#JSON_Contents') $(button).click(function() { var vals = []; $("#questions :input").each(function(index) { if($(this).attr('type') == 'checkbox') { if($(this).prop("checked")) { vals.push('on'); } else { vals.push('off'); } }else { vals.push($(this).val()); } }); vals = JSON.stringify(vals); var url = window.location.pathname; $.ajax({ method: "POST", url: url, data: { 'vals': vals }, dataType: 'json', success: function (data) { //On success } }); }); The view then receives the info here: def add_questions(request, review_id = None): if request.method == 'POST': vals = request.POST.get('vals', None) args = {'recieved': 'true'} return JsonResponse(args) The problem I am getting, is that the info that is sent, is sent as a string, not as a list. So its being sent as '["Example", "Example"]' instead of ["Example", "Example"]. I assume my vals = JSON.stringify(vals); is causing this, however if I remove this, nothing is received by the view. How do I turn it into the list like I want it to? -
Django adding img to the <option>
Hello i got a question to u guys. How can i add a specific img to each of this options in django <select id="sTypes2" name="current_tier" class="form-control input-lg c-square"> <option value="Silver I">Silver I</option> <option value="Silver II">Silver II</option> <option value="Silver III">Silver III</option> <option value="Silver IV">Silver IV</option> <option value="Silver Elite">Silver Elite</option> <option value="Silver Elite Master">Silver Elite Master</option> <option value="Gold Nova I">Gold Nova I</option> <option value="Gold Nova II">Gold Nova II</option> <option value="Gold Nova III">Gold Nova III</option> <option value="Gold Nova Master">Gold Nova Master</option> <option value="Master Guardian I">Master Guardian I</option> <option value="Master Guardian II">Master Guardian II</option> <option value="Master Guardian Elite">Master Guardian Elite</option> <option value="Distinguished Master Guardian">Distinguished Master Guardian</option> <option value="Legendary Eagle">Legendary Eagle</option> <option value="Legendary Eagle Master">Legendary Eagle Master</option> <option value="Supreme Master First Class">Supreme Master First Class</option> <option value="Global Elite">Global Elite</option> -
Issues with django and postgresql triggers
I have made several tables in a Postgres database in order to acquire data with time values and do automatic calculation in order to have directly compiled values. Everything is done using triggers that will update the right table in case of modification of values. For example, if I update or insert a value measured @ 2017-11-06 08:00, the trigger will detect this and do the update for daily calculations; another one will do the update for monthly calculations, and so... Right now, everything is working well. Data acquisition is done in python/Qt to update the measured values using pure SQL instruction (INSERT/UPDATE/DELETE) and automatic calculation are working. Everything is working well too when I use an interface like pgAdmin III to change values. My problem comes with development in django to display and modify the data. Up to now, I did not have any problem as I just displayed data without trying to modify them. But now I don't understand what's going on... If I insert a new value using model.save(), eveything is working: the hourly measure is written, the daily, monthly and yearly calculation are done. But if I update an existing value, the triggers seem to not … -
No questions asked when installing Django CMS - so no bootstrap
I installed Django CMS through Powershell using the command: pip install djangocms-installer I'm new to this, and the tutorial that I've been following suggested that I should be asked questions to set up Bootstrap and the SuperUser account. These questions weren't asked. Does anybody know know why and how I could change this by hand? The django docs don't seem to be much help here because they assume that the questions are asked. -
Django Changing css for base.html based on model instance field value
I have just built this notification system and it works great. However, I don't want to expect that a user will check the notifications page themselves, and so in order to notify the user that they have a new notification I would like the notification link in the nabber to have different css properties depending on if that user has any notifications that have not been read. I am a little stuck on this because the html link that should be changed is in my base.html rather than the app. Also, being that it is a notifications system and new notifications are created all the time and being marked read all the time it needs to be able to go through a loop and look at every notification pertaining to the logged in user. Here is my code, any help would be much appreciated. Notify app Model: class UserNotification(models.Model): fromUser = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') toUser = models.CharField(max_length=100,default='user') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=10) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.fromUser) Base.html navbar: <nav> <div class="container"> <a class="brand" href="{% url 'index' %}">Evverest</a> <div class="navbar"> <a class="nav-link" href="{% url 'index' %}">Home</a> {% if request.user.is_authenticated %} <a class="nav-link" … -
Django rest framework if serializer returns empty
I have am implementing a follower and followers system in my drf api. My relationship model and serializer: models.py class Relationship(models.Model): user = models.ForeignKey(User, related_name="primary_user", null=True, blank=True) related_user = models.ForeignKey(User, related_name="related_user", null=True, blank=True) incoming_status = models.CharField(max_length=40, choices=RELATIONSHIP_CHOICE, default=RELATIONSHIP_CHOICE[0]) def __str__(self): return self.user.username + " " + self.incoming_status + " " + self.related_user.username serializers.py class RelationshipSerializer(serializers.ModelSerializer): outgoing_status = serializers.SerializerMethodField() class Meta: model = models.Relationship fields = ( 'user', 'related_user', 'incoming_status', 'outgoing_status', ) def get_outgoing_status(self, obj): related_user = obj.related_user user = obj.user try: query = models.Relationship.objects.get(user=related_user, related_user=user) user_id = query.incoming_status except models.Relationship.DoesNotExist: user_id = "none" return user_id views.py class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer @detail_route(methods=['get'], url_path='relationship/(?P<related_pk>\d+)') def relationship(self, request, pk, related_pk=None): user = self.get_object() query = models.Relationship.objects.filter(user=user)&\ models.Relationship.objects.filter(related_user__pk=related_pk) serializer = serializers.RelationshipSerializer(query, many=True) return Response(serializer.data) Incoming status is your relationship to the user and outgoing status is the users relationship to you to so for example this can return [ { "user": 2, "related_user": 1, "incoming_status": "follows", "outgoing_status": "none" } ] This means you follow the user and the user doesn't follow you back When you follow a user my code works fine because it returns "incoming_status": "follows" and it then checks for the outgoing status in the serializers. However when … -
Using Q to get reports not equal to
I'm on the last step of my view and I can get all reports to return using QVReportList.objects.all() it shows the report ID correctly in my template. However I'd like to use Q to show only the reports that don't exists in my reportdetail shown below: def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername).values('report_id','report_name','report_access') reportlist = QvReportList.objects.filter(~Q(report_id = reportdetail.report_id)) # excludedlist = QvReportList.objects.filter(report_id = reportlist.Report_ID) print(reportlist) args = {'user':owner, 'applicationaccess':reportdetail, 'applicationlist':reportlist}#, 'excluded':excludedlist} return render(request, 'accounts/profile.html', args) When I try to run it as it I get an AttributeError that states report_id doesn't exist, but it does when I can render it with applicationaccess.report_id and applicationlist.report_id: AttributeError at /account/profile/ 'QuerySet' object has no attribute 'report_id' Why does it state the object has no attribute report_id? It clearly exists in the existing database table and my models. -
ObjectDoesNotExist not catching a DoesNotExist exception
I'm trying to catch a DoesNotExist exception, and inspecting the code where the exception is thrown is difficult. I can't reach the line that throws it in pdb, and in the debug trace there's no information on what object is throwing the exception, as it is contained under an instance variable so the django trace doesn't show what it's value is. I have read the docs at https://docs.djangoproject.com/en/1.11/ref/exceptions/#objectdoesnotexist and this question at Catching Any DoesNotExist Error. Both of these indicate that to catch any DoesNotExist exception, one simply imports ObjectDoesNotExist and that covers all of them. It is not in my case. The exception is not caught in my except ObjectDoesNotExist block. Code: from django.core.exceptions import ObjectDoesNotExist def check_permission(user): """function checks whether the user is in the list of allowed groups""" for option in ALLOWED: # list of groups, constant try: if user.groups.get().name == option: return True except ObjectDoesNotExist: pass else: pass return False The trace reads: File ".../lib/python3.6/site-packages/django/db/models/query.py", line 379, in get self.model._meta.object_name django.contrib.auth.models.DoesNotExist: Group matching query does not exist. Which gets thrown from the line in my code: if user.groups.get().name == option attempting to access django.contrib.auth.models.DoesNotExist simply returns an AttributeError: model 'django.contrib.auth.models' has no attribute 'DoesNotExist' How do … -
Django - How to upload one file to multiple objects?
So the problem I'm face is that we have multiple shops that has the same image, so we would like to upload just one image then we create multiple objects from that image. The problem is that when we saved a model that file cannot be used anymore, seem like the file is closed. This is the error I've got. ValueError: seek of closed file -
Error: 2 issue, reverse accessors for foreign keys clashing
I'm struggling with my codes.I'm following this tutorial and i have some troubles. https://tutorial.djangogirls.org/en/django_forms/ . Could anyone can help me ? My models: model file from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here is my issue, reverse accessors for foreign keys clashing. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packag s\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packag s\django\core\management\commands\runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packag s\django\core\management\base.py", line 472, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check id ntified some issues: ERRORS: blogapp.Post.author: (fields.E304) Reverse accessor for 'Post.author' clashes w th reverse accessor for 'Post.user'. HINT: Add or change a related_name argument to the definition for 'Post author' or 'Post.user'. posts.Post.user: (fields.E304) Reverse accessor for 'Post.user' clashes with re erse accessor for 'Post.author'. HINT: Add or change a related_name argument to the definition for 'Post user' or 'Post.author'. System check identified 2 issues (0 silenced).`enter code here` What could i do? -
Django admin - Auto save current user to model via inlines?
I have the following and it throws an error when I attempt to upload a document via the admin page for Proceeding. How can I auto populate the entered_by field for the Document model when using an inline? Error: IntegrityError at /admin/myapp/proceeding/6/change/ (1048, "Column 'entered_by_id' cannot be null") # models.py class Proceeding(models.model): date = models.DateField() entered_by = models.ForeignKey(User) class Document(TimeStampedUserModel): proceeding = models.ForeignKey(Proceeding) document = models.FileField(upload_to='documents/') entered_by = models.ForeignKey(User) #admin.py class DocumentAdmin(admin.ModelAdmin): fields = ('proceeding', 'document', ) list_display = ('proceeding', 'entered_by', ) def save_model(self, request, obj, form, change): instance = form.save(commit=False) instance.entered_by = request.user instance.save() form.save_m2m() return instance def save_formset(self, request, form, formset, change): def set_user(instance): instance.entered_by = request.user instance.save() if formset.model == Document: instances = formset.save(commit=False) map(set_user, instances) formset.save_m2m() return instances else: return formset.save() class DocumentInline(admin.TabularInline): model = Document fields = ( 'proceeding', 'document', ) extra = 0 class ProceedingAdmin(admin.ModelAdmin): inlines = [DocumentInline, ] fields = ('date',) list_display = ('date', 'entered_by', ) def save_model(self, request, obj, form, change): instance = form.save(commit=False) instance.entered_by = request.user instance.save() form.save_m2m() return instance def save_formset(self, request, form, formset, change): def set_user(instance): instance.entered_by = request.user instance.save() if formset.model == Proceeding: instances = formset.save(commit=False) map(set_user, instances) formset.save_m2m() return instances else: return formset.save() -
Django Email validation continue
I have next code(Using default django validations): def save(request): form = UserProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: return redirect('profile') My purpose is to save emails, such as anrd@gmail and etc. Emails without dots. How can I pass default validation to do it? Thx.