Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data in 'context' is not passed to HTML
The context within the first conditional statement is delivered well, but the context updated within the second conditional statement is not delivered in HTML. For example, 'MODEL_LIST' in first context is delivered well, but 'mape_val' in second context is not. I want it to be delivered. How Can I solve this problem ? <views.py function CODE> def csv_forecast(request): context = {} username = request.user if request.method == 'POST' and request.FILES.get('csvfile'): uploaded_file = request.FILES.get('csvfile') p_data = pd.read_csv(uploaded_file) p_data.reset_index(drop=True, inplace=True) columns_list = list(p_data.columns) columns_list = [column.lower() for column in columns_list] p_data.columns = columns_list os.makedirs('media/csv', exist_ok=True) p_data.to_csv(f'media/csv/{username}.csv', index=False) start_date = p_data.loc[0, 'date'] len_date = int(len(p_data)*0.8) end_date = p_data.loc[len_date, 'date'] datas = [] for i in range(1, len(columns_list)): datas.append(columns_list[i]) MODEL_LIST = ['ARIMA', 'EMA5', 'LSTM'] context = {'datas' : datas, 'd' : p_data, 'columns_list' : columns_list, 'MODEL_LIST' : MODEL_LIST, 'start_date' : start_date, 'end_date' : end_date} if request.POST.get('sendModel') and request.POST.get('sendPdata') and request.POST.get('sendRdata'): send_pdata = request.POST.get('sendPdata') send_rdata = request.POST.get('sendRdata') send_model = request.POST.get('sendModel') cleaned_pdata = re.split(r'[\[\],"]', send_pdata) cleaned_rdata = re.split(r'[\[\],"]', send_rdata) cleaned_model = re.split(r'[\[\],"]', send_model) selected_pdata = [i for i in cleaned_pdata if len(i) >= 1] selected_rdata = [i for i in cleaned_rdata if len(i) >= 1] selected_model = [i for i in cleaned_model if len(i) >= 1] … -
"GET /style.css HTTP/1.1" 404 2565
Ссылка на мой CSS файл Строение директорий Почему то при запуске сервера ошибка 404 не найден файл style.css пробовал ставить абсолютную адресацию не помогло , если запускать html через IDe то все работает. Как починить, спасибо. -
Field 'id' expected a number
I've defined my custom user model as below (to have email as username): class User(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email And Profile model in api app as below: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) def __str__(self): return self.user.email This is the serilizer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user', 'verified'] And the view: @api_view(['POST']) def get_user(request): email = request.data['email'] user = Profile.objects.get(user=email) serializer = ProfileSerializer(user) return Response(serializer.data) But when I call get_user and post email=myuser@mydomain.com to it, I get this: ValueError at /api/get/ Field 'id' expected a number but got 'myuser@mydomain.com'. -
How can I resolve this linting error? "Consider adding meta keywords. <html lang="en-US"> (H031)"
I'm pretty stumped here. I get that it's telling me I should add meta keywords but which ones ? what am I missing ? -
django is just a cluster fig, is PHP any better?
Am trying to learn Django, I followed several tutorials, followed Django guidelines and I ended up having no idea what am doing. if u want to add an app u have to update it in URLs of the app and connect it to the URLs in the site and update it in the list of apps and connect its function to the action file and update it again in the database file.. it's just a freaking mess to a person who's new to web development, is PHP any better or just the same unfriendliness to users? I designed a python app that took me 56 hrs and now I am tormenting myself with the attempt to make it usable by uploading to a website which made me end up having to learn server-side development, front-end development, and JS development... any recommendations on what should I do now to make my app usable? -
Dangjo with Mongodb, spaces in field name: FieldError: Cannot resolve keyword '' into field
Short-time lurker looking for a bit of guidance. I started a small project to automate a little of the day-to-day. I chose Python and from here I have become interested in programming. About a month ago I decided to keep track of what was going on and hooked up a MongoDB instance to the automated process. Moving onto a GUI using Django. I have hit an issue with one of my views and I suspect the answer will likely be to remove spaces from field names but thought I would ask here as a hail mary :) When trying to apply a filter to my objects it returns the following error: Error: django.core.exceptions.FieldError: Cannot resolve keyword '' into field. Choices are: NP Title ID, Product Code, Product Type, _id Problem model and view below: Model: class Railway_Products(models.Model): _id = models.ObjectIdField(name='_id', editable=False) np_title_id = models.CharField(name='NP Title ID', max_length=15) product_type = models.CharField(name='Product Type', max_length=15) product_code = models.CharField(name='Product Code', max_length=15) class Meta: db_table = "Products" verbose_name_plural = "products" View: class Railway_Products_ListView(generic.ListView): model = Railway_Products context_object_name = 'product_list' queryset = model.objects.filter(name='NP Title ID',__icontains='PPSA') I know the issue is this line: queryset = model.objects.filter(name='NP Title ID',__icontains='PPSA') and name= not enjoying the '' or simply not … -
MongoDB stopped the support for all 32 bits OS a while ago
MongoDB stopped the support for all 32 bits OS a while ago because it's limited to about 2GB of RAM which is simply not enough to run something in production and it was too complicated / costly to support both 32 and 64 bits systems in the code. I am learning MERN Stack Development and I don't have required specs computer (64bit), I learned NodeJs, React And also Express but Stucked at MongoDb because I don't have 64bit computer.I don't understand that how I continue. What technology replaces mongodb in this situation. It that PHP or Django(python). And Here is my Code- const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser:true,useUnifiedTopology:true}).then(()=>{ console.log("mongodb connected successfully!"); }).catch((err)=>{ console.log(err); }); Output- MongooseServerSelectionError: Server at localhost:27017 reports maximum wire version 3, but this version of the Node.js Driver requires at least 6 (MongoDB 3.6) at NativeConnection.Connection.openUri (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\connection.js:824:32) at C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\index.js:381:10 at C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5 at new Promise (<anonymous>) at promiseOrCallback (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10) at Mongoose._promiseOrCallback (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\index.js:1234:10) at Mongoose.connect (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\node_modules\mongoose\lib\index.js:380:20) at Object.<anonymous> (C:\Users\MASTER\Documents\temp file\MERN With 6PP\mongoDB\index.js:3:10) at Module._compile (node:internal/modules/cjs/loader:1103:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10) { reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:27017' => [ServerDescription] }, stale: … -
DRF use two models in one Serializer
My Profile model has relation with Django's built-in User model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) Looking at the documentation for Nested Relationships my serializers look like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['date_joined'] class ProfileSerializer(serializers.ModelSerializer): date_joined = UserSerializer(many=False) class Meta: model = Profile fields = ['user', 'verified', 'date_joined'] And my endpoint: @api_view(['POST']) def get_user(request): user = Profile.objects.get(user=request.user) serializer = ProfileSerializer(user) return Response(serializer.data) How ever I get this error when calling that with email=email address in the body of the request: TypeError at /api/get/ Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x000001C454C28F70> I don't want to use id for query. I want email address to be used. -
How to filter through objects in python? [closed]
I am receieving an array of items from an API like this: { "items": [ { "id": "1", "name": "Item #1", "owner": { "id": "james", "type": "user", }, }, { "id": "2", "name": "Item #3", "owner": { "id": "david", "type": "user", }, }, { "id": "3", "name": "Item #3", "owner": { "id": "david", "type": "user", }, }, ], } Based off this example, how can I return only the items by owner 'david' in my get function in Views? -
Django: how to change table names globally?
I know I can change table name per model using db_table attribute, as explained in the doc. However, what if I want to do it globally? Let's say, I want all my table to be like: db_table = f"table_{{model_name}}" Is there any setting for this? Otherwise, I guess I could use a mixin to be inherited from. However, the whole purpose of doing this is to NOT think of table naming when any developer will add a new model. After reading this issue, It seems maintainers didn't even consider to add this feature as they did not understand the need, which is pretty clear to me :/ Any idea? Thanks. -
I'm using django to build a website and I want to link tutors and students
I'm currently stuck with the best way of assigning tutors to students and then tutors can add lessons for these students and they can both see these lessons, but you can only assign one foreign key to the class "MyLessons". So I'm not sure whether it's worth creating a MyStudents class, storing students inside this (but their user is the same as tutors except is_tutor=false) and then for each student creating a MyLessons class that the tutor can add to. I think I can make an approach I'm just worried it won't be very efficient or there will be some serious problems later on. Such as the other way was that each lesson would auto take in the tutors email (I set the username to email) and then when displaying the tutors lessons it would go through every lesson and display the lessons with a matching email... problems are though, if I reassign a student to a new tutor I'd like the new tutor to see the lessons but this would mean manually changing each and if there are too many lessons and students the process would get slow. -
Edit related field on the edit page of the parent model
My Profile model has a OneToOne field with User model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) And ModelAdmin is defined as below: class UserAdmin(UserAdmin): fieldsets = ( .... .... ('Permissions'), 'fields': ( 'is_active', 'is_staff', 'is_superuser', .... .... Is it possible to add verified filed to the above (after is_superuser for example) so I can edit it in the same page as the rest of the User model? P.S: I've already managed to add it to list_display and list_filter of User. -
Django create db table headers from dict
I am trying to create a model.Model with the columnheaders(key) and types(value). I tried it with the setattr("self",columnheader,columntype) but this seems to not work. Can i dynamically alter the table with django inbuilts or do i have to use raw sql? My example dict: _dict = { "column_1": models.IntegerField(), "column_2": models.IntegerField() } My try class table(models.Model): for columnheader,columntype in _dict.items: setattr("self",columnheader,columntype) -
what are the technogies used to build news website with live steaming
Please specify the steps and required technologies to build website with live steaming option . i am trying to use WordPress but am not sure whether live streaming work in WordPress -
how to add url custom items to the apps menu in the Django admin?
i want add custom url in left menu Django admin -
How to create a dataframe from a nested JSONField in Django?
My Django model has a DateTimeField and a JSONField fields I would like to create a timeseries dataframe with. The package django-pandas has a method to_timeseries to do that but my problem is that it puts all the JSONField field into a column. How can I flatten this column into multiindexed columns ? models.py class Indicator(models.Model): dt = models.DateTimeField(null=True) metrics = models.JSONField(default=dict) JSONField dictionary: {'housing': {'1d_percent': 73.62755998, '2d_percent': 3e-08}, 'fund-flower': {'ratio': 0.01981295}, 'mpi': {'mpi': -0.6527736158660562}} Converting queryset to a timeseries dataframe : >> qs = Indicator.objects.all() >> qs.to_timeseries(index='dt', fieldnames='metrics').sort_index().dropna() metrics dt 2018-01-01 00:00:00+00:00 {'mpi': {'mpi': -0.01679772442974948}, 'fund-f... 2018-01-02 00:00:00+00:00 {'mpi': {'mpi': 1.1785319016689795}, 'fund-flo... 2018-01-03 00:00:00+00:00 {'mpi': {'mpi': 1.047678402830424}, 'fund-flow... 2018-01-04 00:00:00+00:00 {'mpi': {'mpi': 1.111703887319459}, 'fund-flow... 2018-01-05 00:00:00+00:00 {'mpi': {'mpi': 2.3908629334035343}, 'fund-flo... ... 2022-09-17 00:00:00+00:00 {'mpi': {'mpi': -1.0434999082318062}, 'fund-fl... 2022-09-18 00:00:00+00:00 {'mpi': {'mpi': -0.9680468633746766}, 'fund-fl... 2022-09-19 00:00:00+00:00 {'mpi': {'mpi': -0.9287818619840235}, 'fund-fl... 2022-09-20 00:00:00+00:00 {'mpi': {'mpi': -0.8487296227267782}, 'fund-fl... This is the desired output: mpi fund-flower housing dt mpi ratio 1d_percent 2d_percent 2018-01-01 00:00:00+00:00 value value value value 2018-01-02 00:00:00+00:00 value value value value 2018-01-03 00:00:00+00:00 value value value value 2018-01-04 00:00:00+00:00 value value value value 2018-01-05 00:00:00+00:00 value value value value ... 2022-09-17 00:00:00+00:00 value value value value 2022-09-18 00:00:00+00:00 value value … -
Django - annotating a field to a model query which adds a datefield value to an existing model field in views
I want to add a field to my model in views without adding it to the database using the annotate function. user_accounts_extension.objects.filter(types='trial').annotate(expire_date=duration + datetime.timedelta(days=180)) The model user_accounts_extension is an extension of the included auth models. "Duration" is a datefield which represents the date when the account is closed. I want my view to render this field + 180 days to my template - but the above code doesn't work. I've also tried: user_accounts_extension.objects.filter(types='trial').annotate(expire_date='duration' + datetime.timedelta(days=180)) To no avail. Is this possible to do, or do I need to add a new field to my model? -
Django: Best practice to sum all total amounts based on a model field
Here is my code reports: queryset for reports in reports: data.append(DataModel( model_id=report.num, title=report.title, total_price=report.total_amount, )) This code will create some DataModel objects and will append the object into a list. I want to sum total_price of all the objects with the same obj.id. For example: If we have these objects on the queryset: id:obj1 total_price: 10 id:obj3 total_price: 20 id:obj2 total_price: 30 id:obj1 total_price: 40 id:obj2 total_price: 50 In the list I want to have these object in the list: id:obj1 total_price: 50 id:obj3 total_price: 20 id:obj2 total_price: 80 What is the best practice to do that? -
Wagtail 2.14.2 ModulNotFound error after running makemigrations
3rd try of wagtail I did install it after having created a virtual environment named wag-env with virtualenv within the directory websites/wag/, not in the .virtualenv folder. Command was "virtualenv wag-env". Did pip install wagtail Then ran wagtail start ready_wag I then ran python3 manage.py makemigrations and get this error messages "ModuleNotFound error wagtail.models". A check in the lib confirmed that there is a models folder at wagtail root level, but no models.py. That's my third try since yesterday, first was with mkvirtualenv, had the same problem, second was with virtualenv, trying to integrate a finished django project, and now trying to start a project from scratch. I ran a pip freeze --user, there's a wagtail installed globally. Should I get rid of it ? Thanks in advance for your answers -
django inspectdb, foreignkey from different schema
in schema_curriculum & table clearance_item I added a constraint(ForeignKey) to schema_srgb & table_student then, I try to run inspectdb with the following command py manage.py inspectdb --database=curriculum clearance_item > models.py class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' I was hoping studid should change from CharField to ForeignKey, is it possible to form a connection from db1.schema2 > db.1schema1 tables -
Why am I getting "Invalid salt" in django?
I have written a code for registration and login in django. While doing login, I am getting the error "Invalid salt" Following is the code: @api_view(['POST']) def login(request): email = request.data.get('email') mobile_number = request.data.get('mobile_number') pin = request.data.get('pin') res = dict() print(dict, "dictonaryyyyyy") if email != None: email_result = Users.objects.filter(email= email).first() print(email_result.pin, "emaillll") if email_result != None: if bcrypt.checkpw(pin.encode("utf-8"), email_result.pin.encode('utf-8')): # if bcrypt.checkpw(pin, ) print("........") payload_data = dict() payload_data['email'] = email_result.email token = generate_token(payload_data) print(token, "token.........") res['messages'] = "Authentication Successful" res['status'] = 200, res['token'] = token return Response(res, status = status.HTTP_200_OK) ... ... How to get rid of this error? -
Automatic avoidance of category duplicates
I have the problem with Category Model. I have 2 tables: class Category(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) class Movie(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, null=False) so they are standard models with categories. User can create Category by creating a movie with the name of category additionaly. The problem is when user is trying to create Movie with category name that already exists, because it will create another category with the same name (like duplicate) and I want to avoid it. How to do it? I can't create unique name field, because many users can have same category (but I can use ManyToManyRelation) but still I don't know how to automatically avoid duplicates like bellow: If Category with that Name and this User does not exist > create Category If Category with that Name and this User exists > use this Category Regards -
How to Redirect tenant to subdomain home page after user can login in public schema
I have to redirect to home page without login in subdomain after login in public tenant That means suppose - public domain is : logic.com subdomain is : tenant1.logic.com I have tried to login to the public domain (logic.com/login) so now I have to redirect to the home page of the subdomain(tenant1.logic.com/home) Without subdomain login def login_user(request): if request.method == 'GET': return render(request, 'users/login-user.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['email'], password=request.POST['password']) if user is None: return render(request, 'users/login-user.html', {'form': AuthenticationForm(), 'error': 'Username and ' 'password did not ' 'match'}) else: client = Client.objects.filter(owner=user).first() with schema_context(client.schema_name): login(request, client.owner) host = request.META.get('HTTP_HOST', '') scheme_url = request.is_secure() and "https" or "http" url = f"{scheme_url}://{client.slug}.{host}" return HttpResponseRedirect(url) What can I do if anyone has know about this? Thanks in advance -
What are the technologies i have to use to bulid news website and app with live news streaming option
what are the technologies required, is it possible with using Wordpress -
how to mail an image stored in an array variable as attachment without saving it on the drive
I have an image stored in the memory as a NumPy array format( stored in a NumPy array variable). I want to mail this image as an attachment to a user without saving it on my drive. Is there a way for doing this? I have tried various codes but have not gotten the mail. can someone help me with this? any help is truly and sincerely appreciated.