Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change Status when update form in Django?
I am working with Django form Updation, but I am facing a small issue, I have 3 fields in form updating, name, image, status, Now if a user upload a image in form then status should be change automaticly in my database. here is my forms.py file... class UpdateForm(forms.ModelForm): model = Product fields = ['name', 'image', 'status'] here is my views.py file... def myview(request, id): datas=Product.objects..get(pk=id) form = UpdateForm(instance=datas) if request.method === 'POST' form = UpdateForm(request.POST or None, request.FILES or None, instance=datas) if form.is_valid(): edit = form.save(commit=False) edit.save() return HttpResponse('Success') else: return HttpResponse('Fail') template_name='test.html' context={'datas':datas} return render(request, template_name, context) Default status is 0 in my database, If a user upload image then status should be 1 in my database, please let me guide how i can do it. -
Django group permissions not working correctly
I'm working on a project using Python(3.7) and Django(3) in which I have created a custom user model using AbstractBaseUser and also utilized PermissionsMixin. In my user model, I have created a field named is_instructor on signup if this is checked user will have the permission of the instructor group. Now if I try to use these permissions with a user which has is_active, is_instructor & is_staff it doesn't work but if I try with is_admin it works. Here are my Implementations: User model: class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=60, unique=True) fullname = models.CharField(max_length=30, unique=True) is_instructor = models.BooleanField(default=False) date_join = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Signup view def registration_view(request): form = RegistrationForm(request.POST or None, request.FILES or None) if request.method == 'POST': print('get post req') if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() if form.cleaned_data['is_instructor'] is True: instructor_group = Group.objects.get(name='Instructors') instructor_group.user_set.add(user) return HttpResponseRedirect(reverse_lazy('users:login')) return render(request, 'users/register.html', {'form': form}) Login view: def login_user(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) … -
Why i am getting this error "Server Error(500)" in django heroku?
Everything is working fine in the application. But in predicting the model. It shows the response like Server Error(500) And the log look like this 10.171.230.57 - - [18/Sep/2020:08:42:24 +0000] "POST /"appname" HTTP/1.1" 500 145 "...." "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36" -
Django URL passing parameter
Would anyone please explain to me how to passing parameter in Django URL I created view in view.py "def hours_ahead(request, offset)" to calculate the time ahead. Then on URL.py I call it with re_path(r'^time/plus/\d{1,2}/$', hours_ahead). But I get the error message when I put the url http://127.0.0.1:8000/time/plus/2/ TypeError at /time/plus/2/ hours_ahead() missing 1 required positional argument: 'offset' -
Add context get method multiple values
I have this method in a Django view in order to receive value from the src http://url/my-view?get1=some1 def my_view(request): get1= request.GET['get1'] context = {'data':{"get1":{"value":get1}}} template_name="get.html" return render(request, template_name, context) And now I want to send multiple values to the get context http://url/my-view?get1=some1&get2=some2. I tried to reconstruct the method to receive both values like this but it doesn't accept them. def my_view(request): get1= request.GET['get1'] get2= request.GET['get2'] context = {'data':[{"get1":{"value":get1}, "get2":{"value":get2}}]} template_name="get.html" return render(request, template_name, context) Do you have any idea what structure should I use for it?? -
Django management command save output to file gives AttributeError
I'm using Django 2.2 I have written a management command to migrate user data from the previous server to the new server. The command is python manage.py migrate_all --email user@example.com Where email is passes as **options and is used to filter the queryset for the specified email of the user. Now I want to save the stdout and stderr to a file because terminal does not shows full output when the command runs for a long time. For that I'm using python manage.py migrate_all --email user@example.com |& tee -a output.txt But this is giving error as AttributeError: 'dict' object has no attribute 'endswith' -
Problem With JQuary Ajax In A Django Project
Hello. I'm working on a small project with Django, and there is a section that needs to do with Ajax JQuery. Unfortunately, I don't know about JavaScript, and it's libraries yet. I will appreciate it if you help me. I want to make Follow and Unfollow button. But there is a problem. I did it with VAR to make a variable, but it didn't recognize and told me I need to use LET. Also, I have defined URL and some, etc., which it doesn't recognize too. Add to that; I have two variable, which has two different names but one path, but It seems it's wrong too. The JavaScript Code: $('#following-btn').click(function(){ let user_id = $('#following-btn').attr('data-id') let follow = $('#following-btn').text(); if (follow === 'follow'){ let url = '/account/follow/' let btn_text = 'unfollow' let btn_class = 'btn btn-warning text-center mx-auto' }else { let url = '/account/unfollow/' let btn_text = 'follow' let btn_class = 'btn btn-primary text-center mx-auto' } $.ajax({ url: url, method:'POST', data:{'user.id':user_id,}, success:function (data) { if (data['status'] === 'ok'){ $('#following-btn').text(btn_text) $('#following-btn').attr({class: btn_class}) } } } ) }) The View File And Path: {% if request.user.id != user.id and not is_following %} <button id="following-btn" data-id="{{ user.id }}" style="display: block" class="btn btn-primary text-center … -
Python Conditional Key/Value in Dict
I have the following piece of code: payload = [ { 'car': { 'vin': message.car_reference.vin, 'brand': message.car_reference.model_manufacturer, 'model': message.car_reference.model_description, 'color': message.car_reference.color, }, } ] The only field on message.car_reference that is guaranteed to not be None is vin. I still want the other keys (brand, model, color) to be in the dict only if they have a value. The payload gets send to an external API that gives me an error if e.g. color = None. How do I make it so that keys and values are only added, if their value is not None? What came to my mind until now was mutlitple if-statements, but that looks awful and I don't think it's the right way. -
ASGI vs WSGI, WSGI compatibility issues
When reading about ASGI specification, I noticed this sentence in WSGI compatibility paragraph: WSGI applications, being synchronous, must be run in a threadpool in order to be served, but otherwise their runtime maps onto the HTTP connection scope’s lifetime. I don't understand why it must be run in threadpool? -
celery multi celery.exceptions.TimeoutError: The operation timed out
I followed the official Celery guide to learn, everything works well when using celery -A proj worker -l info to start the worker, however , if I run the worker in the background using celery multi restart w1 -A proj -l info --logfile=./celery.log, then I got >>> from proj.tasks import add >>> add.delay().get(timeout=19) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.8/dist-packages/celery/result.py", line 230, in get return self.backend.wait_for_pending( File "/usr/local/lib/python3.8/dist-packages/celery/backends/base.py", line 660, in wait_for_pending meta = self.wait_for( File "/usr/local/lib/python3.8/dist-packages/celery/backends/base.py", line 696, in wait_for raise TimeoutError('The operation timed out.') celery.exceptions.TimeoutError: The operation timed out. >>> So what's wrong ? Test environment : Python 3.8.2 celery multi v4.4.7 rabbitmqctl version ---> 3.8.2 and Project layout (code files): proj/init.py /celery.py /tasks.py celery.py from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('proj', broker='amqp://localhost', # backend='db+sqlite:///results.sqlite', # The backend argument, If you don’t need results, it’s better to disable them. Results can also be disabled for individual tasks by setting the @task(ignore_result=True) option. include=['proj.tasks']) # The include argument is a list of modules to import when the worker starts. You need to add our tasks module here so that the worker is able to find our tasks. app.conf.CELERY_RESULT_BACKEND … -
How i can use cleaned_data without forms?
I have custom form on my page (more precisely many inputs, not form). When I want to send it to server I just get values from all inputs, perform JSON.stringify() and send it with $.post or $.ajax. On Django-side I get data with this: data = json.loads(request.body) # now I can use my data and save it in the Database record = get_object_or_404(id=999) record.name = data['name'] ... record.save() I knew that using data without checking is very dangerous for my application. How I can check my data and use it like a "cleaned_data['field_name']"? -
Serve homepage as root in Wagtail using Wagtailtrans
I've setup environment with Wagtail and everything worked as a charm. I need internationalisation, so according to documentation, I've installed wagtailtrans. And still, everything is working, but with one thing that is weird, and have no clue how to change it. It is about slug, I followed this steps, and my homepage is served under localhost/en/home or localhost/fr/home and so on.. My goal is to have the homepage under localhost/fr without /home. Any idea how to accomplish would be very helpfull. My urls.py looks like this: urlpatterns += i18n_patterns( path('', include(wagtail_urls)), ) urlpatterns += [ path('admin/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), ] -
Indexing a heroku site on google
I am a beginner and just made a website using django and python and host this https://randoms77.herokuapp.com/ website to the heroku but whenever I search it on google it's shows no results.Please tell me how can we index a heroku site on google -
Django db - lastrowid
I am new to Django and I cannot get the lastrowid after insert def db_insert_lastrowid(sql, params=None): """Insert and return last row id""" with connections['default'].cursor() as c: with transaction.atomic(using='default'): sql = 'insert into test VALUES (%s, %s)' c.execute(sql, [11, '1']) re = c.fetchone() print(re) return True With this error: django.db.utils.ProgrammingError: no results to fetch I am using postgreSQL here and the the table is like: ### test table id int4 nextval('auto_test'::regclass) name varchar How can I get the last insert row id? Another issue is that even I got this error, it still insert into the table without rollback. Does it mean that I need to manually rollback when encounter an error? -
Django and Stripe, Module 'stripe' has no 'Customer' member
so I'm trying to create a customer in stripe using django, according to the documentation in stripe, the code stripe.Customer.create should work, but it just appears this error, can someone tell me why is this happening? views.py from django.shortcuts import render, redirect from django.urls import reverse from django.http import JsonResponse import stripe # Create your views here. stripe.api_key = "sk_test_51HS9WtLO6GuZLQTlNm3i9sttPGm592XEA0RfsyvalvZ3xbtCWdBFO7MhRBWSpNgIl6LC82hPr19Sgw5CZdymV8gE00kZbLjeqn" def index(request): return render(request, 'sales/index.html') def charge(request): amount = 5 if request.method == 'POST': print('Data', request.POST) stripe.Customer.Create( email=request.POST['email'] ) return redirect(reverse('success', args=[amount])) def successMsg(request, args): amount = args return render(request, 'sales/success.html', {'amount':amount}) -
Calling a .php document in JavaScript using Django Framework
I'm wondering if this is Django URLs issue. I am following [a Google Tutorial][1] to pop down markers showing addresses on a Google Map pulled from a database using php and xml. I have wired up a .php to my PostgreSQL db okay and seem to be able to run the script and show all the addresses and details in the console (I believe this means the XML file is working too). The Problem The trouble I am having is on the JavaScript side: I am using downloadURL() function in my .js static file. And pointing the URL parameter to my .php file which is stored in my local directory: var markerurl = 'testingland/www/xmlpgd.php' downloadUrl(markerurl, function(data) However when I test the script on my local development server (http://127.0.0.1:8000/cafe_list) it returns the following error: http://127.0.0.1:8000/cafe_list/testingland/www/xmlpgd.php 404 (Not Found) What I have tried I have tried moving the xmlpgd.php file to different locations including templates, static and elsewhere. I have tried hosting it on Google Cloud (which returns a CORS error). I am at a loss and thinking maybe I need to wire it up to my urls.py file? I am just not sure whether this is the case or how to … -
JQuery hide field in row by choice value
I have some form in my Django app, and i need to show fields with names From and To if value in Type field is equal Integer, else hide this to field in this row. How can i do this ? https://i.stack.imgur.com/3IcXM.png -
Check if not exists in django model queryset
Lets say I have table that looks like this col1 col2 1 completed 2 error 3 inititated 4 error 5 completed 6 error 7 completed Now I have query in django that do like this: Model.objects.filter(col1__in=[1,2,8]).values('col2') This query is running fine but what i want is to do something like this: Return "pending" for col2 where col1 is not in above list i.e return "pending" for 8 as it is not in table and "completed" and "error" for 1 and 2 -
my current page is /items but after clicking the link it moves to items/checkout/1 instead of checkout/1 [duplicate]
I'm using this link in my current page but whenever I click the link it moves to a different path. It appends the below url to my current url Buy Now For ex above link when clicked should go to /checkout/1 and my current page is /items but after clicking the link it moves to items/checkout/1 instead of checkout/1 How can I solve this problem? -
How to create logic template and model in Class-Base-View base on the path pass by in Django
I'm almost a month working and practicing my self in Django and I do really like it. But right now I have Three Class-Base View which have the same function displaying the list of different data base on the model I provide for them, Now what I want is that to create only one Class-Base View and render the template_name and model base on the url path passes? Is that possible to create? -
Django model default value has a function after model creation and records insertion
Let's say I have a model called Marks, with the below fields class Marks(models.Model): subject1 = models.DecimalField() subject2 = models.DecimalField() subject3 = models.DecimalField() And I have added some records in this models, Now I would like to add one more field which I missed, total so I have added it has total = models.DecimalField() And to apply migrations, I need to provide some default value for the existing rows for this total field, but I don't want it to be static like default=100 or something, I want it to be the addition of all three fields subject1, subject2, subject3 and provide values in for the existing rows, How can I do that, whether in migrations or using some functions. -
Problem in searching in Django. When searched for a exact word in small alphabet it throws error
Type error at /search Traceback When I search for ✅ "g" it shows Git ✅ "gi" it shoes Git ✅ "Git" it shows Git ❎ "git" it throws an error -
WARNING: Could not generate requirement for distribution -jango 3.0.3
WARNING: Could not generate requirement for distribution -jango 3.0.3 (c:\users\sayeef\anaconda3\lib\site-packages): Parse error at "'-jango=='": Expected W:(abcd...) This is the error snippet. -
Running tensorflow models on theano backend
my models are trained using tensorflow in google colab. I want to load them in a django server with keras using theano as backend.Here is my error when i triy to load that model. 2020-09-18 05:00:57,559: File "/home/anush123/sample/transfer/views.py", line 27, in <module> 2020-09-18 05:00:57,559: models['1'] = load_model("/home/anush123/sample/static/car_model.h5",compile=False) 2020-09-18 05:00:57,559: 2020-09-18 05:00:57,559: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/engine/saving.py", line 419, in load_model 2020-09-18 05:00:57,559: model = _deserialize_model(f, custom_objects, compile) 2020-09-18 05:00:57,559: 2020-09-18 05:00:57,559: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/engine/saving.py", line 225, in _deserialize_model 2020-09-18 05:00:57,559: model = model_from_config(model_config, custom_objects=custom_objects) 2020-09-18 05:00:57,559: 2020-09-18 05:00:57,559: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/engine/saving.py", line 458, in model_from_config 2020-09-18 05:00:57,559: return deserialize(config, custom_objects=custom_objects) 2020-09-18 05:00:57,560: 2020-09-18 05:00:57,560: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/layers/__init__.py", line 55, in deserialize 2020-09-18 05:00:57,560: printable_module_name='layer') 2020-09-18 05:00:57,560: 2020-09-18 05:00:57,560: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/utils/generic_utils.py", line 145, in deserialize_keras_object 2020-09-18 05:00:57,560: list(custom_objects.items()))) 2020-09-18 05:00:57,560: 2020-09-18 05:00:57,560: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/engine/sequential.py", line 300, in from_config 2020-09-18 05:00:57,560: custom_objects=custom_objects) 2020-09-18 05:00:57,560: 2020-09-18 05:00:57,560: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/layers/__init__.py", line 55, in deserialize 2020-09-18 05:00:57,560: printable_module_name='layer') 2020-09-18 05:00:57,560: 2020-09-18 05:00:57,561: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/utils/generic_utils.py", line 147, in deserialize_keras_object 2020-09-18 05:00:57,561: return cls.from_config(config['config']) 2020-09-18 05:00:57,561: 2020-09-18 05:00:57,561: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/engine/base_layer.py", line 1109, in from_config 2020-09-18 05:00:57,561: return cls(**config) 2020-09-18 05:00:57,561: 2020-09-18 05:00:57,561: File "/home/anush123/.virtualenvs/myenv/lib/python3.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper 2020-09-18 05:00:57,561: return func(*args, **kwargs) please let me know the changes i should make.thanks. -
Android Volley onResponse function not running
Here is my function which I filled in from https://developer.android.com/training/volley/request#java String url = "http://192.168.1.31:8000/api/social/convert-token"; JSONObject jsonBody = new JSONObject(); try{ jsonBody.put("grant_type", "convert_token"); jsonBody.put("client_id", clientID); jsonBody.put("client_secret",clientSecret); jsonBody.put("backend", "facebook"); jsonBody.put("token", facebookAccessToken); jsonBody.put("user_type", userType); }catch (JSONException e){ e.printStackTrace();; } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //Execute Code Log.d("LOGIN TO SERVER", response.toString()); // Save server token to local DB SharedPreferences.Editor editor = sharedPreferences.edit(); try { editor.putString("token", response.getString("access_token")); }catch (JSONException e){ e.printStackTrace(); } editor.commit(); //Start home activity startActivity(new Intent(Login.this,Home.class)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO: Handle error } }); The string URL is my Django server, this works properly, I can access it from the web browser on the android phone. The next block of just converts data I previously got into JSON format. I tested this by copying and pasting the URL, and each parameter in Postman, and it works and returns JSON back. jsonBody is then passed into the Json Request, along with the URL. The Log.d "LOGIN TO SERVER", is not visible in my log. So I know that the onResponse does not run. Further I put a Log line in the onErrorResponse, and …