Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve sql query that is not working in djongo set up
I am using djongo as Sql to Mongodb query convertor in my Django project. However i am facing issues in Server because of Sql queries. Below is the Sql error i am facing while trying to retrieve data in front end UI. raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "engine_task"."id" AS Col1, "engine_task"."project_id" AS Col2, "engine_task"."name" AS Col3, "engine_task"."mode" AS Col4, "engine_task"."owner_id" AS Col5, "engine_task"."assignee_id" AS Col6, "engine_task"."bug_tracker" AS Col7, "engine_task"."created_date" AS Col8, "engine_task"."updated_date" AS Col9, "engine_task"."overlap" AS Col10, "engine_task"."segment_size" AS Col11, "engine_task"."status" AS Col12, "engine_task"."data_id" AS Col13, "engine_task"."dimension" AS Col14, "engine_task"."subset" AS Col15 FROM "engine_task" LEFT OUTER JOIN "engine_segment" ON ("engine_task"."id" = "engine_segment"."task_id") LEFT OUTER JOIN "engine_job" ON ("engine_segment"."id" = "engine_job"."segment_id") WHERE ("engine_task"."owner_id" = %(0)s OR "engine_task"."assignee_id" = %(1)s OR "engine_job"."assignee_id" = %(2)s OR "engine_job"."reviewer_id" = %(3)s OR "engine_task"."assignee_id" IS NULL)) subquery Params: (6, 6, 6, 6) Version: 1.3.4 Below are the versions i am using Django = 3.0.5 mongodb Server = 4.4.6 djongo = 1.3.4 sql parse = 0.2.4 Please help me resolve this issue. -
Django When(...) object SQL missing when used with __in lookup with empty list as value, leading to ProgrammingError
using Django 3.0 (will be upgraded) I get some invalid SQL that leads to a django.db.utils.ProgrammingError, and I wonder if anyone can help me see why. I wonder if this problem also occurs in newer versions of Django. But I hope to get it working without having to upgrade Django right away. Querying a Model I am annotating a field to each instance, and using Case and When with that, and it seems that the error happens when using a negated Q object with a __in lookup that gets an empty list as value. I will show three examples that are very similar, but lead to different SQL. Only the first example leads to erroneous SQL. Example query that leads to invalid SQL: Activity.objects.all() .annotate( employee_authorized=Case( When(~Q(case__assigned_unit__in=[]), then=Value(False)), default=Value(True), output_field=BooleanField(), ) ) This leads to the following SQL, where there's nothing in between WHEN and THEN. This results in a django.db.utils.ProgrammingError. SELECT "activity_activity"."id", ... CASE WHEN THEN False ELSE True END AS "employee_authorized" FROM "activity_activity" LEFT OUTER JOIN "case_case" ON ("activity_activity"."case_id" = "case_case"."id") The below example seems to lead to logical SQL. The only difference being that the Q object is not negated. Activity.objects.all() .annotate( employee_authorized=Case( When(Q(case__assigned_unit__in=[]), then=Value(False)), default=Value(True), output_field=BooleanField(), … -
How to access a table which is present in mysql database in django?
I'm a django beginner and now I got stuck with one issue which is - I'm trying to access a table which is already present in mysql database now I want to render that table on a html page, How can I access that table and render it on html page -
Creating a staff user and giving permissions in Django
I have created a staff user from admin panel for a Django application, but haven't assigned any permissions manually to that user, when I logged in with this staff user credentials I am getting all the permissions by default. I am using custom user but not customised any permissions. please help me with where I am going wrong and how to create a staff user without any permissions by default. -
Django / Blender / Celery / Channels
I found this repository / youtube video https://www.youtube.com/watch?v=42nvLjOv8Ng https://github.com/hophead-ninja/django_blender But Channels has changed quite a bit and I admit I have never tried anything like this with Django before. I have tried to recreate it up using Channels 3.0 - I can get the Webpage up and the Render button "click" does return a 200 from the server - nothing is failing - but the monkey.blend does not render. I do not see my Worker pick up the click I simply get a 200 back from the server Here is my code - maybe together we can make this work. My code is also open source and will be available if we do get it working Here is all of the files and code - if you need anything else please let me know. I do appreciate your help and would love to get the monkey.blend open in a web browser! Thanks for your time. Screenshot of the rendered HTML page /viewer/ html page Which I get a 200 status back and the REDIS IP HTTP GET /viewer/? 200 [0.00, 172.18.0.1:39096] merlin/settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://redis:6379')] }, }, } BLENDER_FILE = ("monkey.blend") … -
Directly send money from my Stripe account to my customers bank accounts
I'm looking for functionality to make direct payments to my Stripe Customers bank accounts without Stripe Connect. Is it actually possible to do? Do I have to use any other payment providers for that? I spent a lot of hours to find correct way of doing such kind of payment flow, but all of them requires Stripe Connect for customer which is unacceptable in my situation. -
ValueError at / time data '' does not match format '%Y-%m-%d'
I'm working on a project in which when users mention a specific date range from and to, the corresponding data gets printed. The page takes input from users through input type date when the specific date is mentioned the value of date passes to user_input_date_to and user_input_date_to. But when I'm executing I'm getting the error ValueError at / time data '' does not match format '%Y-%m-%d' My views file def indexview(request): url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json') json_data=url.json() user_input_state='' user_input_date_from='' user_input_date_to='' user_data_type='' user_required_type='' if request.method == 'POST': user_input_state=request.POST.get('state') x=request.POST['date_from'] user_input_date_to=request.POST['date_to'] user_data_type=request.POST.get('data_period') user_required_type=request.POST.get('required_type') #To store dates list start_date =user_input_date_from end_date = user_input_date_to start_date_object = dt.datetime.strptime(start_date,"%Y-%m-%d").date() end_date_object = dt.datetime.strptime(end_date,"%Y-%m-%d").date() days = end_date_object - start_date_object dates=[] otp=[] for i in range(days.days+1): dates.append(str(start_date_object+dt.timedelta(days=i))) for i in dates: try: otp.append(json_data[user_input_state]['dates'][i][user_data_type][user_required_type]) except KeyError: otp.append(0) dict_pass={ 'dates':dates, 'otp':otp } return render(request,'index.html',dict_pass) HTML date form <input type="date" name="date_from"><br> <input type="date" name="date_to"> -
Manually attach Django UUIDField
So, maybe dumb question but still I'm running into problems. I am using Python + Django (3.1.1) and DRF I have an id field defined as: id = UUIDField(default=uuid.uuid4, unique=True) But I have a use case where someone wants to generate uuid4 on their side and use it in stead of "default" auto-generated one. I am not sure why the UUIDField does not allow manually adding it, and if I can bypass that Thanks! -
How to connect react frontend served on S3 with Django backend hosted on EC2?
I have developed a web application. I am using React.js for the frontend and have used S3 with CloudFront to deploy it on the cloud. For the backend, I have deployed Django REST API on the EC2 container. Everything works fine until I make API call from local server to my API served on EC2. But whenever I change the proxy in the package.json file to my REST API's IP and deploy it on the S3 by invalidating old files. It still doesn't work. How can I resolve this? Any help would be appreciated. -
Large file upload(like 2gb) in chunk by chunk using javascript ajax and django without any api call
My views.py file like this Now I have some problem to stich all the chunks into the file in views.py and also take so much time to upload this video file.Please help. -
Get n items in django model using releverse relationship
Is possible to get the last n items in the Django model, using the reverse relationship. {% for brand in brands %} {% for product in brand.product_set.all %} {% endfor %} {% endfor %} I am tried in this way, But it prints all things. But want only last 3 items -
How to render clear checkbox manually in Django Forms?
In Django when dealing with an image in a form, there is always this clear checkbox (if the image is nullable), e.g.: <input type="checkbox" name="image_var-clear" id="image_var-clear_id"> <label for="image_var-clear_id">Clear</label> Now, I wish to render it manually. If I place "{{ form.image_var }}" in my HTML, the checkbox appears and the above html code is generated, but I cannot figure out how to render it completely manually. So far I managed to get these values: if required: {{ form.image_var.field.required }} checkbox label: {{ form.image_var.field.widget.clear_checkbox_label }} input text: {{ form.image_var.field.widget.input_text }} checkbox name: {{ form.image_var.field.widget.name }} text: {{ form.image_var.field.widget.initial_text }} This all works fine, until I want to render the checkbox_id with: {{ form.image_var.field.widget.checkbox_id }} What am I missing? -
Change CSS stles from view in Django
Sorry if this is an obvious question, I am new to django and still learning. I am creating a website that contains 6 images in total. The images in the website should remain invisible until its image id is passed from views.py. I have a template index.html page and view that loads when this url is accessed localhost/imageid What I need now is to make the image visible whenever its url is access. So for instance if a user goes to localhost/1. QR code 1 should be made visible. I am also storing the state of all access images. So if the user accesses the website again and goes to localhost/2 it should make image 1 and 2 visible. I am using sessions to store the state. I just need a way of making the images visible. Thankyouuuu -
Where should I initialize my MQTT Loop in Django
Currently my init.py looks like this: from . import mqtt mqtt.client.loop_start() But when I run it some actions in the loop are done more than once. When I place a time.sleep(30) in front everything works as intended. But I think this is not the best thing to do. How do I run my loop only when everything else has loaded. I tried putting it in an AppConfig ready like so: from django.apps import AppConfig from . import mqtt class PrintConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'print' def ready(self): mqtt.client.loop_start() but I get the following error: RuntimeError("populate() isn't reentrant") Is there something I need to add to my INSTALLED APPS when I use the def ready(self): function ? -
super(type, obj): obj must be an instance or subtype of type this the problem and i am pretty sude that this is because of the code in my form [closed]
i am tryna create custom user creator in admin panel class AdminUserCreation(forms.ModelForm): password1 = forms.CharField(label="password", widget=forms.PasswordInput) password2 = forms.CharField(label="password confirmation", widget=forms.PasswordInput) class Meta: model = CUser fields = ["email"] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("passcodes do not match!") return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user every time i try to create it gives me that error! -
Celery Async Issue in Django's Docker Container
I have deployed micro services on docker containers using celery for queue management. Problem is that when I call sync operation it can access database container but async operation gives us this error HTTPConnectionPool(host='database', port=83): Max retries exceeded with url: Can anybody tell me the root cause of this behavior? why the same API is executing in sync and not in async? -
Unnecessary auto migrations on Django?
running python 3.6 and Django 3.1.7! So I have a Django project with an app with models as the following: class Department(models.Model_: name = models.CharField(max_length=255) class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) department = models.ForeignKey( Department, related_name="department_members", on_delete=models.CASCADE ) When I run makemigrations I get this on 0001_initial.py: class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=255)), ('last_name', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Department', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], ), migrations.AddField( model_name='person', name='department', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='department_members', to='my_app.department'), ), ] That is all fine and good but now I've been getting this red text: Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. When I run makemigrations again i get this as 0002_auto_20211111_1116.py: class Migration(migrations.Migration): dependencies = [ ('my_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='Department', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), migrations.AlterField( model_name='Person', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), ] I haven't made changes to models.py and also I can't see a difference on the 'id' field that is being altered on the auto migration. … -
How to convert Optional<Dictionary<String, Any>> to Dictionary<String, Any> to send Alamofire post request with json paramters?
class func postLoginRequest(url: String, parameters: Parameters?, success: @escaping (Any) -> Void, failure: @escaping (NetworkError) -> Void) { if Network.isAvailable { let param : [String : Any] = [ "username" : "cuyar", "password" : "cuyar" ] print (type(of: param)) print(param) print(type(of: parameters)) print(parameters) let manager = Alamofire.Session.default manager.session.configuration.timeoutIntervalForRequest = Constants.NetworkError.timeOutInterval manager.request(url, method: .post, parameters: param, encoding: JSONEncoding.default ).validate(statusCode: 200..<600).responseJSON { (response) -> Void in ... My data output like given in bellow; Dictionary<String, Any> ["username": "x", "password": "x"] Optional<Dictionary<String, Any>> Optional(["username": Optional(<TextFieldEffects.HoshiTextField: 0x11c054600; baseClass = UITextField; frame = (41 10; 286 40); text = 'x'; opaque = NO; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x2821b45d0>; layer = <CALayer: 0x282f855c0>>), "password": Optional(<TextFieldEffects.HoshiTextField: 0x11c043600; baseClass = UITextField; frame = (41 10; 286 40); text = 'x'; opaque = NO; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x2821afe40>; layer = <CALayer: 0x282f849c0>>)]) When ı use param as a parameters no problem. I can get username and password in backend (DJango) for jwt auth. But ı cant when ı use parameters as parameters value. How can do this convertion to send json body data. -
Django - Chaining annotated querysets
I am trying to chain two querysets that have different annotated values based on some filters (which are simplified in the following snippet) queryset = Location.objects.all() queryset_1 = queryset.filter(dummy=True).annotate(weight=Value(1, IntegerField())) queryset_2 = queryset.filter(dummy=False).annotate(weight=Value(0, IntegerField())) queryset = queryset_1 | queryset_2 However, if I iterate the queryset and try to print the weight, if will be 1 for the whole queryset for p in queryset: print(p, p.weight) 5587798: <True> 1 5587810: <True> 1 5587811: <True> 1 5587819: <False> 1 5587823: <False> 1 5587824: <True> 1 Is it possible to keep the annotated value, so the objects that are dummy=False have an annotated value of 0, and the ones that have it set to true have an annotated value of 1? -
Get specific field of model in select_related
I have a query in my project: qs = self.model.objects \ .filter(user=self.request.user, pk__iexact=pk) \ .select_related('shipping_addr', 'billing_addr', 'cart') \ .first() I want to optimize this query more than it is. I want to get only the 'id' and 'name' fields of shipping_addr. But this is not working: qs = self.model.objects \ .filter(user=self.request.user, pk__iexact=pk) \ .select_related('shipping_addr', 'billing_addr', 'cart') \ .only('shipping_addr__name','shipping_addr__id') \ .first() I know the reason that why this code is not running, I don't know what I have to do😕. -
associate the user with the post Django and MySQL
I am trying to associate the user with the post. I have two models students is for user and sublists is for user posts with a foreign key(author). I am using MySQL database and using forms to store data into them. when my form.author execute in my HTML file it gives me a list of ids for all users in the databse but I am already logged in and i want to post as the logged in user without choosing. If remove it says my form is not valid which make sense since im not inputing for form.author.Since I'm using MySQL, I'm not using the built-in User authentication method, but instead comparing both email and password with the login form input. Spend too much time on this but hard to get around with this one. Any help would be appreciated my views.py look like this def addnew(request): if request.method == 'POST': form = Sublist(request.POST) if form.is_valid(): try: form.save() messages.success(request, ' Subscirption Saved') name = sublist.objects.get(name=name) return render (request, 'subscrap/main.html', {'sublist': name}) except: pass else: messages.success(request, 'Error') pass else: form = Sublist() return render(request, 'subscrap/addnew.html', {'form': form}) @login_required(login_url='login') @cache_control(no_cache=True, must_revalidate=True, no_store=True) def main(request): return render(request, 'subscrap/main.html') def mod(request): student = students.objects.all() … -
Adding IdentityServer4 to a Django API as an OAuth2 Server
I have a Python API written using Django. I am going to use IdentityServer4 as my OAuth2 server to generate JWT for the Django application so I can add other frameworks like .NET Core to my solution later without any issues. Is that possible to use IdentityServer4 as an OAuth2 server for Django? Thanks -
Multiple django session tables
An application requires two user models for authentication. First is the AUTH USER model which has name, email and password and another is Account model which has foreign key relationship with AUTH USER MODEL. PermissionsMixin is inherited by the account model, so all the groups and permissions are related to it, rather to the AUTH USER model. User registration is done once using AUTH USER model. But login should happen in following stages. Basic authentication for AUTH USER model with email and password which will return session cookies. (say auth cookie) Using the auth cookie, user gets the list of accounts from the accounts table associated with his AUTH USER entry User sends the account_id along with the auth cookie. Backend returns new session cookie (say account cookie) for that user account and user will have all the permissions associated with that account. Problem: Django session framework authenticates only against the AUTH USER model, so how can I create account session & cookie the second time for the account model? How can I have multiple session tables for authentication? -
Cannot run django project [duplicate]
I am working on Django apps. I have a problem that, whenever I create a new Django project, I get error in browser. Precisely, I enter command "python manage.py runserver" in terminal and I open link http://127.0.0.1:8000/. In browser I get this path: http://127.0.0.1:8000/upload/, which has no relation with the app I created. I once used url "/upload/" in some app, so I suppose that it has relation with it. Please can you help me solve my problem because I don't know how to do that. -
how to get the selected radio button value from models in django
I'm doing a website in django but this is the first time i use this framework so i'm not so used to it. I need to save some information on a DB, and i need to take these information from some radio buttons. I tryied so many ways to get the data but nothing worked. So i'd like to ask how to get these data in models.py from a template,html. This is the code in views.py: def question1(request): form = CHOICES(request.POST) return render(request, 'question1.html', {'form': form}) This is the template question1.html: <form class="form-inline" method='POST' action="" enctype='multipart/form-data'>{% csrf_token %} {{form.NUMS}} </form> And then i literally don't know how to do the function in models.py