Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display queryset list?
I am creating website for game tournaments. I have specialized queryset. I want to display on one page teams' names and their players. I tried to work with "get_queryset()" function but I don't understand what exactly. Probably there is mistake in template section. models.py from django.db import models class TestTeam(models.Model): name = models.CharField(max_length=30, default='Team') slug = models.SlugField(max_length=5) def __str__(self): return self.name class TestPlayer(models.Model): name = models.CharField(max_length=100, default='Player') nick = models.CharField(max_length=20, default='Nickname') team = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, default='Team') #photo = models.ImageField(upload_to='', null=True) No = 'N' Yes = 'Y' STANDIN_CHOICES = [ (Yes, 'Yes'), (No, 'No'), ] standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No) slug = models.SlugField(max_length=20, default=nick) def __str__(self): return self.name class TestMatch(models.Model): name = models.CharField(max_length=100, default='Match') leftTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Left Team') rightTeam = models.ForeignKey(TestTeam, on_delete=models.DO_NOTHING, related_name='+', default='Right Team') slug = models.SlugField(default=str(name)) def __str__(self): return (str(self.leftTeam) +" - "+ str(self.rightTeam)) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.TestView.as_view(), name='home'), path('<slug:slug>/', views.MatchView.as_view(), name='match'), ] views.py from django.views.generic import ListView, DetailView from . import models from django.shortcuts import get_list_or_404 class TestView(ListView): model = models.TestMatch template_name = 'home.html' class MatchView(DetailView): model = models.TestPlayer template_name = 'match.html' def get_queryset(self): queryset = super().get_queryset() if 'slug' in self.kwargs: team_slug = self.kwargs['slug'] TEAM … -
Bootstrap CDN not loading inside Django?
I am following this tutorial to learn Django : https://realpython.com/get-started-with-django-1/#why-you-should-learn-django All the steps were successful until the author started implementing Bootstrap CDN in his code: Django simply ignores it and doesn't show any different text fonts from the Bootstrap style. The section in the tutorial "Add Bootstrap to Your App" is the one I encountered a problem with and also later on "Projects App: Templates". I checked if all the code from the tutorial is correct in my project already. Do I need to install anything from Bootstrap? from the tutorial I understood I only needed to add the link. Thank you -
How can i get custom fields on ModelSerializer
I have a model class Teacher(models.Model): name = models.CharField(max_length=100) message = models.CharField(max_length=300) status = models.OneToOneField(Dictionary, on_delete=models.CASCADE) money = models.IntegerField(default=None, blank=True, null=True) My urls urlpatterns = [ path('get', views.GetViewSet.as_view({'get': 'list'})), ] My view class GetViewSet(viewsets.ModelViewSet): def get_serializer_class(self): GeneralSerializer.Meta.model = Teacher return GeneralSerializer def post(self, request): return self.select_api() def select_api(self): queryset = Teacher.objects.values("name","money").annotate(Count("money")) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) serializer class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None depth = 2 fields = '__all__' in this example in annotate func i have +1 field "money__count" but i can't display it cause my model have not a this field. How can i display it in api and i want a universal serializer (without adding static field to serializer cause it is universal serializer for all models) Please help me -
How to return each iteration using for loop in Django views
How to print iteration in template -
ArrayField In Django is giving error while doing migrations
I have added arrayfield to model in my application. Below is my model class employees(models.Model): firstName=models.CharField(max_length=10), lastName=models.CharField(max_length=10), tags_data = ArrayField(models.CharField(max_length=10, blank=True),size=8,default=list,) Below is my migrations file data. class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='employees', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tags_data', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=10), default=list, size=8)), ], ), ] when I am doing migrate I am getting the below error django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[8] NOT NULL)' at line 1") What is wrong with the syntax. Please help me where I am going wrong? -
After user login based on the user role page should redirect
Table called profile,in that table there is a field called designation,when user logins based on the designation the page should redirect. -
Django, limit many to many choices with exactly equal forignkeys
I have three models like that: " Model.1 X = CharField(...) Model.2 Y = ForeignKey (Model.1...) Model.3 ¥ = ForeignKey (Model.1...) Z = ManyToMany(Model.2...) " I want to just show up just some model 2 that have equal foreign key with model 3, in many to many field of model 3. I use limit chooses in models.py but its not affect dynamically when I make or edit new model3 object. How can I make this check box limited to equal forignkeys? -
How to access and share the model in django microservices
I splited my application from monolith to microservice architecture, but i'm using same Database across the microservices. But how will i fetch data from one application to other, because the model is specified in one application. But i want that data to displayed in other application. Same problem is already asked in stackoverflow, but there is no proper answer. The already existing question, they proposed request to access the data. But i don't feel that is best practice, because i need to make a request lot of times for every record. -
Django boto3 error during collectstatic command
I'm trying to run a gitlab project on a local machine. I have a problem at the start of the command manage.py collectstatic error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file if self.storage.exists(prefixed_path): File "/home/y700/Env/healthline/lib/python3.7/site-packages/storages/backends/s3boto3.py", line 532, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 634, in _make_api_call api_params, operation_model, context=request_context) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 680, in _convert_to_request_dict api_params, operation_model, context) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/client.py", line 712, in _emit_api_params params=api_params, model=operation_model, context=context) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/hooks.py", line 356, in emit return self._emitter.emit(aliased_event_name, **kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/hooks.py", line 228, in emit return self._emit(event_name, kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/hooks.py", line 211, in _emit response = handler(**kwargs) File "/home/y700/Env/healthline/lib/python3.7/site-packages/botocore/handlers.py", line 219, in validate_bucket_name if VALID_BUCKET.search(bucket) is None: TypeError: expected string or bytes-like object I tried to update the boto3 version, but … -
Is it possible to view/receive user form inputs from django site?
I have been experimenting with setting up an eCommerce section on a website. It's on a small scale so making a dedicated system isn't strictly necessary. I was wondering if it were possible to set up a form so that once filled in with for example a Name and Email, the owner of the site can see the contact information and get in touch. As mentioned, it's pretty small and won't have much traffic so having a massive amount of automation isn't needed. The site is run on Django (2.1.11) -
Advanced ORM usage for constraint filtering by an annotated value
I have the following Query/(ies) that I have constructed: users = User.objects.filter(is_active=True) date_range = [start_date, timezone.now()] results = SurveyResult.objects.filter( user__in=users, created_date__range=date_range, ).annotate( date=TruncDate('created_date'), total_score=Sum('score'), participants=Count('user'), ).values( 'survey', 'user', 'date', 'total_score', 'participants', ).order_by( 'date', ) A quick print of each result in the resulting QuerySet as: for result in results: print(results) ...outputs data as this: django_1 | {'survey': UUID('eb51368e-994a-4c0b-8d8a-e00ed20b5926'), 'user': UUID('25afbbfd-bddf-4fe8-bbac-758bd96093b0'), 'date': datetime.date(2019, 7, 26), 'total_score': 90, 'participants': 1} django_1 | {'survey': UUID('09947780-8d60-499f-87e3-fc53a9490960'), 'user': UUID('6afdea22-ea10-4069-9e7b-43fb6955ce0e'), 'date': datetime.date(2019, 7, 26), 'total_score': 17, 'participants': 1} django_1 | {'survey': UUID('890d0a21-6e27-457f-902e-e2f37d2fad6c'), 'user': UUID('d98684f7-97ab-49d7-be50-0cc9b6465ef5'), 'date': datetime.date(2019, 7, 26), 'total_score': 35, 'participants': 1} django_1 | {'survey': UUID('890d0a21-6e27-457f-902e-e2f37d2fad6c'), 'user': UUID('d98684f7-97ab-49d7-be50-0cc9b6465ef5'), 'date': datetime.date(2019, 7, 27), 'total_score': 62, 'participants': 1} The eagle eyed amongst you might notice that the last two records are pseudo-duplicate on the 'user' and 'survey' keys, but not on any of the other. My question is: how the heck do I remove the records from this record set (either using the Django ORM Query I have constructed or in a standard pythonic way) where the 'survey' and 'user' keys match - only keeping the most recent record according to the 'date'...so leaving me: Expected Outcome: django_1 | {'survey': UUID('eb51368e-994a-4c0b-8d8a-e00ed20b5926'), 'user': UUID('25afbbfd-bddf-4fe8-bbac-758bd96093b0'), 'date': datetime.date(2019, 7, 26), 'total_score': … -
using an isolated database like django models
I have a database (postgresql) which is not created by django models (orm). Now I need to use that database in my django project. I can write raw sql to retrieve data from database. But I do want to fetch data like I do with django models. How can I do that? -
How to implment nested queryset in Django ORM?
I am building API from django rest framework. I have a model in which there are certain foreign keys. For that model listing I am using ListAPIView. In that listing I want to implement nested queryset. Foreign key models are not directly in relation with each other. In following example. For multiple x there can be multiple y and for multiple y there can be multiple z. So I want json response as for unique x and in that object its y and its z. I tried with annotate and subquery. But that does not seem to solve my issue. Table: |x_id | y_id | z_id | |1 | 2 | 3 | |1 | 4 | 5 | |1 | 2 | 6 | class Workitem(models.Model): { x_id = # foreign key y_id = # foreign key z_id = # foreign key } class WorkitemSerializer(serializers.ModelSerializer) class Meta: model = Workitem fields = '__all__' depth=2 Current I am getting JSON response a { "count": 1, "next": null, "previous": null, "results": [ { "x_id": {"x_details"}, "y_id": {"y_details"}, "z_id": {"z_details"} } ] } I want response as { "count": 1, "next": null, "previous": null, results: ["x_id":{ "x_details": "y_id": { "y_details": "z_id": { … -
Access Directories of remote server with PHP
I am trying to upload files from my remote server to an s3 bucket. The catch is that I am accessing this server from localhost. While using PHP upload functionality in my django templates, it gives a list of files in my local directory. I would like it to give me the directories in my server. Is there anyway I can change the domain name of this php functionality to match my server's domain name? If yes, how? I am currently trying to find a backdoor mechanism like weevely that could connect with my server. <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html>` Select image to upload: TIA -
Filenotfound error: how to access local files from views in django (Apache server)
Not able to access local file (csv) from views.py file. Tried to give complete path, still facing same error. Project structure: mysite -- app -- views.py -- mysite -- segment.csv views.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) segment_path = os.path.join(BASE_DIR, r".\segment.csv") csv=pd.read_csv(segment_path) Error: [Wed Aug 07 15:57:45.637677 2019] [wsgi:error] [pid 6224:tid 992] [client 10.6.31.40:59595] FileNotFoundError: [Errno 2] File b'segment.csv' does not exist: b'segment.csv' Note: I can able to access static files and even able to run the site. There is some mistake I'm doing, not able to find out. -
Django/Webpack - How to serve generated webpack bundles with webpack dev server
Django's 'static' tag generates urls using STATIC_URL, which results in something like '/static/myapp/js/bundle.js' Mean while, webpack-dev-server is serving bundles from the url 'localhost:3000' My question is how do I get Django 'static' template tag to generate a different url ( which points to webpack dev server) for js bundles. Of course I can hardcore it in the template, but that would not be a good solution. Below is my project configuration webpack.config.js const path = require('path') const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const BundleTracker = require('webpack-bundle-tracker') module.exports = { mode: 'development', context: path.dirname(path.resolve(__dirname)), entry: { index: './typescript_src/index.ts', }, output: { path: path.resolve('./myproject/assets/myapp/bundles/'), filename: "[name]-[hash].js" }, resolve: { extensions: ['.ts', '.js' ] }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ } ] }, plugins: [ new CleanWebpackPlugin(), new BundleTracker({filename: './myproject/webpack-stats.json'}) ], devServer: { port: 3000, publicPath: '/myapp/bundles/', // hot: true, headers: { "Access-Control-Allow-Origin": "http://127.0.0.1:8000", /**Django dev server */ } } } settings.py WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'myapp/bundles/', # must end with slash 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': [r'.+\.hot-update.js', r'.+\.map'] } } STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) Initially I … -
AttributeError: 'CreateBatchForm' object has no attribute 'get'
When i run the following program i am getting the error: AttributeError: 'CreateBatchForm' object has no attribute 'get' I have tried changing the names of the objects and updated the arguments passed to the form "create_batch_admin" but it does not help. urls.py urlpatterns += [ #path('batches/create/', views.CreateBatchForm, name='create_batch_admin'), path('batches/create/', views.CreateBatchForm, name='create_batch_admin'), ] views.py import datetime from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from catalog.forms import CreateBatchForm #@permission_required('catalog.can_mark_returned') def create_batch_admin(request): """View function for creating a Batch by admin.""" template_name = 'catalog/create_batch_admin.html' # If this is a POST request then process the Form data if request.method == 'POST': print("Hello")# Create a form instance and populate it with data from the request (binding): form = CreateBatchForm(request.POST or None) errors = None # Check if the form is valid: if form.is_valid(): Batch.objects.create( batch_Name = form.cleaned_data.get('batch_Name'), start_Date = form.cleaned_data.get('start_Date'), end_Date = form.cleaned_data.get('end_Date'), time = form.cleaned_data.get('time'), ) # redirect to a new URL: #return HttpResponseRedirect(reverse('index') ) return HttpResponseRedirect("/s/") if form.errors: errors = form.errors context = { 'form': form, 'num_Batches': num_Batches, "errors": errors } return render(request, template_name, context) else: form = CreateBatchForm() if 'submitted' in request.GET: submitted = True return render(request, template_name, {'form':form}) create_batch_admin.html {% extends "base_generic.html" %} … -
How to update product quantity after adding product to cart?
I am working on a shopping cart project which is developed using angular and django. I want to update the qty of product when adding a product. but now the qty is updated when page is refreshed. Below code i have been tried so far. Home.Component.ts: async ngOnInit() { await this.getUpdatedCart();} ngOnDestroy() { this.subscription.unsubscribe();} async getUpdatedCart() { this.subscription = (await this.cartService.getCart(this.products)) .subscribe(cart => { this.cart = cart; console.log('cart', this.cart); });}} shopping-cart.services.ts async getCart(product) { const cartId = JSON.parse(localStorage.getItem('cartId')); if (cartId) { return this.http.get(this.globalService.baseUrl + 'shopping-cart/' + cartId + '/'); }} product-card.component.ts export class ProductCardComponent { @Input('product') product; @Input('shopping-cart') shoppingCart; constructor(private cartService: ShoppingCartService, private homeComponent: HomeComponent) { } async addToCart(product) { await this.cartService.addProductToCart(product); //this.getQuantity(); } getQuantity() { if (!this.shoppingCart) { return 0; } const item = this.shoppingCart.carts; for (let i = 0; i < item.length; i++) { if (item[i].product === this.product.id) { return item[i].qty; } } return 0;}} product-card.component.html <div class="card-footer"> <button (click)="addToCart(product) " class="btn btn-primary btn- block">Add to cart</button> <div>{{getQuantity() }}</div> </div> </div> I want when user click "add to cart" button then the quantity will be updated. but quantity is updated after i click the button twice. -
Django Rest Show Several Reverse Relation
I have a model to which several other models have OneToOne relationship: class ModelA(models.Model): title = ... description = ... class ModelB(models.Model): peer = models.OneToOneField(related_name='ModelB') score = models.IntegerField() class ModelC(models.Model): peer = models.OneToOneField(related_name='ModelC') score = models.IntegerField() What I want to do is to provide an endpoint in which I list the score value of all the reverse relation that ModelA has. This is my desired url: modelA/<int:pk>/reverse-relations/ So I have tried achieving so by writing this simple serializer: class ModelAReverseRelationSerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = ['ModelB', #This being the related_name 'ModelC',] And this view which I think I am getting something wrong here: class ModelAReverseRelationsView(ListAPIView): def get_queryset(self): print(self.kwargs["id"]) # Does not print anything in the console and I don't know why queryset = Threat.objects.filter( threat_id=self.kwargs["id"]) return queryset serializer_class = ModelAReverseRelationSerializer This approach returns the value of only one of the related models. I also tried setting many=true on the view but still I get on of the reverse relation's value. -
Django: send emails to users
I have a list of users with their email adress (only for Staff members), I am trying to send a form to the user. When I use i.email, I get this error: "to" argument must be a list or tuple When I use ['i.email'] I don't receive the message. urls.py path('users/<int:id>/contact', views.contactUser, name='contact_user'), views.py def contactUser(request, id): i = User.objects.get(id=id) if request.method == 'POST': form = ContactUserForm(request.POST) if form.is_valid(): message = form.cleaned_data['message'] send_mail('Website administration', message, ['website@gmail.com'], ['i.email']) return redirect('accounts:users') else: form = ContactUserForm() return render(request, 'accounts/contact_user.html', {'form': form, 'username': i}) I am using SendGrid. I have a 'contact us' form which is similar to contactUser and it works fine. -
Track Which user has updated which fields of any models?
How do I log which user has performed what changes(field value) in any of model? The way I tried: Write code in the pre_save signal. In that, I am getting the old and new value, but request object(for current login user) and list of updated fields are not getting. Write code in Django Forms save(), but same issue can fetch request object(current login user). -
How do I delete all the content in my database -Python-
How can I delete the entire contents of my database? Currently I have a script that reads a CSV file and stores the content in my database. But it's important to delete everything in the database before I add the new data. -> I run the script -> Database contents are deleted -> new data will be saved I have to do it that way, because the CSV file changes 1-2 times a day and the information it contains is completely different. -
How to fix "ImportError: cannot import name 'User' from 'cobudget.users.models' (/app/cobudget/users/models.py)" error?
I want to import my custom user model to another model file but I'm getting that error, when trying run django commands by manage.py. For example, I want to run "python manage.py migrate" and I'm getting this: Traceback (most recent call last): File "manage.py", line 30, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site->packages/django/core/management/init.py", line 381, in >execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/usr/local/lib/python3.7/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/app/cobudget/users/models.py", line 6, in from cobudget.companies.models import Company File "/app/cobudget/companies/models.py", line 2, in from cobudget.users.models import User ImportError: cannot import name 'User' from 'cobudget.users.models' (/app/cobudget/users/models.py) My models.py: cobudget/users/models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from cobudget.companies.models import Company class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. … -
django template tag pass as parameter of another template tag
I have 2 custom template tag as following: @register.simple_tag def foo(): return foo_value @register.simple_tag def bar(value): return bar_value + value and I want to to use them in my template like this: {% load my_custom_tags %} {% bar foo %} Is there a way to pass the result of a template tag to another template tag? -
How to order search results according to PageRank scores
I am working on a search engine that produces results with PageRank scores assigned to each link. I want the results to be ordered (sorted) according to the PageRank score (highest scored links come at the top). I am not an expert in python, but I used the following code with Django. I put part of the code I used here, please have a look: https://trinket.io/python/1d3490b96e How do I order the resulting links accoridng to their given PageRank Score? The scores are stored in a text file, and each link has its own score given during the crawling. Thanks