Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail collectstatic finish with errors. How I can fix it?
Traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect raise processed File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 296, in _post_process content = pattern.sub(converter, content) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 197, in converter force=True, hashed_files=hashed_files, File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 134, in _url hashed_name = hashed_name_func(*args) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 345, in _stored_name cache_name = self.clean_name(self.hashed_name(name)) File "/home/megagun/PycharmProjects/wagtail-bootstrap-blog/venv/lib/python3.5/site-packages/django/contrib/staticfiles/storage.py", line 94, in hashed_name raise ValueError("The file '%s' could not be found with %r." % (filename, self)) ValueError: The file 'blog/img/overlays/01.png' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7f77b8fb1198>. When I try to run server with DEBUG = False, I got 500 error. I it coz I collect not all static. -
Function looking for 3 arguments but only 2 given. Not sure where the issue is
I am running into an error page when I try to resolve a link in my django project. It is telling me that the function find_module() takes 3 arguments but only 2 are provided. Now I understand what that means, but I can't find where the error is originating. The traceback points to a view but I don't see any problems with the code. Here is the traceback: -
Add search field in Django Admin
Before add a person in a event, I would like to search it. If the person exists, add it. If not, create it and add it. I have tryed many times with diferent ways in admin.py but I am not able to get it. Could someone help me with the admin.py? models.py class Person (models.Model): dni= models.CharField(primary_key = True, max_length=9 ) name= models.CharField(max_length = 30) surname1 = models.CharField(max_length = 30) surname2 = models.CharField(max_length = 30) table = models.PositiveIntegerField(default=0) def __str__(self): return self.dni class Meta: ordering = ('dni',) class Event (models.Model): name = models.CharField(max_length = 100) people= models.ManyToManyField(Person,blank = True, default = None) date = models.DateField('date event') category = models.CharField (choices = TYPE_EVENT, max_length = 1) def __str__(self): return self.name class Meta: ordering = ('name',) Currently all persons appear in the box. But its not correct. I would like to get something like this (link) but I didn't get the solution :S. -
django rest framework - backward serialization to avoid prefetch_related
I have two models, Item and ItemGroup: class ItemGroup(models.Model): group_name = models.CharField(max_length=50) # fields.. class Item(models.Model): item_name = models.CharField(max_length=50) item_group = models.ForeignKey(ItemGroup, on_delete=models.CASCADE) # other fields.. I want to write a serializer that will fetch all item groups with their item list as a nested array. So I want this output: [ {group_name: "item group name", "items": [... list of items ..] }, ... ] As I see, I should write this with django rest framework: class ItemGroupSerializer(serializers.ModelSerializer): class Meta: model = ItemGroup fields = ('item_set', 'group_name') Means, I have to write a serializer for ItemGroup (not for Item). To avoid many queries I pass this queryset: ItemGroup.objects.filter(**filters).prefetch_related('item_set') The problem that I see is, for a large dataset, prefetch_related results in an extra query with a VERY large sql IN clause, which I could avoid with the query on the Item objects instead: Item.objects.filter(**filters).select_related('item_group') Which results in a JOIN which is way better. Is it possible to query Item instead of ItemGroup, and yet to have the same serialization output? -
What is the idea of MultiPartParser and FormParser in Django REST framework?
I try to upload the files in Django REST framework and I read this documentation https://www.django-rest-framework.org/api-guide/parsers/#multipartparser. However, I have misunderstanding about the uses of MultiPartParser and FormParser. What is the idea of uses MultiPartParser and FormParser? I'm writing the code that can upload the file without using MultiPartParser and FormParser and it works fine!. So, is it necessary to use MultiPartParser and FormParser? model.py class Examole(TimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) name = models.CharField(max_length=128) file = models.FileField( upload_to=path_and_rename('user/po', 'po'), storage=private_storage, validators=[validate_file_extension]) view.py class UploadingFilesView(generics.CreateAPIView): serializer_class=UploadingFilesSerializer permission_classes = [AllowAny] def perform_create(self, serializer, format=None): file=self.request.FILES['file'] serializer = UploadingFilesSerializer(data=self.request.data, context={'file':file}) if serializer.is_valid(raise_exception=True): if self.request.data.get('file') is not None: file.name = self.request.data.get('file').name file.user = self.request.user serializer.save(name=file.name, user=file.user) -
Django SearchVector on choices field
If I have a simple Django model like: from model_utils import Choices class Art(models.Model): CATEGORIES = Choices((1, 'DIGITAL_ART', 'Digital Art'), (2, 'MULTIMEDIA', 'Multimedia')) title = models.TextField() category = models.PositiveSmallIntegerField(db_index=True, choices=CATEGORIES, blank=True, null=True) How can I use SearchVector in postgres to allow for searching on both the title and categories fields? E.g. so "Some Book Digital Art" would query over both the title and categories fields. The problem is that at the database-level the choices field is stored as an integer, not text. Is there a way I could just map the integer to the corresponding text value when creating my search vector? -
Django form's clean method doesn't raise ValidationError, instead makes is_valid() function return False
I've created this form where there are two fields, one field is the amount and the other field is the balance in account(credits). forms.py class SendCredits(forms.Form): credits = forms.IntegerField(required=False, widget=forms.HiddenInput()) amount = forms.IntegerField(max_value=1000) def clean_amount(self): cleaned_data = super(SendCredits, self).clean() if cleaned_data['amount'] > cleaned_data['credits']: raise forms.ValidationError("Not enough credits") return cleaned_data views.py if request.method == "POST": acceptor_points = all_users.filter(email=request.POST.get('towards', False))[0].credit_points giver_points = all_users.filter(email=request.GET['email'])[0].credit_points amt = int(request.POST['amount']) form = SendCredits({'amount': request.POST.get('amount', 0), 'credits': giver_points}) if form.is_valid(): print("Foo!") else: print(form.non_field_errors) When i check console it always prints out else: part of the is_valid() condition. Which is : <bound method BaseForm.non_field_errors of <SendCredits bound=True, valid=False, fields=(credits;amount)>> sendto.html <form class="form-group" method="POST"> <h2> Please select user to transfer funds to: </h2> {%csrf_token%} <table class="table table-dark"> <thead > <th scope="col"> Select </th> <th scope="col"> Name </th> <th scope="col"> E-mail </th> <th scope="col"> Credit Points </th> </thead> <tbody> {%for ex in others%} <tr> <td> <label for="towards"> <input type="radio" name="towards" value="{{ex.email}}"></label> </td> <td> {{ex.user_name}} </td> <td> {{ex.email}} </td> <td> {{ex.credit_points}} </td> </label> </tr> {%endfor%} </tbody> </table> {%for field in form%} <p> {%if field.is_hidden%} {%else%} {{field.non_field_errors}} {{field.label}} {{field}} {%endif%} </p> {%endfor%} <input type="submit" value="Send Credits" class="btn btn-lg btn-primary"> </form> I want to raise error if the balance(credits) are lower than the … -
Request timeout on dockerized django application deployed with Heroku
I have a django project which works fine locally, and a Dockerfile that correctly creates a Docker image for my django app. That image deploys well on Heroku, and opens login to admin page correctly. If I enter incorrect credentials, the application throws an invalid credentials error quickly. However, if I enter correct credentials, the application keeps working until Heroku timeout (30 seconds that can't be changed) is expired. I'm using Postgres add-on, and I assume it is correctly configured (as well as settings.py), because of the credentials error mentioned above (when I try to login with an incorrect user). The error throw in logs when request timeout is the following: File "/usr/local/lib/python3.7/site-packages/requests/sessions.py", line 618, in send 2018-12-20T17:20:56.027703+00:00 app[web.1]: r = adapter.send(request, **kwargs) 2018-12-20T17:20:56.027704+00:00 app[web.1]: File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 508, in send 2018-12-20T17:20:56.027705+00:00 app[web.1]: raise ConnectionError(e, request=request) 2018-12-20T17:20:56.027707+00:00 app[web.1]: requests.exceptions.ConnectionError: HTTPConnectionPool(host='10.5.0.1', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f0cdf24e5c0>: Failed to establish a new connection: [Errno 110] Operation timed out')) 2018-12-20T17:20:56.333701+00:00 app[web.1]: [20/Dec/2018 17:20:56] "POST /admin/login/?next=/admin/ HTTP/1.1" 500 281813 Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect... 2018-12-20T17:20:56.027696+00:00 app[web.1]: File "/usr/local/lib/python3.7/site-packages/requests/api.py", line 58, in request 2018-12-20T17:20:56.027697+00:00 … -
How to add a custom header (JWT AUTH TOKEN) in response and redirect user to another page/url in python djnago
I want to have AUTH header for all django requests and responses. I have a question (python 3.7 - django 2.1): I want to authenticate the users via JWT tokens. I don't want to use Models.py or external libraries like as Rest-Framework. I built a mysql-db for managing CRUD operation for working with JWT-tokens and user-management. Problem: I want to add a "AUTH" header in response (if username and password were correct) to incoming request from "http://127.0.0.1:8080/my_dj_app/register" page; and then i want to redirect user to Login page ("http://127.0.0.1:8080/my_dj_app/dashboard"). So (when user is redirecting to Dashboard, I'm checking the value of AUTH header in DB in GET-request), in Dashboard view, again, I'm checking the AUTH header for authorization/authentication the user. Note: via this topic, i can add AUTH in reponse header. but how i can redirect user to dashboard !? Django: Add response header when using render or render_to_response above scenario is possible !?. how i can do it !?. please help meeeee. response = render(request, "my_dj_app/dashboard.html", {}) response['AUTH'] = JWT_TOkEN return response but above code, can't to solve my problem :( -
Django: is_valid is changing self.object
In my code, you see two print statements. In my form the previously saved value in the database was emailprevious@gmail.com. The new value I entered into the form is emailnew@gmail.com. The expected outcome I had from my print statements: emailprevious@gmail.com self.object.email emailprevious@gmail.com self.object.email 2 Actual outcome: emailprevious@gmail.com self.object.email emailnew@gmail.com self.object.email 2 It seems that self.attendee_form.is_valid(),is changing the self.object. I couldn't find that behaviour defined in the Django source code from is_valid() Can you explain why self.objectis changing? class AssignAttendee(SuccessMessageMixin, SingleObjectMixin, TemplateView): template_name = 'attendees/front/assign_attendee.html' success_message = _("Attendee has been successfully updated.") def get_object(self): return get_object_or_404( Attendee, ticket_reference=self.kwargs['ticket_reference'], ticket_code=self.kwargs['ticket_code'], ) def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) @cached_property def attendee_form(self): return AssignAttendeeForm( prefix='attendee', data=self.request.POST or None, instance=self.object, ) @cached_property def get_consent(self): organizer = self.object.event.organizer return organizer.contacts.filter(email=self.object.email).first() @cached_property def consent_form(self): return AttendeeConsentForm( prefix='consent', data=self.request.POST or None, instance=self.get_consent, email=self.object.email, ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'attendee': self.object, 'attendee_form': self.attendee_form, 'consent_form': self.consent_form, }) return context @transaction.atomic def post(self, request, *args, **kwargs): self.object = self.get_object() # Check if consent already exists which defines if consent entry will be # updated or if a new one will be created. consent = self.get_consent print(self.object.email, "self.object.email") # Validate forms forms = … -
Permissions set in django, but not working after
I've written an app called 'ra' and replaced the user model with a custom one that inherits from AbstractBaseUser and PermissionsMixin. class Credentials(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELD = ['username'] username = models.CharField(max_length=255, null=False, help_text=_('A distinctive and human-readable user name')) email = models.EmailField( help_text=_('Email address')) Surely the settings file is also changed: AUTH_USER_MODEL = 'ra.Credentials' Authentication is working great, but permissions are not. I wrote a test with the following: def setUp(self): self.credentials = Credentials.objects.create( username='Example Username', email='email@example.com' ) add_perm(self.credentials, Credentials, 'add_credentials') print(self.credentials.get_all_permissions()) print(self.credentials.has_perm('ra.add_credentials')) However, get_all_permissions prints and empty set (set()) and has_perm outputs False. This is the code for add_perm: from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission def add_perm(user, model, codename): content_type = ContentType.objects.get_for_model(model) permission = Permission.objects.get(content_type=content_type, codename=codename) user.user_permissions.add(permission) What am I missing? -
Python modulus assignment (%=) for string formatting
Django, for example, uses this code to cater for ValidationError exceptions >>> message = 'My name is %(name)s' >>> params = {'name': 'George'} >>> message %= params >>> print(message): 'My name is George' The only documentation I managed to find on %= is here where it is called a modulus assignment operator. I really do not understand why it works with the old style formatting and I cannot understand how this will be used with the new style formatting. Does the new style formatting render this code redundant? -
Is it possible to override the default of an abstract model in django?
Say I have an abstract model that looks something like this: class CommonInfo(models.Model): id = models.BigIntegerField(primary_key=True, default=get_id, editable=False) class Meta: abstract = True And a class that inherits the abstract model like this: class Concrete(CommonInfo): name = models.CharField() Would it then be possible to later create a Concrete instance that overrides the id in CommonInfo. For instance: Concrete.objects.create(id=1, name="test") I've kind of already tried this and it seems to work but when I try and then sort these objects I get a TypeError: '<' not supported between instances of 'Concrete' and 'Concrete' as seen in this question: Django: TypeError: '<' not supported between instances (model objects) But when I don't override id and just create and object with name: Concrete.objects.create(name="test") no such error is raised. This leads me to believe it isn't actually possible to do what I'm trying to do, is that right or is something else causing the TypeError? -
You don't have permission to view or edit anything
I know this problem has been floated on this platform, but i have tried all solutions without success including reinstalling django. I have the latest django so it is not an issue with upgrade, i have also added admin.autodiscover() in my project urls file as suggested by some people, i have inspected the database(in postgres) and the user is actually a super user, but i cant view my models and apps after logging in from a custom user app, i have this error You don't have permission to view or edit anything. -
Django model for primary and secondary email addresses
I have a Django model that has a foreign key back to a user: class Emails(models.Model): user = models.ForeignKey(CustomUser, unique=True) email1 = models.EmailField() email2 = models.EmailField() email3 = models.EmailField() However, I have two questions: I need way to mark one as the primary email address - is this possible with Django models? Listing out 3 separate fields seems clumsy - is there a more Django-recommended way to store multiple similar values? Note: I'm aware there are a few 3rd party model fields for achieving this, I'm looking for a native approach. -
How do I implement SSL on a private IP?
I am developing a network management product. We ship our product to customers as a VM, which they install on a hypervisor in their network. These VMs are given static, private IP addresses in the customer network. They monitor the customer's devices, and run a (Apache/Django) webserver showing the state of the network. Customers access the site by the private IP and we access the VMs directly using TeamViewer (installed before we ship them), so there's no public IP or domain name involved. We'd very much like to provide SSL certs on our VMs so that clients stop seeing notifications that our site is insecure (and of course, so that our site stops being insecure). Preferably, customers should not have to add trust for a new CA or add security exceptions to their browsers. What is the most efficient and cost effective way to do so? I have tried LetsEncrypt, but they only support certs for domain names, not for IPs. -
Django adding an extra unmanaged field to instance in post_save
I'm trying to perform a HTTP request in my post_save and in case of a failure to connect to the service I want to send a message back to the user via the response from the view. My post_save looks something like this: def test_post_save(instance, created, **dummy): try: success = request_function(instance.item.id) if success: log.debug('Request succeeded') except requests.exceptions.ConnectionError: instance.stop = instance.start instance.save() log.debug('Request failed') The above code works just fine, What I want to do is to add a field to the instance or in someway return a message back to the view's create function which utilizes serializer.data that the request failed. I was hoping to achieve this without adding an extra column on the model's table. I've read about unmanaged models but I couldn't find any reference to an unmanaged field. Is there any other way for me to achieve this? My end goal is to basically send back a message in the response to the client letting them know that the connection failed. -
How to use raw SQL in Django Admin's get_queryset?
I am trying to use Model.objects.raw() in Django Admin but end up with a generic database error: "Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user." admin.py class ChapterAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields':['title','shorthand','description',]}) ] list_display = ('shorthand','title') def get_queryset(self, request): queryset = super(ChapterAdmin, self).get_queryset(request) sql = "SELECT * FROM myapp_chapter" queryset = Chapter.objects.raw(sql) return queryset models.py class Chapter(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=800, blank=True, null=True) shorthand = models.SlugField(max_length=3, unique=True, null=True) def __str__(self): return self.shorthand Everything functions if queryset is set to Chapter.objects.all() instead of Chapter.objects.raw(sql), so I initially assumed that my raw SQL was incorrect. I also read that errors can occur if Models.objects.raw() fails to return rows. However, running SELECT * FROM myapp_chapter in dbshell returns everything normally. How do I get a queryset using raw SQL in Django Admin? For context on why I am choosing to use raw SQL, the shorthand contains a mixture of numeric and alphanumeric values that I need sorted naturally: 1 10 11 4 5 7A 7B I get the results I want in dbshell using SELECT * FROM myapp_chapter ORDER BY shorthand*1, shorthand: … -
Django, Celery - removed tasks showing up with not registered errors in logs
Good afternoon, I have removed some old tasks from Celery and my tasks logs are now being flooded with the below error, I read in a another thread it maybe because of the .pyc files, so I removed them all, however this hasn't helped. When I search my project for the text vpn_3p_data does not exist, I'm not sure where this info is being gathered from nor how to remove it, has anyone come across his before? {"exc_type": "NotRegistered", "exc_message": ["monitoring.tasks.vpn_3p_data"], "exc_module": "celery.exceptions"} -
Django Subquery doesn't escape dates
I have a query that filters registers according to some dates, and uses subqueries to aggregate data. It goes like this: # Parse datetime st_date = timezone.datetime.strptime(...) ed_date = timezone.datetime.strptime(...) # Main queryset clients = Client.objects.all() # Subquery details = Detail.objects.filter( temp__client__id=OuterRef('pk'), temp__datetime__date__range=(st_date, ed_date)) # Filter brand brand_values = detalles.filter( product__brand__id=...).values( 'temp__client') # Aggregate total_qtys = brand_values.annotate(t=Sum('qty')).values('t') # Annotate to main query qs = clients.annotate(brand_1: Subquery(total_qtys, output_field=FloatField())) And it works on my local env, but on production it always returns null for all rows. Upon inspection I noticed that the generated query goes like: SELECT ..., COALESCE((SELECT SUM(U0.`qty`) AS `t` FROM `sales_detail` U0 INNER JOIN `sales_temp` U1 ON (U0.`temp_id` = U1.`id`) INNER JOIN `inventory_product` U3 ON (U0.`product_id` = U3.`id`) WHERE (U1.`cliente_id` = (`sales_client`.`id`) AND DATE( CONVERT_TZ(U1.`datetime`, 'UTC', 'America/Mexico_City')) BETWEEN 2018-12-01 AND 2018-12-31 AND U3.`brand_id` = 6) GROUP BY U1.`client_id` ORDER BY NULL), 0) AS `brand_1` FROM `sales_client` WHERE NOT (`sales_client`.`status_rip` = True) And if I run the raw query against my local db it fails, too. I then noticed that the dates are being unquoted, and the problem is solved by just quoting them, i.e. by replacing 2018-12-01 for '2018-12-01' in the raw query. So the question is: why doesn't … -
How to handle and have 2 types of users in django
I'm working on a project that should handle two types of users. normal users and teachers. I created one major model. actually I extended AbstractUser built-in django model and added some other fields to it. one of extra fields is is_teacher that is BooleanField and default is False. for users registration I created ModelForm from model User that I extended before. and while registration I set default value for is_teacher = False to specify that this user is normal user. and for teachers registration is_teacher = True. This is ok for both users and teachers login and redirecting them to their panel. but issue is coming after that. I need third model for something else. I need to have ManyToMany field in third model with NORMAL users and TEACHERS; both of them but I have only one model. actually I didn't separate users and teachers models from each other. because of that I don't know how to specify ManyToMany relation with users model and ManyToMany relation with teachers. There is something that I can do (maybe) is creating two types of models one for users and one for teachers and in respect of those two models I have to create … -
How to use sitemap with https?
I decided to enable https in Django 1.11.4. Thank you "Let's Encrypt". So I redirected (301) all http requests to https. Also, all non-www (http or https) is redirected (301) to https://www It works fine exept my url https://www.example.com/sitemap.xml which doesn't work currently and since the https passing. It returns a 500 error code and I don't really know why. urls.py from django.conf.urls import url from django.contrib.sitemaps.views import sitemap from example.sitemaps import * from django.conf import settings #Pour charger le favicon media = settings.MEDIA # Dictionary containing sitemap classes sitemaps = { 'products': ArticleSitemap(), } urlpatterns = [ url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] sitemaps.py #Generating Sitemap for Dynamic Urls from django.contrib.sitemaps import Sitemap from wall.models import Articles class ArticleSitemap(Sitemap): changefreq = "weekly" priority = 0.7 def items(self): return Articles.objects.filter(published=True).order_by('-update') def lastmod(self, item): return item.date settings.py INSTALLED_APPS = [ 'django.contrib.sites', #SiteMap 'django.contrib.sitemaps', #SiteMap It was working by http, so there is a modification to do, but I don't know the which one. -
Django: object not iterable
I want to fill my model form with initial data. However, I always receive an 'Attendee' object is not iterable. Full traceback: http://dpaste.com/0BH9MAM When I comment this out: initial=self.object, the error disappears. However, my from is not pre-filled with any data. As I add more forms I can't work with FormMixin or UpdateForm Anyone can help me with that problem? class AssignAttendee(SuccessMessageMixin, SingleObjectMixin, TemplateView): template_name = 'attendees/front/assign_attendee.html' success_message = _("Attendee has been successfully updated.") def get_object(self): return get_object_or_404( Attendee, ticket_reference=self.kwargs['ticket_reference'], ticket_code=self.kwargs['ticket_code'], ) def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) # def post(self, request, *args, **kwargs): # self.object = self.get_object() # return super().post(request, *args, **kwargs) @cached_property def attendee_form(self): return AssignAttendeeForm( prefix='attendee', data=self.request.POST or None, initial=self.object, ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'attendee': self.object, 'attendee_form': self.attendee_form, } return context forms.py class AssignAttendeeForm(forms.ModelForm): class Meta: model = Attendee fields = ( 'ticket_reference', 'first_name', 'last_name', 'company_name', 'email', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ticket_reference'].widget = forms.HiddenInput() self.fields['ticket_reference'].disabled = True for visible_field in self.visible_fields(): visible_field.field.widget.attrs['class'] = 'form-control' -
Copy Model Object From a Model To Another Model In Django
I want to copy data from a model to another model, I found an example Copy Model Object From a Model To Another In Django but I'm getting an error: AttributeError: 'BigAutoField' object has no attribute 'wid'. This is my code: models.py class w_orders(models.Model): Id = models.BigAutoField(primary_key=True) datedefwo = models.DateField(default=datetime.now) datesched = models.DateField(blank=True, null=True) datefinished = models.DateField(blank=True, null=True) sign = models.BigIntegerField(blank=True, null=True) statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES) typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) comments = models.CharField(max_length=254, blank=True, null=True) navid = models.BigIntegerField(blank=True, null=True) navkonsid = models.CharField(max_length=12, blank=True, null=True) navname = models.CharField(max_length=254, blank=True, null=True) navcustadr = models.CharField(max_length=254, blank=True, null=True) navdebt = models.FloatField(blank=True, null=True) navpropcode = models.CharField(max_length=254, blank=True, null=True) navdepcode = models.CharField(max_length=254, blank=True, null=True) navphoneno = models.CharField(max_length=254, blank=True, null=True) navreasoncomp = models.CharField(max_length=254, blank=True, null=True) nightshift = models.BooleanField(default=False) priority = models.BigIntegerField(blank=True, null=True) stid = models.BigIntegerField(blank=True, null=True) mapurl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.Id def save(self, *args, **kwargs): super(w_orders, self).save(*args, **kwargs) newob = tobjects() ... newob.save() class tobjects(models.Model): oid = models.BigAutoField(primary_key=True) wid = models.ForeignKey(w_orders, on_delete=models.CASCADE, default=1) objtypegisid = models.BigIntegerField(blank=True, null=True, default=1) objgisid = models.BigIntegerField(blank=True, null=True, default=1) condgenid = models.BigIntegerField(blank=True, null=True, default=1) condriskid = models.BigIntegerField(blank=True, null=True, default=1) condratsid = models.BigIntegerField(blank=True, null=True, default=1) condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1) condmhwallid = models.BigIntegerField(blank=True, null=True, default=1) condpipehydrsid … -
Disabling formset form field
I am trying to disable some formset form fields. But i couldn't achieve it. I have below formset. If the status is Missing the related status field should be disabled. So that nobody can change it. If the status is Report the field will be enabled so that somebody can change it. the DB value of Missing is 1 and Report is 2. I tried below code in the views.py but i get error. 'TypedChoiceField' object has no attribute 'value' for form in formset: if form.fields["status"].value() == 1: form.fields["status"].widget.attrs['disabled'] = True The status field in model is : status = models.IntegerField(choices=STATUSES, default=None, verbose_name=_("Status"))