Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django & MongoDB has issue with default ID autoField on django models
I have Django 2 that the Rest Framework and Djongo is used in it. The Account can be created but when I try to see the list of created Accounts to updated or do any operation on them I can't actually I can't retrieve the list of Accounts and gives me error on ID field. I think this is an issue with MongoDB, so how I can fix this issue? Here is the error that I have that followed by my Account related codes MigrationError at /Accounts/account/ id Request Method: GET Request URL: http://localhost:8000/Accounts/account/ Django Version: 2.2.7 Exception Type: MigrationError Exception Value: id Exception Location: C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\sql2mongo\query.py in _align_results, line 287 Python Executable: C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.0 Python Path: ['E:\Project\accountingPy', 'C:\Users\PC ' '001\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32', 'C:\Users\PC 001\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\PC ' '001\AppData\Local\Programs\Python\Python38-32\lib\site-packages'] Server time: Mon, 6 Apr 2020 15:00:38 +0000 The record that stored in database // 1 { "_id": ObjectId("5e8b3a0c10fc9f40cdca44be"), "label": "Mapping", "owner": "Nasser", "balance_currency": "USD", "balance": "23.00", "desc": "This the Cash account that manage by cash payments", "status": true, "created_at": ISODate("2020-04-06T14:17:48.838Z"), "updated_at": ISODate("2020-04-06T14:17:48.838Z") } Account model class Account(models.Model): class Meta: db_table = 'account' def __str__(self): return self.label label = models.CharField(max_length=20,unique=True) owner = models.CharField(max_length=20) balance = … -
How to upgrade python version inside a virtual environment (in windows)
How to make my virtual environment use same version of python installed in my system. (see picture) -
How to create auto generate code in django
I have a company, department, and item list. in item list company and department are foreign keys. so when I add an item into the item list, item will generate a code for itself automatically like from company name's 3 alphabets, department name's 3 alphabets and 4 or 5 digits no. starting from 0001 and auto-increment. each company item will start from 0001. As an example: If a company is "ABCDE" and the department is "Finance" the code will be auto-generated like ABC-Fin-0001. is there any way to get these things done? Model_Class class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) item_choice = ( ('IT','IT'), ('Electronics', 'Electronics'), ) item_type = models.CharField(max_length=255, blank =True, choices = item_choice ) code = models.CharField(unique=True, max_length=255) company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True) department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True) My_view def item_entry(request): title = 'Add Item' form = ItemForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/item_list') context = { "title": title, "form":form } return render(request,'item_entry.html', context) Form_View class ItemForm(forms.ModelForm): class Meta: model = Item fields = ("item_name","item_type", "code","company","department",) Template_view <table> <tr> <th>#</th> <th>Item Name</th> <th>Item Type</th> <th>Code</th> <th>Company</th> <th>Department</th> </tr> {% for instance in queryset %} <tr> <td>{{forloop.counter}}</td> <td><a href="{% … -
Django: How can i get multiple model class fields in one model with our without foregin key
Models.py I have a model like these. I'm trying to access 2 fields from all top 4 models into last model class(UserTimeZone) but im getting only one field from each models,anyone if anyone who can understand these problem,it will be a great help for me. class ControllerParameters(models.Model): ControllerName = models.CharField(max_length=50,null=True) ControllerID = models.IntegerField(null=True) . #multiple fields here.. def __str__(self): return self.ControllerName class DoorInfo(models.Model): DoorName = models.CharField(max_length=50, null=True) DoorSensor = models.CharField(max_length=10, choices=SensorChoice,default=True) . #multiple fields here.. In DoorInfo Table i have fixed 4 door records like,door1,door2,door3,door4 class Enrollment(models.Model): userid = models.CharField(max_length=15,blank=True,null=True) username =models.CharField(max_length=15,blank=True,null=True) . #multiple fields here.. class TimeZone(models.Model): timezoneid = models.CharField(max_length=50,choices=Timezone_Choices,blank=True, null=True) timezonename = models.CharField(max_length=100,db_column='TimeZone Name', blank=True, null=True) . #multiple fields here.. class UserTimezone(models.Model): employeeid = models.CharField(max_length=20, blank=True, null=True) employeename = models.ForeignKey(Enrollment, related_name="enrollment", on_delete=models.SET_NULL,null=True) controllerid = models.CharField(max_length=20, blank=True, null=True) controllername = models.ForeignKey(ControllerParameters, related_name="controlparameter", on_delete=models.SET_NULL,null=True) doornumber = models.IntegerField(blank=True, null=True) doorname = models.ForeignKey(DoorInfo,related_name="doorname", on_delete=models.SET_NULL,null=True) timezoneid = models.IntegerField(blank=True, null=True) timezonename = models.ForeignKey(TimeZone, related_name="timezone", on_delete=models.SET_NULL,null=True) views.py this code might be totally wrong as per my requirement so not understanding how can i do queryset, def usertimezone(request): timez = TimeZone.objects.all() text = DoorInfo.objects.all() enroll = Enrollment.objects.all() usertext = UserTimezone.objects.all() if request.method == "POST": userform = UserTimezoneForm(request.POST) if userform.is_valid(): userform.save() userform =UserTimezoneForm() context = {'userform':userform,'usertext':usertext, 'enroll':enroll,'text':text,'timez':timez, … -
How to redirect from one page to another in Django
I have created sign up Page and I want to redirect to login if the user is already registered. I am confused about how to do it in views I am also attaching views.py Thanks. def register(request): if request.method == 'POST': first_name = request.POST['Firstname'] last_name = request.POST['Lastname'] username = request.POST['Username'] password1 = request.POST['password'] password2 = request.POST['password1'] email = request.POST['email'] user = User.objects.create_user(username=username, password= password1, first_name=first_name, last_name=last_name, email=email) user.save() print('user Created') return redirect('/') else: return render(request, 'register.html') -
How to define django-imagekit ImageSpecFields in parent/mixin class?
I'm using django-imagekit to provide thumbnail versions of uploaded images on my Django models. I would like to define various thumbnail ImageSpecFields in a mixin that my models can then inherit. However, each model currently has a different name for the ImageField on which its ImageSpecFields would be based. I've tried this: from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFit class ThumbnailModelMixin(models.Model): IMAGE_SPEC_SOURCE_FIELD = None list_thumbnail = ImageSpecField( processors=[ResizeToFit((80, 160)], source=IMAGE_SPEC_SOURCE_FIELD, format="JPEG", options={"quality": 80} ) class Meta: abstract = True class Book(ThumbnailModelMixin): IMAGE_SPEC_SOURCE_FIELD = "cover" cover = models.ImageField(upload_to="books/") class Event(ThumbnailModelMixin): IMAGE_SPEC_SOURCE_FIELD = "ticket" ticket = models.ImageField(upload_to="events/") But, as expected, this fails with: Exception: ThumbnailModelMixin does not define any ImageFields, so your list_thumbnail ImageSpecField has no image to act on. Is there a way to get inheritance like this to work? There are at least two other solutions: Don't use a mixin/parent, and include the ImageSpecFields on each child class - a lot of duplicate code. Change the Book.cover and Event.ticket fields to have the same name, like image and use "image" for the ImageSpecField source parameter. The latter sounds best, but I'm still curious as to whether there's a way to get the inheritance working? -
How to display chosen poll option alongside overall results in Django
I'm new to Python & Django and I have been following the App tutorial that the Django Documentation has. I have made the routes and everything is working, the issue I am having is that I want to be able to show what poll option the user chose on the result page. (The result page currently only shows the overall result of the poll, which I do want to keep but I also want to display the selected choice in addition to that.) The user does not have to be logged in so I haven't created a foreign key to tie a user to their vote. I figured out a way to add the selected choice primary key to the URL but as i'm using class based views i'm not sure how to get that value in the result view. urls.py ... app_name = "polls" urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/<int:choice_id>', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] ... views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) ... #removed the test part else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id, selected_choice.id))) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' -
Upload Image Django and AJAX
I'm trying to upload an image using django and ajax, but it doesn’t load in the database. This appears: C:/fakepath/img.png. As far as I understand that the problem is in Ajax, it saves all the rest of the form data well, but it doesn’t work with photography, how to solve this problem? FORM: <div class="table-responsive"> <form id="addProduct" enctype="multipart/form-data" action=""> <div class="form-group"> <input class="form-control" type="text" name="sku" placeholder="sku" required> </div> <div class="form-group"> <input class="form-control" type="text" name="product_name" placeholder="name" required> </div> <div class="form-group"> <input class="form-control" type="number" name="price" placeholder="price" required> </div> <div class="form-group"> <input class="form-control" type="number" name="qty" placeholder="qty" required> </div> <div class="form-group"> <input class="form-control" type="file" name="picture" placeholder="PIC" required> </div> <button class="btn btn-primary form-control" type="submit">Save</button> </form> </div> JS: $("form#addProduct").submit(function() { var skuInput = $('input[name="sku"]').val().trim(); var nameInput = $('input[name="product_name"]').val().trim(); var priceInput = $('input[name="price"]').val().trim(); var qtyInput = $('input[name="qty"]').val().trim(); var pictureInput = $('input[name="picture"]').on('change', prepareUpload); function prepareUpload(event) { files = event.target.files; } if (skuInput && nameInput && priceInput && qtyInput && pictureInput) { // Create Ajax Call $.ajax({ url: '{% url "ajax_addown_offer" instance.id %}', data: { 'sku': skuInput, 'product_name': nameInput, 'price': priceInput, 'qty': qtyInput, 'picture': pictureInput }, dataType: 'json', success: function (data) { $('#order_item_container').html(data.result) } }); } else { alert("All fields must have a valid value."); } $('form#addProduct').trigger("reset"); return false; … -
trouble being spyed on [closed]
Ok Im brand new to all this and dont know the FIRST THING about coding, however EEXTREAMLY INTRIGUED since i believe that im being spyed on or hacked by my soon to be ex. It started 6 years ago and has BAFFELED ME TO NO END!!! Long story short,,, I finally figured out its GOTT BE CODING BEING SOMEHOW WRITTEN INTO ALREADY EXISTING PROGRAMS LIKE MICROSOFT, AND EVEN THE INTERNET ITSELF KEEPING ME FROM FINDING TRACES OF HIS CHEATING AND KEEPING AN EYE ON ME TO MAKE SURE I DONT CATCH HIM. My question is--AM I CCRAZY? OR IS THIS PISSIBLE? IF SO...HOIW DO I RECOGNIZE THE CHANGES IN WHAT IS SUPPOSED TO BE IN A ROOT FILE ANDBWHAT HAS BEEN CREATED TO DETER, SPY, OR FLAT OUT SCREW WITH MY HEAD? -
Django/Nginx: Restricting access to content on a subdomain
I have a Django app at www.mydomain.com that will be redirecting users to video streams on a subdomain meetings.mydomain.com. A user will purchase a license to view the stream, and then be able to view it. I can authenticate users with a JWT (JSON Web Token). Problem How to restrict access to the content on this subdomain so that only the users with a license may view this content? I am trying to a situation where a user shares a token which allows people that have not paid to access the stream. Questions Is it possible to block direct access to a URL via Nginx? Or is there a smarter approach with Django? -
Django rest framework, error when creating user field in serializer
I have an API that didn't contain a created by user field. I decided to add such field in the serializer: class PointsSerializer(PermissionRequiredMixin, HyperlinkedModelSerializer): date_added = DateTimeField(format="%d-%m-%Y", required=False, read_only=True) created_by = serializers.CharField(default=CurrentUserDefault(),) class Meta: model = Points fields = ( 'created_by', 'MissionName', 'location_name', 'GDT1Latitude', 'GDT1Longitude', 'UavLatitude', 'UavLongitude', 'UavElevation', 'Area', 'date_added' ) until now my logic in the view worked fine, after migrating to this changes I started getting this error in the view when trying to serialize data and use it: class PointsViewSet(ModelViewSet): # Return all order by id, reversed. queryset = Points.objects.all().order_by('-id') serializer_class = PointsSerializer data = queryset[0] serialized_data = PointsSerializer(data, many=False) pprint(serialized_data) points = list(serialized_data.data.values()) search_fields = ['MissionName', 'date_added'] ordering_fields = ['id', 'MissionName', 'Area', 'date_added'] filter_backends = (filters.SearchFilter, filters.OrderingFilter) @action(detail=True, methods=["post"]) def last_object_by_user(self, request, *args, **kwargs): # your query to get the last object by your user queryset = Points.objects.filter(created_by=request.user).latest() return queryset the error being raised on point variable: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/yovel/PycharmProjects/Triangulation/ven/lib/python3.7/site-packages/rest_framework/fields.py", line 454, in get_attribute return get_attribute(instance, self.source_attrs) File "/home/yovel/PycharmProjects/Triangulation/ven/lib/python3.7/site-packages/rest_framework/fields.py", line 94, in get_attribute instance = getattr(instance, attr) AttributeError: 'Points' object has no attribute 'created_by' During handling of the above exception, another exception occurred: Traceback (most recent call last): … -
dynamic url for specific primary key in Django
My models has a field call 'topic', then I want to create a page which can show the specific, and the urls can be dynamic path to different topics on 1 html. How do I suppose to do it? models.py: TOPIC = ( (0,"Finance"), (1,"Toys"), (2,"Foods"), (3,"Travel"), ) class Post(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True, max_length=200) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField(auto_now_add=True) body = RichTextField(null=True) status = models.IntegerField(choices=STATUS, default=0) topic = models.IntegerField(choices=TOPIC, default=0) cover_img = models.ImageField(upload_to='post_cover', null=True, default='post_cover/coming_soon.jpg') def __str__(self): return self.name def get_img(self): return f"{'/media/post_cover/'+self.cover_img}" html <div class="col-md-6 mt-3 "> <a href="{% url 'post_list' %}"> <img src="../media/topic/travel3.jpg" alt=''> </a> </div> views.py def post_list(request): posts = Post.objects.filter(topic=0) context = {'posts': posts, 'autor_list':autor_list} return render(request, 'post_list.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('finance/', views.post_list, name='post_list'), path('<slug:slug>/', views.post_detail, name='post_detail'),] -
Django - choose Choice value depending on view loaded
I have a (forms.form) class where I have choices. I wish to decide whenever I load view_1, that the choice for that view is choice_A, and then when I load view_2, that the choice for that view is choice_B. So depending on the view loaded the choice value changes accordingly. Class for CreateGameForm(forms.form) class CreateGame(forms.Form): game_choices = ([ ('choice_A', 'choice_A'), ('choice_B', 'choice_B') ]) game = forms.ChoiceField(choices=game_choices , required=True) I have tried to make it work with changing the initial value by adding one to the game, and then in def init adding it together with a function that changes the initial value when the view/URL_pattern changes, but without much luck. Any ideas? -
Can i see images and files in Django-admin?
I have model name photos which has already register in Django-admin.it has two columns one is simple char field and other is file field.when i try to open the files of different objects of photos model in Django-admin i'm getting this warning from Django-admin. Check the warning image here all media files are properly present in media folder present in project.how i can see the images or files in Django-admin. -
ModuleNotFoundError: No module named 'jose'
I am using python-social-auth in my django project to use social platforms for authentication in my project. It all worked well but am getting this error ModuleNotFoundError: No module named 'jose' This is the whole error: [05/Apr/2020 14:01:00] "GET /accounts/login/ HTTP/1.1" 200 3058 Internal Server Error: /login/twitter/ Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\social_core\backends\utils.py", line 50, in get_backend return BACKENDSCACHE[name] KeyError: 'twitter' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Ahmed\AppData\Roaming\Python\Python37\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ahmed\AppData\Roaming\Python\Python37\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ahmed\AppData\Roaming\Python\Python37\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ahmed\AppData\Roaming\Python\Python37\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Program Files\Python37\lib\site-packages\social_django\utils.py", line 46, in wrapper backend, uri) File "C:\Program Files\Python37\lib\site-packages\social_django\utils.py", line 27, in load_backend Backend = get_backend(BACKENDS, name) File "C:\Program Files\Python37\lib\site-packages\social_core\backends\utils.py", line 53, in get_backend load_backends(backends, force_load=True) File "C:\Program Files\Python37\lib\site-packages\social_core\backends\utils.py", line 35, in load_backends backend = module_member(auth_backend) File "C:\Program Files\Python37\lib\site-packages\social_core\utils.py", line 62, in module_member module = import_module(mod) File "C:\Program Files\Python37\lib\site-packages\social_core\utils.py", line 56, in import_module __import__(name) File "C:\Program Files\Python37\lib\site-packages\social\backends\google.py", line 3, in <module> from social_core.backends.google_openidconnect import GoogleOpenIdConnect File "C:\Program Files\Python37\lib\site-packages\social_core\backends\google_openidconnect.py", line 5, in <module> from .open_id_connect import OpenIdConnectAuth File "C:\Program Files\Python37\lib\site-packages\social_core\backends\open_id_connect.py", … -
problem with timezone and datetime libs in Django 2 and python 3
I'm a bit confused by the daylight savings handling. I have working on web notifier application in Django 2.0.6 framework and python 3.6. this application provide scheduling notification. for example users schedule message for some hours later or a few days later. this website is available in only one time zone. I have use this settings in Django: ... TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True ... when I run this code in python manage.py shell: >>> from django.utils import timezone >>> from datetime import datetime >>> timezone.now() >>> datetime.now() django timezone.now() return to me datetime with tzinfo UTC and datetime.now() return to me correct time information with correct time zone info. when I made USE_TZ=False in django setting to find out timezone.now() in django return correct time zone information like datetime.now(). in Django time zone document said: ''This is handy if your users live in more than one time zone and you want to display datetime information according to each user’s wall clock.good practice to store data in UTC in your database. The main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring … -
How to send data from external python script to django view
I've written a python script on my raspberry pi. I want to send it to my django view function, but I keep running into csrf token issues. I've read about the work around using the decorator, but I want to know if there is a more clean way in sending data to a django view. -
Typeerror: Missing one required argument in content
The code is below if request.method == 'POST': record_name = request.POST.get('recordname') record_date = request.POST.get('recorddate') record_generate_by = request.POST.get('recordgenerateby') record_description = request.POST.get('recorddescription') record_file = request.FILES.get('recordfile') record_image = request.FILES.get('recordimage') fs = FileSystemStorage if record_file is None: record_file = 'No File' else: fs.save(record_file.name , record_file) if record_image is None: record_image = 'No Image' else: fs.save(record_file.name , record_file) I used this API(FileSystemStorage) many times, but this time it shows error like this and already used this API in previous function and MEDIA_ROOT and MEDIA_URL is all set. The previous function stores file and image successfully, but this shows this kind of type error. Now what's the solution: The error is File "C:\Users\Mahad Akbar\PycharmProjects\FYP\Healthcare\myapp\views.py", line 754, in addnewRecord fs.save(record_file.name , record_file) TypeError: save() missing 1 required positional argument: 'content' [06/Apr/2020 17:15:28] "POST /addnewRecord HTTP/1.1" 500 72349 -
Django distinct count annotation not counting distinct
I am trying to annotate a queryset with a related object count, however it seems to be counting the same records multiple times even though I am passing the count=True flag: obj.some_set.annotate(rel_ct=Count('rel', distinct=True)).values('pk', 'name', 'pc') Problem: some results o.rel_ct returns a greater number than the real count o.rel_set.count(). I've tried ordering the original queryset to no avail. Not that it should matter because distinct=True should take care of that. -
How can I show a help text for models/databases in admin interface?
In the Django admin interface (Home -> Database -> Database administration) I'd like to show an additional help text as column in the list of databases/models (Database). How can I achieve this? -
How can I show model/database in admin interface for superuser only?
In the Django admin interface (Home -> Database -> Database administration) I'd like to show the databases/models (Database) for superusers only. How can I achieve this? -
How do I build an elsaticsearch_dsl query with wildcards?
I'm trying to build a wildcard query in elasticsearch_dsl (I'm using django_elasticsearch_dsl). This is a simplified bit of code when I've received a search_term search_term = '*' + search_term + '*' sqs = documents.OrganisationDocument.search() query = Q('wildcard', name=search_term) sqs = sqs.query(query) data = sqs.execute(ignore_cache=True).to_dict()['hits']['hits'] If provides no results and I'm not getting an error But if I replace wildcard with match I do get results based on the complete words entered (not the partial words). I'm guessing I've got something wrong with my field definitions but I don't know what - can anyone advise? -
How to integrate google calendar in my local django project
Hey i am a django beginner so want to know how to integrate full funcitonal google calendar in my local django project? Thanks for any related help or guidance in advance. -
Hosting Django in Apache
I try to host Django at Apache using mod_wsgi and following a nice tutorial. I have a Windows 7 OP, and I had everything set as described by the tutorial, however, I get this Error 500 for which I paste the ErrorLogs below: [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] mod_wsgi (pid=7784): Failed to exec Python script file 'D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app/wsgi.py'. [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] mod_wsgi (pid=7784): Exception occurred processing WSGI script 'D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app/wsgi.py'. [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] Traceback (most recent call last):\r [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] File "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app/wsgi.py", line 16, in <module>\r [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] application = get_wsgi_application()\r [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] File "c:\\users\\adwy\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\django\\core\\wsgi.py", line 12, in get_wsgi_application\r [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] django.setup(set_prefix=False)\r [Mon Apr 06 14:37:28.669698 2020] [wsgi:error] [pid 7784:tid 1048] [client 95.47.51.217:48374] File "c:\\users\\adwy\\appdata\\local\\programs\\python\\python35\\lib\\site-packages\\django\\__init__.py", line 19, … -
Creating a form from a model - Django
I am running into trouble here. Here is my form: class PublishBiddingForm(forms.Form): class Meta: model = Puja fields = ("title", "video", "photo", "bidding_end","starting_price") def save(self, commit=True): Puja = super(PublishBiddingForm, self).save(commit=False) if commit: Puja.save() return Puja Here is my model: class Puja(models.Model): seller = models.OneToOneField(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=100) video = models.FileField() photo = models.ImageField() published_date = models.DateTimeField("Published: ",default=timezone.now()) bidding_end = models.DateTimeField() starting_price = models.IntegerField(default=1) def __str__(self): return str(self.title) my view: def is_seller(user): try: return user.is_authenticated and user.seller is not None except Seller.DoesNotExist: return False @user_passes_test(is_seller) def publish_bidding(request): if request.method == "POST": form = PublishBiddingForm(request.POST) if form.is_valid(): Puja = form.save() titulo = form.cleaned_data.get('title') messages.success(request, f"New bid created: {titulo}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") return render(request = request, template_name = "user_templates/register.html", context={"form":form}) form = PublishBiddingForm return render(request = request, template_name = "publish_bidding.html", context={"form":form}) and the error: Does anybody know what is going on ? I have a register form successfully implemented, and I used it as a model to create this one, but I only get errors. Any help would be much appreciated.