Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to work many to one relationship in django
Hello friends I am trying to figure out how to work properly with a One to Many relationship. I want to create two models, The first model is Post And a second model is Comment Now I say that every post has many comments, and every comment has one post. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) message = models.TextField(max_length=256,null=True) def __str__(self): return str(self.title) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) message = models.TextField(max_length=256, null=True) I'm trying to figure out how I can get all the posts and all the comments so that all the comments match the post to which they belong That is, in the functions in the views file how do I send back this option. because on the HTML page I want to display the post with all its comments but there are a number of posts, so how do I do that? The only thought I can do is this: dict = {} all_posts = Post.objects.all() for post in all_posts: dict[post] = Comment.objects.filter(post=post).values() print(dict) but I have a feeling there is something better -
Tiltled previous and next blog using django class based view
If I open a blog detail, there should be the previous blog and next blog title as a pagination. From Django documentation, I implemented the pagination by page number. But how can I implement the pagination by previous blog and next blog title. Here is my model.py: class Post(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") cover = models.ImageField(upload_to="Uploaded/") content = RichTextUploadingField(blank=True, null=True) sticker = models.CharField(max_length=50, unique=False, null=True, blank=True) published_at = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=STATUS, default=0) tags = models.CharField(max_length=400, null=True, blank=True) class Meta: ordering = ['-published_at'] def __str__(self): return self.title views.py class PostDetail(generic.DetailView): model = Post template_name = 'blogs/post_detail.html' post_detail.html {% extends "blogs/base.html" %} {% load static %} {% block post %} <section class="services"> <dev class="box-container"> <div class="box-lg"> <h3>{{ post.title }}</h3> <img src="/Images/{{ post.cover }}" > <hr> <small>{{ post.published_at }}</small> <p>{{ post.content | safe }}</p> </div> </dev> </section> <!-- Pagination Start --> <div class="center"> </div> <!-- Pagination Ends --> {% endblock post %} Now please help me how to do the prev-next blog titled pagination like the below image! titled pagination image -
set ManyToManyField with particular users from another model's ManyToMany Field
I am building a simple blog app in which I am trying to add particular users from another model's ManyToFieldField to a new model's ManyToFieldField. class ClassGroup(models.Model): admins = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admins') members = models.ManyToManyField(settings.AITH_USER_MODEL) title = models.CharField(max_length=9999, default='') class ClassGroupInvite(models.Model): invite_sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) invite_receiver = models.ManyToManyField(ClassGroup.admins) As you can see that I am filtering (send request only to class group admins) in ClassGroupInvite with setting ManyToManyField with ClassGroup.admins But when I try this then it is showing ManyToManyField(<django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x000001CE78793280>) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string 'self' I also read the documentation about it, But I didn't find anything about defining it. then I tried using ClassGroup.admins.all then it showed AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' I have tried many times but it is still not working, Any help would be much Appreciated. Thank You in Advance. -
Django: Removing duplicated data in model
I am getting a data directly from an API and store it in list in dictionary format and then loads the data into the database , but whenever i open that page the data gets duplicated even tho i am clearing the list. -
find out when user leaves a page in django
I have an ajax function that sends requests to a Django view every second: function get_updates() { $.ajax({ url: full_path, type: 'GET', data: {latest_pk: latest_pk}, success: function(json) { ... }, complete: function(data) { setTimeout(get_updates, 1000); } }); } get_updates(); get method of the view is like this: def get(self, request, *args, **kwargs): if request.GET: # If there are GET parameters, use them to return updates. response = self.get_updates(request.GET.get("latest_pk")) return JsonResponse(response) else: # Otherwise if the url is simply requested, # return the rendered chat page. return super().get(request, *args, **kwargs) How can I execute some code in Django, after requests stopped being sent? I need to save the time of the last request. -
DRF and django_filters. Change queryset before applying filters
There is a ModelViewSet and a FilterSet that work great. But the problem is that I need to transform the queryset before filtering, for this I overridden the get_queryset() method. It changes the queryset, but as a result, on the page with a list of objects, I see that no changes have occurred. If I override the list() method using the rewritten get_queryset() method in it: queryset = self.get_queryset() Changes will occur, but filters will not work on this queryset. I tried using: qs = self.filter_queryset(self.get_queryset()) in this case, the filters work, but the data on the page remains as it was before the change in get_queryset(). Please tell me what is my mistake, why can't I filter the queryset with changes and what should be done to make the filtering of the transformed queryset possible? -
i have to make a relation between movie and actor without using manytomany field i have to use only foreign key in django i've write this code so far
models.py class Movielist(models.Model) : Title = models.CharField(max_length=1000) Description = models.TextField(blank=True) ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True) # NoOfActors = models.IntegerField() Upvote = models.IntegerField(default=0) Downvote = models.IntegerField(default=0) def __str__(self): return self.Title class Actorlist(models.Model): Name = models.CharField(max_length=1000) DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True) # NoOfActors = models.IntegerField() def __str__(self): return self.Name class ActorInMovie(models.Model): Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True) Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True) def __str__(self): return self.Movie.Title views.py def Movie_Detail(request): MovieName = Movielist.objects.all() tablelist = ActorInMovie.objects.all() return render(request, 'Collection/index.html', {'MovieName':MovieName, 'tablelist':tablelist}) index.html <table border="solid"> <th>Name</th> <th>Release Date</th> <th>Actors</th> {% for data in MovieName %} <tr> <td>{{ data.Title }}</td> <td>{{ data.ReleaseDate }}</td> <td> <ul> {% for name in tablelist %} <li>{{ name.Actor.Name }}</li> {% endfor %} </ul> </td> </tr> {% endfor %} </table> **i have getting this out put can any any one tell me how to filter this data only my movie id i would like if someone come and help me in solving this problem [this is the output what i am getting but i want filter actors name by movielist.id][1] [1]: https://i.stack.imgur.com/BlAuP.png** -
How to render not to see all the columns as default , user can select the column which they want to see
I am trying to not to make the columns as visiable as default , So by this html redering i can see all the columns but i want just one column not to show as default , but user can view the file if user want to to see the column. the django template configure column. {% extends "admin/base_site.html" %} <!-- LOADING --> {% load i18n grp_tags admin_urls static admin_list %} <!-- STYLESHEETS --> {% block stylesheets %} {{ block.super }} {{ media.css }} {% endblock %} <!-- BREADCRUMBS -- > {% block breadcrumbs %} {% if not is_popup %} <ul class="grp-horizontal-list"> <li><a href="{% url 'admin:index' %}">{% trans "Home" %}</a></li> <li><a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a></li> <li>{{ opts.verbose_name_plural|capfirst }}</li> </ul> {% endif %} {% endblock %} <!-- CONTENT-TITLE --> {% block content_title %} <h1>Columns for {{ opts.verbose_name|capfirst }} list</h1> {% endblock %} <!-- OBJECT-TOOLS --> {% block object-tools %} <ul class="grp-object-tools"> {% block object-tools-items %} {% if has_add_permission %} {% url opts|admin_urlname:'add' as add_url %} <li><a href="{% add_preserved_filters add_url is_popup to_field %}" class="grp-add-link grp-state-focus">{% blocktrans with opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}</a></li> {% endif %} {% endblock %} </ul> {% endblock %} <!-- CONTENT --> … -
Opening Local Desktop Applications from website button
I want to open a Desktop Application from the Website button. The Desktop Application actually uses the username and password to load so it will also be passed. The problem is that the Website works locally but does not work when hosted... I used OsPopen and Os.system to open the applications(which works locally). os.system('putty username@servername -pw password') os.Popen('putty username@servername -pw password') Custom Protocol Handler was tried but I am not able to pass the username and Password. Any Help would be really appreciated and would do wonders!! -
css does not work for <img src="{{i.image.url}}"> in django
I have an image tag in my html tags that wants to add an image to template through admin page of django. html: <body> {% for i in pr%} <div class='card'> <div class="number">{{i.number}}</div> <img src="{{i.image.url}}"> <span class="prname">{{i.name}}</span> <p id="id">{{i.description}}</p> <button><span class="price"> ${{i.price}}</span> <img id='add'src="{% static 'add.png'%}"> Add to cart</button> </div> {%endfor%} </body> i set up my media root and i can see the image in browser but my css about that image tag does not work. css: .card image{ max-height: 100%; max-width: 100%; } urls: urlpatterns = [ path('admin/', admin.site.urls), path('',views.a) ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) a part of settings: > # Static files (CSS, JavaScript, Images) > # https://docs.djangoproject.com/en/4.0/howto/static-files/ > > STATIC_URL = '/static/' > STATICFILES_DIRS=[os.path.join(BASE_DIR,'static'), ] > > # Default primary key field type > # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field > > DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' > > MEDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' How can i add some css to <img src="{{i.image.url}}">? -
Kubernetes pod keeps crashing
I have a database service like so in GKE. apiVersion: v1 kind: Service metadata: annotations: kompose.cmd: C:\ProgramData\chocolatey\lib\kubernetes-kompose\tools\kompose.exe convert kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.service: taiga-db name: taiga-db spec: ports: - name: "5472" port: 5472 targetPort: 5472 selector: io.kompose.service: taiga-db This is the DB-Deployment apiVersion: apps/v1 kind: Deployment metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.service: taiga-db name: taiga-db spec: replicas: 1 selector: matchLabels: io.kompose.service: taiga-db strategy: type: Recreate template: metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.network/taiga: "true" io.kompose.service: taiga-db spec: containers: - env: - name: POSTGRES_DB value: taiga - name: POSTGRES_PASSOWRD value: taiga - name: POSTGRES_USER value: taiga - name: POSTGRES_HOST_AUTH_METHOD value: trust - name: PGDATA value: /var/lib/postgresql/data/pg-data image: postgres:12.3 name: taiga-db resources: {} volumeMounts: - mountPath: /var/lib/postgresql/data/ name: taigadb-data restartPolicy: Always volumes: - name: taigadb-data persistentVolumeClaim: claimName: taiga-db-data status: {} This is the deployment that connects to it apiVersion: apps/v1 kind: Deployment metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.service: taiga-back name: taiga-back spec: replicas: 1 selector: matchLabels: io.kompose.service: taiga-back strategy: type: Recreate template: metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml kompose.version: 1.26.1 (a9d05d509) creationTimestamp: null labels: io.kompose.network/taiga: "true" … -
When i try to query django model by small positive integer field i get error
When i run the following code i get the error "TypeError: Field 'app' expected a number but got <AppChoices.SUK: 1>" class Category(models.Model): class AppChoices(models.Choices): ASK_EMBLA = 0 SUK = 1 --- class RentPostDetailSearializer(serializers.ModelSerializer): --- def get_posted_by_brief(self, obj: RentPost): ----- rating = 0 ratings = list(poster_profile.seller_reviews.filter( app=Category.AppChoices.SUK).values_list("rating", flat=True)) #---> issue here if ratings: rating = sum(ratings)/len(ratings) --- -
Django .py file code changes don't reflect on production server
I made a few changes in two .py files and when I transfer those files through Filezilla to my remote sides the changes in the production server don't reflect. What do I do any suggestions guys? -
i want to post data to Bonus field from a function made from the random choice of list elements
I am trying to make an api for a wheel which rotates and we get a random reward so i am using list and random function. I want to save the data in the Bonus field from the function corresponds to random choice if else condition. I have tried this. models.py class Wallet(models.Model): user = models.ForeignKey(User, null=True, related_name='wallet_mobile', on_delete=models.CASCADE) total_amount = models.FloatField(_('Total amount'), default=10) add_amount = models.FloatField(_('Add amount'), default=0) deposit_cash = models.FloatField(_('Full Add amount'),default=0) win_amount = models.FloatField(default=0) winning_cash = models.FloatField(default=0) withdraw_amount = models.FloatField(default=0) amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2, default=10) description = models.CharField(max_length=200, null=True, blank=True) Recieved_sreferral = models.CharField(max_length=200, null=True, blank=True) referral_status = models.BooleanField(null=True, blank=True) Bonus = models.FloatField(default=0) serializer.py class Bonusserializer(serializers.ModelSerializer): class Meta: model = Wallet fields = ['Bonus'] views.py @api_view(['POST']) def bonus_money(request, pk): if request.method == 'POST': qs = Wallet.objects.get(pk=pk) serializer = Bonusserializer(qs, data=request.data) if serializer.is_valid(raise_exception=True): Bonus = request.data['Bonus'] li = ['5 Rs. Entry ticket','Get Another Spin','50 Rs Bonus', '10% Discount Coupon','20% Extra Referral Bonus','5 Rs Bonus','Better luck next time','10 Rs Bonus'] x = random.choice(li) if x == li[0]: qs.Bonus = qs.Bonus + 5 qs.save() elif x == li[1]: y = 'Get Another Spin' return y elif x == li[2]: qs.Bonus = qs.Bonus + 50 qs.save() elif x == li[3]: y … -
i am unable to pass data from view.py to html templates django
My name is arslan chaudhry, currently i am working with django. In my django project i have made some filters to filter the product category wise.i have successfully display the category of products. But when i click on the category image i recived an empity page no error is dispalyed. I think data are not passing from view.py to html template.How i can fix this? the code is given below. views.py def collectionsview(request, slug): if(Category.objects.filter(slug=slug, status=0)): products=Product.objects.filter(category__slug=slug) category_name=Category.objects.filter(slug=slug).first() contex={products:"products",category_name:"category_name"} print(products) return render(request, "store/product/index.html", contex) else: return HttpResponse('This is not a valid product') html template {% extends 'store/layouts/main.html' %} {% block title %}Home{% endblock title %} {% block body %} <div class="container mt-3"> <div class="row"> <div class="col-md-12"> <h4>{{category_name}}</h4> <div class="row"> {% for item in products %} <div class="col-md-2"> <div class="card"> <a href="#"> <div class="card-body "> <div class="card-image"> <img src="{{item.imge.url}}" alt="" width="100%" height="100%"> <h4 class="text-center mt-1" style="font-size: medium; font-weight: 600;">{{item.name}}</h4> </div> <span>{{item.original_price}}</span> <span>{{item.selling_price}}</span> </div> </a> </div> </div> {% endfor %} </div> </div> </div> </div> {% endblock body %} -
Django models file field regex?
I want to be able to check if the files that are going to be uploaded through forms contain any sensitive information. Can someone please give me an idea on how I can accomplish this. This is my code. Models.py class File(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])]) def __str__(self): return self.title My upload code in views.py def upload_file(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) #request.Files handles file uploads if form.is_valid(): form.save() file_dlp() return redirect('file_list') else: form = FileForm() return render(request, 'upload_file.html', { 'form':form }) -
Why does my Fpl loop not showing up instead, React code not updating
I changed it to FPLLoop, but it still shows the same thing in the typography. Please help. For some reason nothing updates even after I save it. Is there some reason with react.js. import React, { Component } from "react"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import Room from "./Room"; import { Grid, Button, ButtonGroup, Typography } from "@material-ui/core"; import { BrowserRouter as Router, Switch, Route, Link, Redirect, } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); this.state = { roomCode: null, }; this.clearRoomCode = this.clearRoomCode.bind(this); } async componentDidMount() { fetch("/api/user-in-room") .then((response) => response.json()) .then((data) => { this.setState({ roomCode: data.code, }); }); } renderHomePage() { return ( <Grid> <Grid item xs={12} align="center"> <Typography variant="h3" compact="h3"> FPLloop </Typography> </Grid> <Grid item xs={12} align="center"> <ButtonGroup disableElevation variant="contained" color="primary"> <Button color="primary" to="/join" component={Link}> Join a Room </Button> <Button color="secondary" to="/create" component={Link}> Create a Room </Button> </ButtonGroup> </Grid> </Grid> ); } clearRoomCode() { this.setState({ roomCode: null, }); } #Rendered it can't fit as too much code, but the react is the problem It says house party instead -
Why Django can’t update date?
I practiced writing the update function(update)of Pytohn+Django ModelForm. But I have been catching bugs for many days, I still can't think of what went wrong... I came to ask you what is the error? Thank you for your advice. Attach the structure and url of MTV with form writing and pictures Model: `class TaskList(models.Model): task = models.CharField(max_length=200) priority = models.PositiveIntegerField(default=0) status = models.PositiveIntegerField(default=0) user = models.CharField(max_length=50) worker = models.CharField(max_length=50, null=True, blank=True) timestamp = models.DateTimeField(default=timezone.now) start_date = models.DateField(null=True, blank=True) finish_date = models.DateField(null=True, blank=True) def __str__(self): return self.task` Templates: `{% block main %}` `<form action="/edittask/" method="POST">` `{% csrf_token %}` `<table class="table table-striped">` `<tr>` `<td align=right>TaskItem</td>` `<td><input type=text name="task" size=100 value='{{target_edit.task}}' required></td>` `</tr>` `<tr><td> </td><td>` `<input type=submit value="Update" class="btn btn-primary">` `</td></tr>` `</table>` `</form>` `{% endblock %}` Views: `@login_required(login_url='/admin/login/') def edit_task(request,id=1): tasks = TaskList.objects.get(id=id) logged_user = User.objects.get(username=request.user.username) logged_user = UserProfile.objects.get(user=logged_user) form = TaskListEdit(instance=tasks) if request.method=='POST': form = TaskListEdit(request.POST,instance=tasks) print(form) if form.is_valid(): form.save() return redirect("/tasklist/") try: target_edit = TaskList.objects.get(id=id) except: return redirect("/tasklist/") return render(request,"edit_task.html",locals())` Url `urlpatterns = [ path('edittask/',views.edit_task), path('edittask/<int:id>/',views.edit_task), path('', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) forms: class TaskListEdit(ModelForm): class Meta: model = TaskList fields = ['task']` forms `class TaskListEdit(ModelForm): class Meta: model = TaskList fields = ['task']` enter image description here enter image description here enter image … -
Creating slug in my django model gives error: IntegrityError at /admin/blog/post/add/
I have this Django module (below), it creates a field called slug that is a slug of the model name and date: from django.db import models from django.utils.text import slugify class chessed (models.Model): name = models.CharField(max_length=60) type = models.CharField(max_length=20, choices=(('Gemach', 'Gemach'),('Organization', 'Organization'),)) description = models.CharField(max_length=750) picture = models.URLField(max_length=200, default="https://i.ibb.co/0MZ5mFt/download.jpg") slug = models.SlugField(unique=True, default=slugify(name), editable=False) When I try to create a new object from this item in my admin portal, tho, I get this error: IntegrityError at /admin/blog/post/add/ UNIQUE constraint failed: blog_post.slug More: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/post/add/ Django Version: 4.0.1 Python Version: 3.10.1 Installed Applications: ['info.apps.InfoConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: blog_post.slug) was the direct cause of the following exception: File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func response … -
Getting Error while trying to get the value of the many to many field in django
models.py class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to='org_logo/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "organisation_master" def __str__(self): return self.org_name serializers.py class Organisation_Serializers(serializers.ModelSerializer): product_name = serializers.CharField(source='product.product_name') class Meta: model = Organisation fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product','product_name') While i tried to get the value of the product name iam getting an error as "Got AttributeError when attempting to get a value for field product_name on serializer Organisation_Serializers. The serializer field might be named incorrectly and not match any attribute or key on the Organisation instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'product_name'. Can you please help me to fix this issue.Posting the traceback error. Request Method: GET Request URL: http://127.0.0.1:8000/api/onboarding/organisation/ Django Version: 3.2.12 Exception Type: AttributeError Exception Value: Got AttributeError when attempting to get a value for field `product_name` on serializer `Organisation_Serializers`. The serializer field might be named incorrectly and not match any attribute or key on the `Organisation` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'product_name'. Exception Location: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py, line 490, in get_attribute … -
Django-disqus: manage.py not accepting API key
I'm trying to integrate disqus into my Django app. I got the API key and put it in settings.py, but when I tried to start the local server, it is giving me an error. settings.py INSTALLED APPS = [ ... 'disqus', ] DISQUS_API_KEY = 'key' DISQUS_WEBSITE_SHORTNAME = 'website_shortname' Of course I've put the actual key and shortname. The error I'm getting: NameError: name 'key' is not defined help -
Is there a third-party authentication system for Django?
We are trying to integrate a Django application with an OpenID Connect (OIDC) provider as a Relying Party. The provider isn't a major vendor, and thus doesn't have custom-built packages, so we are leveraging Authlib. This works, but I'm stressed about the amount of custom code we are having to put in to manage the session and redirects and whatnot. I have experience in the Ruby and Node.js worlds, and those communities have the general-purpose authentication tools OmniAuth and Passport, respectively. Is there an equivalent for Django? Closest I've found is mozilla-django-oidc, which I may try — curious if there are others I'm missing. Thanks! -
Bulk import with mptt and Django
I have the following code to take data from a very large csv, import it into a Django model and convert it into nested categories (mptt model). with open(path, "rt") as f: reader = csv.reader(f, dialect="excel") next(reader) for row in reader: if int(row[2]) == 0: obj = Category( cat_id=int(row[0]), cat_name=row[1], cat_parent_id=int(row[2]), cat_level=int(row[3]), cat_link=row[4], ) obj.save() else: parent_id = Category.objects.get(cat_id=int(row[2])) obj = Category( cat_id=int(row[0]), cat_name=row[1], cat_parent_id=int(row[2]), cat_level=int(row[3]), cat_link=row[4], parent=parent_id, ) obj.save() It takes over an hour to run this import. Is there a more efficient way to do this? I tried a bulk_create list comprehension, but found I need parent_id = Category.objects.get(cat_id=int(row[2])) to get mptt to nest correctly. Also, I think I have to save each insertion for mptt to properly update. I'm pretty sure the parent_id query is making the operation so slow as it has to query the database for every row in the CSV (over 27k rows). The upside is this operation will only need to be done sporadically, but this dataset isn't so large that it should take over an hour to run. -
How do I add cropperjs to my django project
I am working on a django project that requires adding a profile picture and that works; but where the problem comes in is that when someone uploads a picture that is quite long or quite wide, the profile image display would look weird. I tried initializing basic cropperjs by adding this to my base.html <link rel="stylesheet" href="{% static 'cropperjs/dist/cropper.min.css' %}"> <script type="module" src="{% static 'cropperjs/dist/cropper.min.js' %}"> and i just wanted to follow the docs and i kept my edit-profile.html {% block content %} <div class="image-box"> <img src="{{ request.user.userprofile.profile_image.url }}" id="image" width="300px"> </div> {% endblock %} and my edit-profile.js console.log('Hello there') var $image = $('#image'); $image.cropper({ aspectRatio: 16 / 9, crop: function(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); } }); var cropper = $image.data('cropper'); but then when i runserver and i inspect the page, i see the error edit_profile.js:3 Uncaught ReferenceError: $ is not defined at edit_profile.js:3:14 so i tried creating a normal html file and linked it with a javascript file an then tried to initialize cropper. index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="forum/static/cropperjs/dist/cropper.css"> <meta http-equiv="Access-Control-Allow-Origin" content="*"/> <title>Test site</title> </head> <body> <div class="image-box"> <img src="yor.png" id="image" width="300px"> </div> <script type="text/javascript" … -
How to get all manytomany objects in a queryset of objects
I have a model Department which has Roles which Users are linked to. I know the user, but need to get the user.role.department_set.all() (all departments the user's role belong to) and then get all the roles in each of those departments. Models: class User(AbtractUser): role = models.ForeignKey(Role) class Role(models.Model): name = models.CharField() class Department(models.Model): name = models.CharField() roles = models.ManyToManyField() How can I get all the departments which contains the user's role, then get the roles of all those departments? I am doing something like this currently but it is a very expensive lookup: def get_departments(self): """Returns a list of departments the user is in.""" return self.role.department_set.all() def get_users_departments_roles(self): """Returns all the roles of all the departments the user is in.""" departments = self.get_departments() roles = Role.objects.none() for department in departments.iterator(): for role in department.roles.all(): roles |= Role.objects.filter(name=role.name) return roles Side question: After typing all this out, would it be better to just add the a department field to each user? My concern is that if a role changes, I will also have to change the department at the same time and it will add complexity.