Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using models clean method for fields validation
I need to check the model field for a list of available items before I save them to the database. models.py class Vendors(models.Model): COUNTRY_CHOICES = tuple(countries) ... country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) ... class for saving models class CsvToDatabase(APIView): def post(self, request, format=None): data = request.data for key, vendor in data.items(): Vendors( ..., country=vendor['Country'], ..., ).save() return Response({'received data': request.data, 'message': 'Vendors from vendors_list were successfully added to the database'}) For validation Im added clean method to models def clean(self): if self.country not in [x[1] for x in countries]: print("Invoke save") raise ValidationError(detail="Country name does not match to the country list ") But it doesnt work Next step I added the same code to method save def save(self): if self.country not in [x[1] for x in countries]: print("Invoke save") raise ValidationError(detail="Country name does not match to the country list ") And it works, but I read that using validation in the save method is not correct. And the correct method for use - clean, why in my case it does not work? -
Sum of product of numbers using Multi threading in django
I have a csv file which contains space seperated numbers and has multiple rows, I need to find product of all numbers in a row and also sum of all numbers using multi threading in Django. -
Django - Diffrent ListViews
I have a problem, I'm making a simple blog and I want to have drafts, archive and main list of posts. I made 3 ListViews and all of them display like main one, but with diffrent filters and I want them to be diffrent. Can you tell me what I did wrong? views.py class PostListView(generic.ListView): model = Post redirect_field_name = "posts/post_list.html" def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-create_date')[0:3] class ArchiveView(generic.ListView): model=Post redirect_field_name = "posts/post_archive.html" def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-create_date')[3:0] class DraftListView(LoginRequiredMixin, generic.ListView): login_url = "/login/" redirect_field_name = "posts/post_draft_list.html" model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('create_date') urls.py urlpatterns = [ path('', views.IndexView.as_view(), name="index"), path('posts/',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), path('posts/<int:pk>', views.PostDetailView.as_view(), name='post_detail'), path('posts/new/', views.CreatePostView.as_view(), name='post_new'), path('posts/<int:pk>/edit/', views.PostUpdateView.as_view(), name='post_edit'), path('drafts/', views.DraftListView.as_view(), name='post_draft_list'), path('posts/<int:pk>/remove/', views.PostDeleteView.as_view(), name='post_remove'), path('posts/<int:pk>/publish/', views.post_publish, name='post_publish'), path('posts/archive', views.ArchiveView.as_view(), name='archive') ] post.list.html {% extends 'posts/base.html' %} {% block title %} Dziennik z życia {% endblock %} {% block content %} <div class="text-white list-container pt-5"> {% if post_list %} {% for post in post_list %} <div class="post"> <h2><a href="{% url 'post_detail' pk=post.pk %}" class="text-white">{{ post.tytuł }}</a></h2> <div class="date"> <p>Utworzony: {{ post.create_date }}</p> </div> </div> {% endfor %} <p>Aby obejrzeć moje wcześniejsze dzieje, odwiedź <a href="{% url 'archive' %}"><strong>ARCHIWUM</strong></a></p> {% else %} <h2 class="d-flex justify-content-center mt-5">Nie ma jeszcze żadnych wpisów! Moi … -
AWS Elastic Beanstalk, wont update django.config with "eb deploy"
I've deployed a API application to AWS Elastic Beanstalk written in python and django. I'm now developing the frontend from which I'm trying to send a simple get request to the AWS python server. Trying different solutions to the CORS header issue I added: files: "/etc/httpd/conf.d/cors.conf" : mode: "000644" owner: root group: root content: | <Location "/"> Header set Access-Control-Allow-Origin: * Header set Access-Control-Allow-Methods: "POST, GET, PUT, DELETE, OPTIONS" Header add Access-Control-Allow-Headers: "Authorization, Content-Type, Accept" Header set Access-Control-Allow-Credentials: true SetOutputFilter DEFLATE </Location> to the django.config file which made it work on AWS but not locally (the django.config file is located in .ebextensions file). I decided to instead use the 'django-cors-headers' middleware so that it would work both locally and on AWS. But now it wont work on AWS since it registers multiple Access-Control-Allow-Origin domains. So after removing the above files: code from django.config the problem persisted so the reasonable problem would be that the header is added both by the middleware and by the django.config code which I'm not able to remove. Could someone help me find a solution? -
query on manyToMany field with related_name
my models: class Course(models.Model): pass class CourseRun(models.Model): course = models.ForeignKey(Course, related_name='course_runs') class Category(models.Model): courses = models.ManyToManyField(Course, related_name='category_set') for some reason I was forced to add many2many in Category model instead of Course model my question: how can I search on CourseRun by category id somethings like this: CourseRun.objects.filter(course__category__in=[1, 2]) -
Django Mail with .ics attachment : Mail is not Send?
from icalendar import Calendar,Event def send_mail_to_interviwee(request, round_pk): intv_round = Round.objects.get(pk=str(round_pk)) supporters = list(intv_round.supporting_interviewer.values_list('email', flat=True)) round_taker = intv_round.assignee subject = "Interview Scheduled..Please go through details" htmly = get_template('Evaluator/email_interview.html') d = { 'round_taker': round_taker, 'candidate': intv_round.interview.candidate, 'round_date': intv_round.date, 'round_name': intv_round.name, 'round_time': intv_round.contact_time, 'round_type': intv_round.round_type, 'additional_Comments': intv_round.comments, } cal = Calendar() cal.add('version', '2.0') cal.add('prodid', '-//Microsoft Corporation//Windows Calendar 1.0//EN') cal.add('method', 'PUBLISH') event = Event() event.name = intv_round.name event.begin = intv_round.date cal.add_component(event) file_name = "interview.ics" with open(file_name, 'w') as my_file: my_file.writelines(cal) my_file.close() html_content = htmly.render(d) all_mails = [round_taker.email] + supporters #Format: Subject, Message, from, to msg = EmailMultiAlternatives(subject, "Please find details of Candidate in this mail", request.user.email, all_mails) msg.attach_alternative(html_content, "text/html") msg.attach(file_name, calendar, mimetype='text/calendar') try: msg.send() messages.success(request, 'Mail sent successfully') except: logger.debug('Sending mail to %s' % all_mails) logger.warning('Failed to send mail to:{} , User: {}'.format(round_taker.name, request.user.username)) messages.error(request, 'Failed to send mail') return HttpResponseRedirect(intv_round.interview.get_absolute_url()) This function is not able to send email with attachments? -
Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P<pk>\\d+)/delete/$']
I am getting django.urls.exceptions.NoReverseMatch: Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P\d+)/delete/$'] and in my console it is showing :- Failed to load resource: the server responded with a status of 500 (Internal Server Error) My views.py def company_delete(request,pk): data = dict() company = get_object_or_404(Company,pk=pk) if request.method == "POST": company.delete() data['form_is_valid'] = True companies = Company.objects.all() data['company_list'] = render_to_string('company_list_2.html',{'companies': companies}) else: context = {'company': company} data['html_form'] = render_to_string('company_delete.html',context,request=request) return JsonResponse(data) my urls.py urlpatterns = [ url(r'^company/$', views.company_list, name='company_list'), url(r'^company/create/$', views.company_create, name='company_create'), url(r'^company/(?P<pk>\d+)/update/$', views.company_update, name='company_update'), url(r'^company/(?P<pk>\d+)/delete/$', views.company_delete, name='company_delete'), ] my company_list_2.html {% for c in companies %} <tr> <td>{{ c.name }}</td> <td>{{ c.description }}</td> <td>{{ c.website }}</td> <td>{{ c.address }}</td> <td>{{ c.phone }}</td> <td>{{ c.email }}</td> <td>{{ c.contact }}</td> <td> <button class="btn btn-warning show-form-update" data-url="{% url 'company_update' c.pk %}"> <span class="glyphicon glyphicon-pencil"></span> Edit </button> </td> <td> <button class="btn btn-danger show-form-delete" data-url="{% url 'company_delete' c.pk %}"> <span class="glyphicon glyphicon-trash"></span> Delete </button> </td> </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">No Company</td> </tr> {% endfor %} my company_delete.html {% load crispy_forms_tags %} <form method="post" data-url="{% url 'company_delete' c.pk %}" class="delete-form"> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title" >Delete Company</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> … -
Python: Object to list of tuples extraction
I have an object in the following format: { 'af': { 'bidi': False, 'code': 'af', 'name': 'Afrikaans', 'name_local': 'Afrikaans' }, 'ar': { 'bidi': True, 'code': 'ar', 'name': 'Arabic', 'name_local': 'العربيّة' }, ... } This is a list of locales as found in django.conf.locale.LANG_INFO. (see here for full reference: https://github.com/django/django/blob/master/django/conf/locale/init.py). Now, I am hoping to utilise this list in a model class: locale = models.CharField(max_length=5, choices=get_locale_choices(), default='en') Such that I have the following utility function: from django.conf.locale import LANG_INFO def get_locale_choices(): return ? Now, that ? that gets returned, I'd like to be in the following format: [ ('af', 'Afrikaans'), ('ar', 'Arabic'), ... ] My question is this, how would I turn the LANG_INFO dictionary into the above list of tuples? It feels like something like this is close: a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'} d_items = a_dict.items() d_items # Here d_items is a view of items dict_items([('color', 'blue'), ('fruit', 'apple'), ('pet', 'dog')]) But...hmmm, not sure? I want to extract a sub-value from the key item... -
What are the differences between using self.add_error() and raising a ValidationError()?
You can throw a validation error in 2 ways. The first is with self.add_error() and the second with raise ValidationError(). I've read that when you use self.add_error('field1','description here') then field1 is also automatically removed from the cleaned_data list and i assume a ValidationError object is also added to the self.errors list, is this correct? But what happens when you don't choose to use self.add_error and opt for using raise ValidationError instead? Is this object also automatically added to the errors list behind the scenes? And how would you display this error message as caption under the correct invalid field? Thank you -
How to set the default language for all users or browsers
There are two working versions of the translation on the site - Russian and English using i18n. How to make sure that everyone has a website loaded in Russian and then, at the request of the user, he can change it to English? MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] LANGUAGE_CODE = 'ru' LANGUAGES = ( ('ru', _('Russian')), ('en', _('English')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TIME_ZONE = 'Europe/Kiev' USE_I18N = True USE_L10N = True USE_TZ = True -
How to validate one name is unique and remaining names is not unique example sunday is unque and moday,tuesday values are not unique using django
class IssueTypeForm(forms.ModelForm): LIVE = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(IssueTypeForm, self).__init__(*args, **kwargs) self.fields['NAME'].widget.attrs.update({'class' : 'form-control mb-2','placeholder': 'Enter Issue Type'}) self.fields['DESCRIPTION'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'}) self.fields['ICON'].widget.attrs.update({'class' : 'custom-file-input','placeholder': 'Upload Reference Image','aria-describedby':'fileInput'}) self.fields['TYPE'].widget.attrs.update({'class' : 'browser-default custom-select','placeholder': 'Select Issue Type'}) class Meta: model=IssueType fields = '__all__' exclude=['CREATOR','UPDATOR','CREATE_DATE_TIME','UPDATED_DATE_TIME','PROJECT'] def clean_TYPE(self): TYPE = self.cleaned_data['TYPE'] if IssueType.objects.exclude(pk=self.instance.pk).filter(TYPE=).exists(): raise forms.ValidationError(u'Type "%s" is already in use.' % TYPE) return TYPE -
Template Syntax Error in python Django example?how to solve this one
TemplateSyntaxError at /emp 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/style.css' %}"/> And I wrote 'django.contrib.staticfiles', in Installed Apps -
Database in celery task is out dated
I have Django==2.2.8 and celery==4.3.0, redis as broker. Have very simple drf view to create BankEntry. def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = serializer.save() async_task = async_create_transactions.delay(instance.pk) <--- celery task @celery_app.task() def async_create_transactions(entry_id): bank_entry = BankEntries.objects.filter(id=entry_id).first() if bank_entry: <---- HERE SOMETIMES BANK_ENTRY IS NONE, But why, we just created it return bank_entry.create_entries() Have no idea why, but in async_create_transactions I can get just created BankEntry. I'm sure that celery setup use same database, because in a next async_create_transactions call, I can see previous BankEntry but not the current one. I don't have, hooks, signals, postgresql functions and other side effects. -
Django template - how to access form in forms (context) given an index number (generated by an iterator)
I have two forms - a source form and a result form. Forms.py class SourceForm(forms.Form): some_source_field = forms.forms.CharField(...) class ResultForm(forms.Form): some_result_field = forms.forms.CharField(...) My view has uses formset_factory to render two instances of each and passes this to the template with a range of numbers that matches how many forms are to be rendered. Views.py class MyView(Vew): def get(self, request): forms_to_render = 2 SourceFormSet = formset_factory(SourceForm, extra=forms_to_render) ResultFormSet = formset_factory(ResultForm, extra=forms_to_render) context = { 'source_forms': SourceFormSet, 'result_forms': ResultFormSet, 'init': range(0, forms_to_render), } In my template, I want to generate a container for which holds a source_form and result_form, for each of the numbers in the given range (2 in this case), as below. template.html {% for i in init %} <div class="container-fluid" id="primary_container_{{ i }}"> {{ source_forms.i }} {{ result_forms.i }} </div> {% endfor %} Background: I have a javascript queue which unhides one primary_container at a time to be processed; I hide the "just-processed" container and populate it in the background while the user works on the next formset in the queue. The purpose is minimize the wait time while a form populates. If I hard-code the index value of 0 or 1 in, the form renders. {{ source_forms.0 … -
Django Channels: Exception inside application: No handler for message type app_consumer.notification_message
I'm trying to send a notification to the user using websockets, on a particular event. I have the following model receiver which triggers a websocket method: @receiver(pre_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, update_fields=None, **kwargs): if update_fields: if 'pan_number_verified' in update_fields and instance.pan_number_verified is True: notification = Notification.objects.create(message='Your PAN Number has been verified...Head on to ' 'creating a campaign right away.', user=instance) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("notification_%s" % instance.id, { "type": "app_consumer.notification_message", "message": str(notification.id) }) Here is my app consumer: class AppConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['user_id'] self.room_group_name = 'notification_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'app_consumer.notification_message', 'message': message } ) def notification_message(self, event): message = event['message'] self.send(text_data=json.dumps({ 'message': message })) But I get the following error message: Exception inside application: No handler for message type app_consumer.notification_message File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/consumer.py", line 59, in call [receive, self.channel_receive], self.dispatch File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/asgiref/sync.py", line 244, in call return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/tasks.py", line 414, in wait_for return await fut File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/channels/db.py", line 14, in thread_handler return super().thread_handler(loop, … -
Django: Input/Output error for certain api alone
I have problem in my application. When the application is started or restarted my code works 100% but after 6h and 12h appears strange error.When error occurred i need to restart server to fix, but the returns in some hours. ihave attached the error below.Any idea how to fix that? File "/home/ubuntu/site/local/lib/python2.7/site-packages/dj_static.py", line 59, in call return self.application(environ, start_response) File "/home/ubuntu/site/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 206, in call response = self.get_response(request) File "/home/ubuntu/site/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./main/decorators.py", line 12, in decorator return function(*args, **kwargs) File "./main/views.py", line 214, in get_nominals qwt.report_trace(e, request) File "./main/views.py", line 206, in get_nominals credit=protocol_obj.get_credits(), File "./Protocols/protocol.py", line 51, in get_credits return self.request.management.get_credits(self.service.id, self.login) File "./utils/Management.py", line 166, in get_credits request = self.__create_request_my_api(Credits, 'find_active_credit', service_id, login) File "./utils/Management.py", line 122, in __create_request_my_api terminal_info = getattr(class_api, method_name)(**args) File "./my_api/Credits.py", line 11, in find_active_credit obj_response = credit.get_credit_from_response(self.send_request()) File "./my_api/to/Credit.py", line 17, in get_credit_from_response print xml_response IOError: [Errno 5] Input/output error -
How to define a foreign key in an Django app model which is ignored if a sub-app is not installed
I have a base app which is used by sub-apps. I have an AbstractUser defined in the base app and I need to add a relation to a sub-app model if the sub-app is installed. I understand that my new field will be present in the user table in the database, but with a null value if the sub-app is note installed. My problem is to reference the foreign key I had to a model that does not exists if the sub-apps is not installed. Does I need to transfer the model from the sub-apps to the base app or is there another solution like a conditionnal foreign key constraint in my AbstractUser model. -
Is it possible to add a postgresql trigger to notify my Django app when a table changes?
My Django app connects to a PostgreSQL 9.x database. To this database, a legacy Java app is connected, too. So two different apps use the same database. Is it possible for PostgreSQL to notify my Django (2.2.x) app when a table changes? I know that I can create a cron job to check on tables on a timely basis, but the Server administrator does not let me do cron jobs (why?) and the Java guy is too busy on other things to do code rewiring (so I can't ask him him to send me url requests after table changes). Or any other idea would be much appreciated. Thanks. -
Django unable to read the model of other app
here is the directory format. I have 4 apps. -project -accounts -subscription -basiclinks I have already read out all the articles and failed so asked. The model class is in subscription and I want to import that into accounts from project.subscription.models import Package *Its throwing error that there is no module named project.subscription. -
Django Rest Framework - How to modeling and serialing data from Mssql Stored Procedure
I'm new to Django, and i'm trying to build my app that pulling some data from mssql database, i'll appreciate all the help that you can provide. I'm using 'django-mssql-backend' as the db backend, and using stored procedure from mssql, the data from the SP can be a 2 results sets, one as the correct data with 3 columns, and other in case of an error with 1 column. The parameters for the SP are coming as inputs from the request data. I want to understand how can i pull the data dynamically when getting one of the results using models. And how i can dynamically serialize the data the that will verify the inputs from the request and manilpulate the data before returning the response to the user, using serialzers. this is what i have currentlly just for testing # views.py from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def top_serial2(request, format=None): param1 = request.query_params.get('param1') param2 = request.query_params.get('param2') instance = GetWorkOrder.serials(param1, param2) serializer = GetSerializer(instance, many=True) return Response(serializer.data) # models.py from django.db import models, connections priority = connections['priority'].cursor() class GetWorkOrder(models.Model): PartNumber = models.CharField(db_column='PartNumber', max_length=50) SerialNumber = models.CharField(db_column='SerialNumber', max_length=50) Index = models.IntegerField(db_column='Index') ErrMessage = models.CharField(db_column='ErrMessage', max_length=256) @staticmethod def serials(param1, … -
Django Queryset ManyToMany
I'm trying to only show a user the Portfolios that they created but right now the form shows the user all the portfolios created. Ideally, I would like to filter this in the view.py but maybe filtering in the models.py could also be a good approach as I'll need this in several forms throughout the app. A post can belong to many different portfolios. Similar to how a hiking article may belong to several categories (outdoors, fitness, nature, travel, etc.) The only thing is I only want to show the user the "categories" or in our case the Portfolios that they have created and not of other users. I've been on this for several days now and read Djangos docs on queryset and manytomany plus gone through countless other guides and SOF questions. Am I overcomplicating this whole thing? It seems like it should be super simple. Any help would be very much appreciated. views.py class PostCreate(CreateView): model = Post form_class = PostCreateForm def get_queryset(self): return Portfolio.objects.filter(user=self.request.user).order_by('created') Models.py class Portfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20) description = models.CharField(max_length=250, blank=True, null=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = RichTextUploadingField(blank=True, null=True) associated_portfolios = models.ManyToManyField(Portfolio, blank=True) created_on … -
Why django can be tested without running server?
I want to test the reachability of home page of a demo app. So I do this: from django.test import TestCase class TestHomePageView(TestCase): def test_reachable_home(self): response = self.client.get('/home/') self.assertEqual(response.status_code, 200) and the views.py from django.shortcuts import render def home_view(request): return render(request, 'home.html', {}) home.html is a simple one: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> Hi, circleci and django </body> </html> and urls.py: from django.contrib import admin from django.urls import path from demo_app.views import home_view urlpatterns = [ path('admin/', admin.site.urls), path('home/', home_view) ] It's a really simple demo app. What I am curious is "Why I can test the status code without running django server?" Just simply $ python manage.py test without $ python manage.py runserver and get the test result: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.011s OK Destroying test database for alias 'default'... Any idea or suggestion is welcome, thanks. -
How to Redirect/Access Django Admin Page from Angular UI - Docker
We have used Docker environment which has two images. one for Back-end(Django) and another for front-end(Angular). In the Docker we have blocked(Back-end is running in port 8000) the direct back-end port access. only through front-end the backed will be access. I can access all the urls from frond-end. but I cannot access Django admin page. Because I am blocking the direct port access for back-end. Example: 1. Before blocking Port in docker-compose.yml, when access admin page, it will work http://domain_name:8000/api/user - **Accessible** http://domain_name:8000/admin - **Accessible** 2. After blocking Port in docker-compose.yml, when access admin page, it will work http://domain_name/api/user - **Accessible** http://domain_name/admin - **Not-Accessible** Kindly help me to access Django admin page. even if it the port is blocked. -
Related to user object ain't beeing created Django
thanks for your time: i've been having a problem on my POST request its getting me de code 302.0 it should create a object that is related to the user that did the request: views.py: @login_required @transaction.atomic def parceiros_create(request): if request.method == 'POST': form = ParceirosForm(request.POST, instance=request.user.parceiros) if form.is_valid(): form.save() messages.success(request, ('Parceiro criado')) return redirect('home2') else: messages.error(request, ('Please correct the error below.')) else: form = ParceirosForm(instance=request.user) context = { 'form': form, } return render (request, 'parceiroform.html', context) forms.py: class ParceirosForm(forms.ModelForm): nome = forms.CharField(max_length=200) endereco = forms.TextInput() responsavel = forms.CharField(max_length=100) tel = PhoneField(max_length=12) class Meta: prefix = 'parceiro' model = Parceiros fields = ['nome', 'endereco', 'responsavel', 'tel'] models.py: get_user_model = User class Parceiros (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nome = models.CharField(max_length=200) endereco = models.TextField(max_length=400, blank=True) responsavel = models.CharField(max_length=100) tel = PhoneField(max_length=12) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) ativo = models.BooleanField(default=False) def __str__(self): return '%s %s' % (self.user, self.nome) parceiroform.html: {% extends 'base.html' %} {% block content %} <h1>ok</h1> <h1>OK</h1> <h1>ok</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Save</button> </form> {% endblock %} i'm getting the message (parceiro criado) on my admin although ain't creating any object(Parceiros). -
How to change the default permission name?
I want to change the default permission name created by django after migrating django model. The docs says Providing default_permissions = [] in the class Meta works but It must be specified on the model before the model is created by migrate in order to prevent any omitted permissions from being created. But is it possible to change the permission Name (codename also if possible) after the model migration also ? class ContactPage(models.Model): full_name = models.CharField(max_length=255) email = models.EmailField() msg = models.TextField() sent_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Meta: default_permissions = [] # works in the first migrate permissions = [ ('can_view_contacts', 'Can View Contacts'), ('can_delete_contacts', 'Can Delete Contacts'), ]