Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect payment to order in django
i'm trying to do something. i'm trying to do something in my code that once the payment is confirmed, the order would be stored in the database. i was following this tutorial but i got lost because we are using different payment gateway he is using stripe, i'm using flutterwave my codes javascript document.addEventListener("DOMContentLoaded", (event) => { // Add an event listener for when the user clicks the submit button to pay document.getElementById("submit").addEventListener("click", (e) => { e.preventDefault(); const PBFKey = "xxxxxxxxxxxxxxxxxxxx"; // paste in the public key from your dashboard here const txRef = ''+Math.floor((Math.random() * 1000000000) + 1); //Generate a random id for the transaction reference const email = document.getElementById('email').value; var fullname= document.getElementById('fullName').value; var address1= document.getElementById('custAdd').value; var address2= document.getElementById('custAdd2').value; var country= document.getElementById('country').value; var state= document.getElementById('state').value; var address1= document.getElementById('postCode').value; const amount= document.getElementById('total').value; var CSRF_TOKEN = '{{ csrf_token }}'; const payload = { 'firstName': $('#fullName').val(), 'address': $('#custAdd').val() + ', ' + $('#custAdd2').val() + ', ' + $('#state').val() + ', ' + $('#country').val(), 'postcode': $('#postCode').val(), 'email': $('#email').val(), } getpaidSetup({ PBFPubKey: PBFKey, customer_email: email, amount:"{{cart.get_total_price}}", currency: "USD", // Select the currency. leaving it empty defaults to NGN txref: txRef, // Pass your UNIQUE TRANSACTION REFERENCE HERE. onclose: function() {}, callback: function(response) { flw_ref … -
How to fix 504 Gateway Time-out while connecting to google calendar api
I have created project which fetch one month events of all the calendars in my calendar list. To do this, I followed google calendar api documentation Quickstart. This is function which connect to google api. def connect_google_api(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) I hosted the website using Apache and all the pages are working except google calendar. I first thought that there might be some problem while reading credentials.json so I use this to find out data = None with open('credentials.json') as f: data = json.load(f) qw = data Website is still in debug mode so I made some error to check local variable and I found out that data and qw variable contains credentails.json. I think the problem is happening because of the below two lines flow = InstalledAppFlow.from_client_secrets_file('credentials.json',SCOPES) creds = flow.run_local_server(port=0) I opened credentails.json and i found this redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"] I changed http://localhost to http://test.example.com/. I dont know what to put at the place of http://localhost. I want to find out what changes are required in this code … -
How to get the authentication process for the hikevision cctv dvr setup for my python application
i am into integrating the hike vision CCTV into my python application can anybody help me with the starting authentication and how i can get the IP of the device without taking it from the connected devices. -
how to obtain the registration_id for FCM-Django push notifications (flutter app)
I am using django as my back end for my flutter app. And just wanted to learn how to implement push notifications. is there a way to get the registration_id of a device to send push notifications without adding the firebase_messaging/firebase_core packages to my flutter package? I feel like its excessive to get those packages to just register the device token. Or is this the only way^ I am using the FCM-django package to send notifications but need to save the registration_id of the device for each user in my database. -
Django collectStatic command failed on Deploy to ElasticBeastalk with S3
I am attempting to change my Django application to use S3 for static and media storage. It is working without issue on a local machine and I'm able to run "collectstatic" locally. When I deploy to the Elastic Beanstalk instance I get this error: ERROR Instance deployment failed. For details, see 'eb-engine.log'. INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. ERROR Failed to deploy application. In eb-engine.log: [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: container commands build failed. Please refer to /var/log/cfn-init.log for more details. In cfn-init.log [INFO] -----------------------Starting build----------------------- [INFO] Running configSets: Infra-EmbeddedPostBuild [INFO] Running configSet Infra-EmbeddedPostBuild [INFO] Running config postbuild_0_LocalEyes_WebApp [ERROR] Command 00_collectstatic (source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput) failed [ERROR] Error encountered during build of postbuild_0_LocalEyes_WebApp: Command 00_collectstatic failed Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 00_collectstatic failed [ERROR] -----------------------BUILD FAILED!------------------------ [ERROR] Unhandled exception during build: Command 00_collectstatic failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 135, … -
How to use one application in two different projects in Django
'''I made testapp application in baseproject here I create urls.py in testapp and include in base project , Now I just copy paste the testapp in derivedproject with all urls.py file and views.py , when I add the testapp urls in derived project urls.py using include function it is showing error... I want to inform you that I made two projects in same directory and manage.py is inside the projects Now I am pasting the whole error.....''' PS C:\Users\hp\Desktop\For Django\day2\derivedproject> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen … -
Am trying to display only the appointments that the current logged in user has made, but i end up fetching all the appointments from the database
this the views.py file how can i display the appointments made the current logged in user def user(request): client = Client.objects.all() appointments = Appointment.objects.all() context = {'appointments': appointments, 'client': client, } return render(request, 'users/user.html', context) -
What is the best way to host a React Native mobile app with a Django backend on AWS?
I want to build a mobile app using React Native (frontend) and Django (backend). I've never done this but ideally my application would have a simple frontend UI that displays data retrieved from Django (backend) which retrieves it from the MySQL database. I am trying to grasp how I could host this using AWS but am having trouble as I cannot find the same question online. I have lots of programming experience but am a beginner when it comes to actually deploying code. I could be thinking about this completely wrong, I am pretty lost, so any help would be very useful. Thank you in advance! -
AWS SES sending email from Django App fails
I am trying to send mail with using SES and already setup the mail configuration. Now SES running on production mode -not sandbox-. But in Django App, when I try to send mail nothing happens. it's only keep trying to send, no error. in setting.py made the configuration. INSTALLED_APPS = [ 'django_ses', ] EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_SES_REGION_NAME = 'ap-northeast-1' AWS_SES_REGION_ENDPOINT = 'email-smtp.ap-northeast-1.amazonaws.com' and email method. def send_mail(request, user, emails, subject, path): current_site = get_current_site(request) message = render_to_string(f"store/emails/{path}.html", { "some": "context" }) send_email = EmailMessage(subject, message, "info@mydomain.com", to=emails) send_email.send() By the way I already verified the info@mydomain.com in SES console. And when I try to send email from the SES console using send test email option, I can send without a problem. But in Django App. I can't. Is there any other settings should I do. Because I can't see any error popping when I try to send mail. It's only keep trying to send. But it can't. -
How to send javascript list from template to request.POST (django framework)
I have the javascript below that gets all checked box and it works well. <script> function addlist() { var array = [] var checkboxes = document.querySelectorAll('input[type=checkbox]:checked') for (var i = 0; i < checkboxes.length; i++) { array.push(checkboxes[i].value); } document.write(array); } </script> I want to know how to submit the list array to views.py and get it via request.POST[''] Any suggestions? -
Datalist with free text error "Select a valid choice. That choice is not one of the available choices."
I am building a Create a Recipe form using crispy forms and I am trying to use a datalist input field for users to enter their own ingredients, like 'Big Tomato' or select from GlobalIngredients already in the database like 'tomato' or 'chicken'. However, regardless of whether I enter a new ingredient or select a pre-existing one, I am getting the following error: "Select a valid choice. That choice is not one of the available choices.". How do I fix this error? Visual: models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) websiteURL = models.CharField(max_length=200, blank=True, null=True) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) notes = models.TextField(blank=True, null=True) serves = models.CharField(max_length=30, blank=True, null=True) prepTime = models.CharField(max_length=50, blank=True, null=True) cookTime = models.CharField(max_length=50, blank=True, null=True) class Ingredient(models.Model): name = models.CharField(max_length=220) def __str__(self): return self.name class GlobalIngredient(Ingredient): pass # pre-populated ingredients e.g. salt, sugar, flour, tomato class UserCreatedIngredient(Ingredient): # ingredients user adds, e.g. Big Tomatoes user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True, null=True) quantity = models.CharField(max_length=50, blank=True, null=True) # 400 unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc forms.py class RecipeIngredientForm(forms.ModelForm): def … -
django models related manager
I want to develop DJANGO Application for rooms booking. I want to use following TWO models. class Room(models.Model): room_no = models.IntegerField() remarks = models.CharField(max_length=100) def __str__(self): return self.remarks class Roombooking(models.Model): room = models.ForeignKey(Room, related_name= 'roombookingforroom', on_delete=models.CASCADE) booked_for_date = models.DateField(blank=True, null=True) booked_by = models.TextField(max_length=1000, default='') remarks = models.CharField(max_length=100,) class Meta: constraints = [ models.UniqueConstraint( fields=["suit", "booked_for_date"], name="unique_room_date", ), ] def __str__(self): return self.room.remarks To avoid assigning one room to 2 different persons on any day, “ UniqueConstraint” is used. Now, how to query the list of rooms which are vacant from DATE1 to DATE2 -
Why can't django find the environment.py file?
I've been running a django project locally by running the following command environment.py -r When I tried running the project locally again I got the following message The system cannot find the path specified. Why am I receiving this message in the command prompt when the path for this file exists in my repository? -
How to send data to a flask template as a string with \n in it
My code is supposed to send data taken from a json file and then take a specific element of the json and send it to a flask template. There, it will be put into a CodeMirror object and sent to a div. My problem is that when i do {{ context }} it actually puts the return in there. <header> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css"></link> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </header> <body> <div id="ff-cool" style= "border: 1px solid #ddd" name="code"></div> <div id="mydiv" dataa="{{ context }}"> </div> <script type="text/javascript"> var t = CodeMirror(document.querySelector('#ff-cool'), { lineNumbers: true, tabSize: 2, value: $("#mydiv").data("dataa") }); //alert("{{context.code}}"); </script> </body> @app.route('/n/<note>') def no(note): global js try: f = js[note] except: return "no" context = {"code": f["code"]} #problem is in templates/display.html return render_template("display.html", context = context) {"5XqPNXl": {"title": "De", "code": "hi\nfw\nfwe", "user": "De", "pass": "de", "priv": true}} There are no error messages because this is a problem with the html itself. -
Django table.objects.filter(__icontain) return wrong data (sometimes)
I start Django fews days ago (Django 3.2.9) for a personnal project with sqlite3. I have a table with 10000+ entries about card, with specific id_card, name, description... I made pages for listing and searching cards my problem came with the searching "engine" : My search is made with a query in URL (named 'query') but I got the same problem if I use post data. My views.py looks like this : def search(request): query = request.GET.get('query') if not query: all_cards= Cards.objects.all() context = { 'card_list': all_cards, 'paginate': True, } return render(request, 'collection/search.html', context) else: # title contains the query is and query is not sensitive to case. spe_cards = Cards.objects.filter(name__icontains=query).order_by('-type_card') if not spe_cards .exists(): spe_cards = Cards.objects.filter(name_en__icontains=query) else: spe_cards = Cards.objects.filter(desc__icontains=query) title = "Résultats pour la requête %s"%query context = { 'liste_carte': spe_cards, 'title': title, 'paginate': True, } The problem is on this line spe_cards = Cards.objects.filter(name__icontains=query).order_by('-type_card') the filter "__contains" or "__icontains" work only for fews requests with partial response. I take three search with : One request correct with all the cards searched One request incorrect with 0 cards returned One request incorrect with few good cards returned but not all Each request work in django shell but … -
Not getting input from form Django
I'm using Django's forms.py method for building a form, but am not getting any data when trying to user request.POST.get('value') on it. For every print statement that gave a response, I put a comment next to the command with whatever it returned in the terminal. Additionally, I do not understand what the action = "address" is meant for in the form. Finally, the csrf verification was not working and kept returning CSRF verification failed so I disabled it, but if anyone knows how to get this working I would appreciate it. forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Enter name:', max_length=100) views.py @csrf_exempt def blank(request): if request.method == 'POST': get = request.POST.get print(f"get: {get}") # get: <bound method MultiValueDict.get of <QueryDict: {}>> print(f"your_name: {request.POST.get('your_name')}") # your_name: None form = NameForm(request.POST) if form.is_valid(): your_name = form.cleaned_data["your_name"] print(f"your_name cleaned: {your_name}") return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'blank.html', {'form': form}) blank.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <form action="" method="post"> {{ form }} <input type="submit" value="Submit"> </form> </body> </html> -
Using 2 different models on a same html Forms
How will the view code part based on Class-based view will look like if i have for example this 2 models Class Student with two columns name and last_name Class City name and street The form will be in a html file, in this case it will have the 4 inputs, -
django save() refuses to update an existing record
I've got the below model and a function that I call from view.py to update a field within that model called unread_count. However, it keeps trying to create a record rather than update the existing one and I get the error shown below. I've included 2 print statements to show the records exist. I've tried various things to get it working but I'm not making any progress (besides tearing my hair out). Any help would be appreciated. class RoomOccupier(TimeStampedModel): room = models.ForeignKey(Room, on_delete=models.CASCADE, db_index=True) occupier = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name="+", db_index=True) unread_count = models.PositiveSmallIntegerField(default=0, blank=False) def __int__(self): # __unicode__ for Python 2 return self @database_sync_to_async def increment_unread(room_id): roomOccupiers = RoomOccupier.objects.filter(room_id=room_id) print(roomOccupiers) for roomOccupier in roomOccupiers: print(roomOccupier) roomOccupier.unread_count += 1 roomOccupier.save() return true <QuerySet [<RoomOccupier: RoomOccupier object (1)>, <RoomOccupier: RoomOccupier object (2)>]> RoomOccupier object (1) Exception inside application: NOT NULL constraint failed: chat_roomoccupier.created Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: chat_roomoccupier.created The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application...etc... -
Problem in comparing Arabic and persian texts in django Filter
The below model has a field that takes a name and searches it in an API. class Symbol(models.Model): name = models.CharField(max_length=20, unique=True, blank=False) sigma = models.FloatField(null=True) s = models.IntegerField(null=True) The problem is that the model name property is Persian and the API content is Arabic so Django filter can't find the model object. e.g: >> 'ي'=='ی' >> False # while it should be true >> Symbol.objects.get(name="آریا") #returns nothing while it exists I need something like localecompare() in javascript. p.s: model data is taken from other API so I can't enter the data manually in Arabic. -
How to create a list with checkbox values and return to request.POST
I want to get the values of checkbox and return it to request.POST {% for flow in data.flows %} <div style="margin-bottom:-27px"> <div class="w3-bar"> {% csrf_token %} <input type="checkbox" id="{{flow.0}}" name="precedent" value="{{flow.0}}"><label for="scales" > {{flow.0}} - {{flow.1}}</label> <br> <br> </div> </div> % endfor %} So I want to return all the values in a list to def create_flow_and_phases(request): ... Any suggestions? -
How to use a prop from an auth route to gain props from a different route? (Django/React)
I'm creating a profile page with Django and react. The idea is that once a user is signed in, they go to a profile page and it sends a get request to http://localhost:8000/users/auth/user and then uses the props to populate the page. However, since this is a Django-created route, I need to use maybe data.username to link a different route that displays all the other props i need (such as bio, location) and then populate the rest of the profile with this. Here is an example of the code: fetch('http://localhost:8000/users/auth/users', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Token ${localStorage.getItem('token')}` } }) .then(data => { console.log(data) setUserName(data.username); And somehow use data.username to fetch another route that displays my other props not located in auth. How can I do this within the fetch/then format? Please let me know if further clarification is needed. Thank you! -
Django error 'ModuleNotFoundError: No module named 'ocore'
New to Django and have just started building out a new project following a tutorial. I have created a virtual environment as follows: pip install virtualenv virtualenv myproject_3_7_3 I then activate the virtual env and install Django as follows: cd myproject_3_7_3 source bin/activate pip install django This installs Django version 3.2.10 successfully, so then I activate the project, add some folder structure and create an app using the following commands: django-admin startproject myproject cd myproject mkdir apps mkdir apps/core python manage.py startapp core apps/core I then open VSCode and I can see the project and all of the default folders/files there. To start the app I run: python manage.py startapp core apps/core But I immediately get the following error in the terminal. Traceback (most recent call last): File "/Users/myuser/myproject_3_7_3/lib/python3.7/site-packages/django/apps/config.py", line 244, in create app_module = import_module(app_name) File "//anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ocore' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) … -
ValueError: Field 'id' expected a number but got string in Django Rest Framework
In DRF I am facing an issue, whenever I do a POST request on the endpoint, on the field "name" which is a text field I get an exception "Field 'id' expected a number but got 'TITLE'", but when I change the value of "name" to an integer the request is successful I don't understand it becauses name is TextField in model and why its mixing Id and Name field with each other. I have deleted the migration files from the Project and DB and re-run the Migrations, but still facing this issue. Following is my code: models.py class Project(models.Model): admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='project_crated_by') name = models.TextField(max_length=225, blank=False, null=False) project_members = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='members', null=True, blank=True) created_on = models.DateField(default=timezone.now) tags = ArrayField(models.CharField(max_length=225, default=''), blank=True) def __str__(self): return self.name objects = models.Manager() views.py class ProjectView(viewsets.ViewSet): def create(self, request): project_name_exist = Project.verify_project_name(request.data['admin'], request.data['name']) if project_name_exist: return Response({'message': 'You already have a project with this name', 'status': status.HTTP_200_OK}) serialized_project = ProjectSerializer(data=request.data) if serialized_project.is_valid(): serialized_project.save() return Response({'message': 'Project Created Successfully', 'status': status.HTTP_201_CREATED}) else: return Response({'error': serialized_project.errors, 'status': status.HTTP_400_BAD_REQUEST}) serializer.py class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' -
django redirect update to detail view after ajax update
I want to redirect to detail view after an update that uses ajax form submission. Urls path('<uuid:pk>', concept_detail, name='concept_detail'), path('<uuid:pk>/update/', update_concept, name='update-concept'), Detail View def concept_detail(request, pk): context = {} context['concept'] = Concept.objects.get(id=pk) return render(request, 'concepts/concept_detail.html', context) Update View @login_required def update_concept(request, pk): if request.method == 'POST': try: ## I GET THE FORM DATA - I haven't included the querysets because I haven't figured it out yet, just want to get the redirect to work print(request.POST) ## THIS DOESN'T WORK, BUT IT WORKS BELOW concept = Concept.objects.filter(id=pk).first() return redirect(concept) except Exception as e: print(e) else: ## this populates the update form context = {} obj = get_object_or_404(Concept, pk=pk) context['concept'] = obj if (request.user == obj.user): return render(request, 'concepts/concept_update.html', context) else: ## If user didn't create the post but tried to go to update url, redirect to detail page - WORKS concept = Concept.objects.filter(id=pk).first() return redirect(concept) Response Codes Don't know why I'm getting 302 for update view -- don't get that for my create view, and the forms and ajax are basically the same. "POST /concepts/1241955d-1392-4f85-b8ed-e3e0b89b4e50/update/ HTTP/1.1" 302 0 "GET /concepts/1241955d-1392-4f85-b8ed-e3e0b89b4e50 HTTP/1.1" 200 7577 AJAX FORM SUBMIT The form is a lot more dynamic than this which is why I'm using … -
create() in Django gives me ValueError "Field 'width' expected a number but got 'NA'
I am trying to insert several rows from .csv file into SQLite in Django. I don't want to be using import_data(), because I wanted to have a more granular control for each insertion. My model is something like this: class Box(models.Model): name = models.CharField(max_length=30) color = models.CharField(max_length=30) size = LengthField(blank=True, null=True, default=None, decimal_places=2,validators=(MinValueValidator(0, field_type='Length'),MaxValueValidator(100, field_type='Length')))) Only name has a constraint to be unique. Now, when i am running get_or_create, and have a csv row that has a blank for size, i am getting an error "ValueError - Field 'size' expected a number but got 'NA'". (For the csv rows before that, everything is inserted correctly.) I find it strange because in the model i have blank=True and null=True for size. What could i be doing wrong and how i could fix that? Thank you in advance!