Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: type object 'AuthUserGroup' has no attribute 'REQUIRED_FIELDS'
I am using Django 3.0.5 and trying to make migrations but I get this error AttributeError: type object 'AuthUserGroup' has no attribute 'REQUIRED_FIELDS'. I have added the AUTH_USER_MODEL=mins_auth.AuthUserGroup in settings.py. This is the class model AuthUserGroup: class AuthUserGroup(models.Model): appuser = models.ForeignKey(AppUser, blank=True, null=True, on_delete=models.SET_NULL) group = models.ForeignKey(AuthGroups, blank=False, null=True, on_delete=models.SET_NULL) class Meta: """Override table details.""" db_table = 'auth_user_groups' verbose_name = 'AuthUserGroup' verbose_name_plural = 'AuthUserGroups' What am I doing wrong? -
Django Rest Framework Related Query?
There is 3 models, Article(post) Follow(To follow a user) User, How can I get all the post of user I'm following? class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(db_index=True, unique=True, max_length=255) title = models.CharField(max_length=255) subtitle = models.CharField(blank=True, max_length=400) body = RichTextUploadingField() class Follow(models.Model): user_from = models.ForeignKey(User, related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey(User, related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class User(models.Model): pass -
Action decorator with API view in Django is not working
I have created following API view. class LandingFlowViewSet(APIView): @action(detail=True, methods=['GET']) def get_mobile_number(self, request, pk=None, *args, **kwargs): return Response(('ok'), status=200) urls.py path('landing-flows/', views.LandingFlowViewSet.as_view()), request format :- /landing-flows/get_mobile_number/ I am getting 404 error.It is working fine with model view set. -
Hide a button in jQuery after an AJAX call
I have a list of items from a database displayed thanks to a for-loop in Django. I have a "save button" next to each one to save them to a favorite database thanks to an AJAX call. Everything works like a charm. But I want the "save button" to .hide() whenever the AJAX call is a "success". But if I do so, every "save button" from the page is hidden. So I tried to use .parent() or .closest() to select only the <div> where my "save is button" with no luck. My HTML: {% for sub_product in products %} <div class='sub_button'> <form class="add_btn" method='post'>{% csrf_token %} <button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button> </div> {% endfor %} My AJAX: $(".added").on('click', function(event) { event.preventDefault(); var product = $(this).val(); var url = '/finder/add/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) $(this).parent('.sub_button').hide(); } }); }); -
How to serve an image variable in a response?
When serving a file, we normally include it in the Response as such: response['Content-Disposition'] = f'attatchment; filename="<file-path>"' My issue however is I need to serve an image file from a variable. The image is stored on a different server which is downloaded, stored as a variable, and then needs to be attached to my Response object. Is this possible? Something like the following: import PIL, io from django.http import HttpResponse img = PIL.Image.open(io.BytesIO(photo_bytes)) response = HttpResponse(content-type='image/png') response['Content-Disposition'] = f'attatchment; filebytes="{photobytes}"' -
Django how to filter ManyToMany Field
I am trying to build a form with filtered many-to-many field. so i created Objects: Dayname 1) name=sunday 2) name=monday Submain 1) name:Math days(ManytoMany field): Sunday Monday 2) name: Sport days(ManytoMany field): Tuesday 3) name:Dance days(ManytoMany field): Sunday Tuesday Day 1)name(Char field)="Sunday" hog1(ManytoMany field, filterd): will show me only Dance and Math to pick. how can i filted this hog1 manytomany field in the form.py ? should i change the Name of Day model into forginkey of dayname? thank you for any help. I Have 3 Models: Models.py class Dayname(models.Model): name = models.CharField(verbose_name="day", max_length=200, null=True) def __str__(self): return self.name class Submain(models.Model): name = models.CharField(verbose_name="שם החוג", max_length=200, null=True) days = models.ManyToManyField(Dayname, verbose_name="ימי פעילות", related_name="active", max_length=200, null=True, ) def __str__(self): return self.name class Day(models.Model): name = models.CharField(verbose_name="יום", max_length=200, null=True) hog2 = models.ManyToManyField(Submain, verbose_name="חוג 2 ביום", related_name="hog2", max_length=200, null=True, ) def __str__(self): return self.name forms.py class DaysForm(ModelForm): def __init__(self, *args, **kwargs): super(DaysForm, self).__init__(*args, **kwargs) self.fields['hog1'].required = False self.fields["hog1"].widget = CheckboxSelectMultiple() self.field['hog1'].queryset = Submain.objects.filter(days__in__name="sunday") -
Django ModelForm not saving any data
Using django 3, I have a model and a modelform: class Upload(models.Model): content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ['content',] def clean_content(self): content = self.cleaned_data.get('content') if len(content) > MAX_CONTENT_LENGTH: raise forms.ValidationError('This content is too long') The view looks like this: def upload_view(request, *args, **kwargs): form = UploadForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance = instance.save() form = TweetForm() I am prompting the user to upload the contents only. After saving the form, even if I input some text inside the form, in the database it gets a value of NULL. How do I fix this? -
Django ORM: child's fields & values not inherited. Objects duplicated. (Using Django admin interface)
I'm trying to have a variety of dishes (Pizza, Subs, etc) that inherit from a common (concrete) parent class Dish. (Logically, I have no reason for it to be concrete other than having had difficulties implementing it). Every pizza (or other concrete dish) corresponds to exactly one dish ID (implemented as FK here) and every dish (ID) is exactly one pizza. I am new to this, but based on my understanding, the shared fields (name, type price, size and dish ID (PK for Dish = FK dish_id for Pizza)) in Dish as well as their values are inherited by children such as Pizza. So much for the theory. Now I implemented the classes as per below. And then I use the Django Admin interface to create objects, but against expectations, when I create a Dish object of type 'Pizza', automatically a Pizza object is created. Now when I go into that Pizza object, the name, type, price and size fields are blank. Shouldn't they be aready set when I select Pizza's dish attribute as the Dish-object I just created? And also when I start by creating a Pizza, selecting the corresponding parent (or creating it in the Django admin interface), … -
How to query links present in database from data I've got from user in Python?
I have cruciblelinks that I'm getting from a user in the form of: ['https://crucible05.cerner.com/viewer/cru/CCS-28483', 'https://crucible05.cerner.com/viewer/cru/CCS-28520'] It's a list data type. My Python model looks like this - (this is just to get a clearer picture) class reviewComments(models.Model): reviewID = models.CharField(max_length=20, blank=True) commentID = models.CharField(max_length=20, primary_key=True) solution = models.CharField(max_length=50) comment = models.TextField() dateCreated = models.DateField() type = models.CharField(max_length=20, blank=True) **crucibleLink = models.URLField(blank=True)** authorID = models.CharField(max_length=20) reviewerID = models.CharField(max_length=20) def __str__(self): # pragma: no cover return self.commentID In MongoDb, I have crucibleLink's that are present in the form of https://crucible05.cerner.com/viewer/cru/CCS-26041#CFR-2549575 (notice the extra # part) How do I query in Python so that I am able to get the data from MongoDb of the links that I was getting from the user in the beginning? -
DRF_simplejwt authentication does'nt work
i have an user_auth with drf_simplejwt, but only the super user can make login, when i try to make login with a normal user its not work #serializers.py class TokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user return serializers.ValidationError('Incorret cridentials') #views.py from rest_framework_simplejwt.tokens import RefreshToken class TokenView(generics.GenericAPIView): serializer_class = TokenSerializer def post(self, request, *args, **Kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data refresh = RefreshToken.for_user(user) return Response({ 'user': UserSerializer(user, context=self.get_serializer_context()).data, 'token': { 'refresh': str(refresh), 'access': str(refresh.access_token) } }) -
Djnago Razorpay integration
I want to integrate my website with razorpay, but I am lacking with the correct resource or tutorial for that. Actually I want a wallet in my website in which a user add money in his/her wallet by simply entering the amount in form and submitting the form. But I don't known how to link all files like models.py views.py urls.py and as well as the templates file. The attempt is given below please help! class PaymentDtails(models.Model): paymentby=models.OneToOneField(User,on_delete='CASCADE',null=True) razorpay_id = models.CharField(max_length=255) payment = JSONField(null=True, blank=True) amount=models.IntegerField(default=0) forms.py class AddMoneyForm(forms.ModelForm): class Meta: model= PaymentDetails fields=('amount',) please help me to integrate all that -
Chat application between user and customers
want to create a simple chat application between users and customers with the help of Django Channels.. this is my model. class ExternalMessageModel(models.Model): """ This class represents a chat message. It has a owner (user), timestamp and the message body. """ customers = models.ForeignKey('customers.Contact', on_delete=models.CASCADE, verbose_name='customer', related_name='from_customer', db_index=True) users = models.ForeignKey('users.UserProfile', on_delete=models.CASCADE, verbose_name='users', related_name='to_user', db_index=True) timestamp = models.DateTimeField('timestamp', auto_now_add=True, editable=False, db_index=True) body = models.TextField('body') I know how to create a chat application between users and users. but here my requirement is a bit different I have two tables one or user and another for customer.so my requirements are reals time communication between users and customers -
Django: the post isn't selected automatically of particular user
hi am working on a project where am using multiple user data a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post is not selected on which he adds price this is my post model.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) this is my second model of adding price to a particular post class price(models.Model): my_post = models.ManyToManyField(Loader_post, related_name='prices') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) approved_price = models.BooleanField(default=False) status = models.BooleanField(default=False) this is my adding price to the post views.py @login_required def add_price_to_post(request, pk): post = get_object_or_404(Loader_post, pk=pk) user = request.user if request.method == "POST": form = price_form(request.POST) if form.is_valid(): ps = form.save(commit=False) ps.user = request.user ps.status = True ps.post = post ps.save() return redirect('Driver:Driverview') else: form = price_form() return render(request, 'price_form.html', {'form': form}) this is my html add post button {% for loader in Loader %} this is loop and this is button <a … -
Linking Foreign key between tables in django models
I am just starting out with Django and so please help me out with my doubt. Currently, I have three tables Topic, Webpage, and AccessRecord. In the third table AccessRecord, I have used a ForeignKey with the second table Webpage. But Webpage table has three attributes topic, name, and URL ..so my doubt is which attribute of these three will be treated as a Foreign key to AccessRecord table. Any help will be greatly appreciated. class Topic(models.Model): top_name = models.CharField(max_length=264,unique = True) def __str__(self): return(self.top_name) class Webpage(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage,on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date) -
Sentry cloud database migration: Cannot see the migrated data in the new Sentry install
Here is the issue I am seeking to resolve: I am in the process of migrating a production Sentry instance (hosted on Nomad) onto a new new install (hosted on AWS ECS), both currently on version 9.0.0. Both the current and the new Postgres databases are hosted in AWS RDS. Same for Redis, they are both managed by AWS (i.e. ElasticCache). I have used two methods to migrate the database: (1) AWS RDS snapshot/restore, and (2) pg_dump, and pg_restore methods; and both worked successfully from the database perspective. The new database seems fine to me, with all tables exactly the same as the original database. However, when loading and hitting the new hosted Sentry instance, I can only see one empty Sentry organization, no teams, no project. Empty. I haven’t migrated the Redis database, but I can’t see why this would be the cause of it, given it’s a cache mechanism only. The source Sentry install instance also uses SAML2 for SSO. I cannot see any of that configuration, and any of that original data in the new install. What am I missing? Thank you. -
conect django to datastax casandra
I am try to conect django to datastax casandra but i cant do this. my database conection is here : DATABASES = { from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster 'default': { cloud_config= { ` 'secure_connect_bundle': 'secure-connect-okul.zip'` } auth_provider = PlainTextAuthProvider('mahmut215', 'm11223344m') cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider) session = cluster.connect() } } ` Help me please . -
How can I solve "cannot import name 'main' from 'virtualenv'"?
When I try running virtualenv I get the following error: [jelly@laptop Getskilled]$ virtualenv venv Traceback (most recent call last): File "/usr/bin/virtualenv", line 6, in <module> from virtualenv import main ImportError: cannot import name 'main' from 'virtualenv' (/home/jelly/.local/lib/python3.8/site-packages/virtualenv/__init__.py) Virtualenv was working when I last used it for a project so I am guessing that an update cause it to break. I have tried reinstalling virtualenv and pip. The closest post I could find was this one: virtualenv: cannot import name 'main' I tried following this post so I ran the following in the python interpreter: import virtualenv virtualenv.__file__ Which returned: '/home/jelly/.local/lib/python3.8/site-packages/virtualenv/init.py' However, there was no file /usr/local/bin/virtualenv.py and there is no virtualenv.py in the .local directory so that solution in that post won't work for me. What can I try next? -
Send Form Content to Endpoint in Different App Django
Say I have an app called App1 - inside of which there is a template that has a form with name and email. Now, say I have an app called App2 - that has an endpoint which takes in a name and email and sends an email to that email. Now, I want to combine the two, so that I can make the form contents go to the endpoint in App2 on submit, thus sending an email to the email in the form. How would I do this? Would it be better to just put them in the same app? When would someone use 2 apps over 1? Does this make sense? Thanks for your help! -
Tyring to understand WSGI interface in Django
I was recently trying to undestand the what is WSGI application: a WSGI application is just a callable object that is passed an environ - a dict that contains request data, and a start_response function that is called to start sending the response. In order to send data to the server all you have to do is to call start_response and return an iterable. So, here's a simple application: def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return ['Hello World!'] The Djangos wsgi.py is """ WSGI config for basic_django project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'basic_django.settings') application = get_wsgi_application() But when i see the wsgi.py the application = get_wsgi_application() object does not get passed with environ or start_response function So how to understand this -
Should I change password settings in Django or leave it as it is?
If I am building a website such as social media or even ones where there will be monetary transactions by users, is it a good idea to change the password settings for better security or do the default password settings incorporate better security measures in most cases? -
Django clone recursive objects
previously I have a problem when I want to clone the objects recursively. I know the simply way to clone the object is like this: obj = Foo.objects.get(pk=<some_existing_pk>) obj.pk = None obj.save() But, I want to do more depth. For example, I have a models.py class Post(TimeStampedModel): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=200) content = models.TextField(_('Content')) ... class Comment(TimeStampedModel): author = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField(_('Comment')) ... class CommentAttribute(TimeStampedModel): comment = models.OneToOneField(Comment, related_name='comment_attribute', on_delete=models.CASCADE) is_bookmark = models.BooleanField(default=False) ... When I clone the parent object from Post, the child objects like Comment and CommentAttribute will also cloned by following new cloned Post objects. The child models are dynamically. So, I want to make it simple by creating the tool like object cloner. This snippet below is what I have done; from django.db.utils import IntegrityError class ObjectCloner(object): """ [1]. The simple way with global configuration: >>> cloner = ObjectCloner() >>> cloner.set_objects = [obj1, obj2] # or can be queryset >>> cloner.include_childs = True >>> cloner.max_clones = 1 >>> cloner.execute() [2]. Clone the objects with custom configuration per-each objects. >>> cloner = ObjectCloner() >>> cloner.set_objects = [ { 'object': obj1, 'include_childs': True, 'max_clones': 2 }, … -
How to filter a ForeignKey in Django Model
I'm trying to filter a field to be shown in the Django admin form: class Buy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() image = models.FileField(upload_to='images/') date = models.DateTimeField() buy_price = models.DecimalField(max_digits=6, decimal_places=2) sell_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f'DM {self.id}' class Sell(models.Model): item = models.ForeignKey(Buy, on_delete=models.CASCADE) def __str__(self): return f'DM {self.id}' The issue is: the Django admin form must show only item > 0 in the Sell model. How can I do that with ForeignKey relationship in a simple way? I tried limit_to but it didn't work with greater than values. -
How can I get my css to render correctly?
So I'm a newbie and I'm having trouble getting my css to render in Django. I am attempting to create a red notification like in Facebook for my unread messages. But my css isn't rendering. What am I doing wrong here? Here's my code settings.py/Static_Dir STATIC_URL = '/static/' STATICFILES_DIRS = [ "/DatingAppCustom/dating_app/static", ] notification.css .btn { width:100px; position:relative; line-height:50px; } .notification { position:absolute; right:-7px; top:-7px; background-color:red; line-height:20px; width:20px; height:20px; border-radius:10px; } base.html/notification section <link href="{% static 'notification.css' %}"> <button class="btn">message counter <div class="notification">{% unread_messages request.user %}</div> </button> -
Cant add the last post to main body at django
I have no idea how to add my last post to the main content. With for loop it just copying the main content several times. I want to have these 3 blocks below to have a post and the last one to be on a main content (where the big picture located). here is the image Below my html code. <div class="container"> <div class="row"> <div class="col s6"> <div class="no-gutters"> <span style="color:pink; font-weight:bold; font-size:22px">NEW</span> <i class="small material-icons md-dark">favorite_border</i><span>25</span> <img src="{% static "images/comment.png" %}"><span>25</span> <i class="small material-icons md-dark">remove_red_eye</i><span>25</span> </div> <h2 class="blue-text">Some text/h2> <p>My last post</p> <a class="waves-effect waves-light btn-large"><span class="read">Read</span></a> </div> <div class="col s6"> <p> <img src="{% static "images/1Statya_3.png" %}" width="694px" height="568" /></p> </div> </div> </div> <hr> <div class="container"> <div class="row"> {% for post in posts %} <div class="col s12 m4"> <div class="card hoverable small"> <div class="class image"> <p>{{ post.date_posted }}</p> <img src="{% static 'images/1Statya_2.png' %}" class="center"> <span class="card-title">{{ post.title }}</span> </div> <div class="card-content"> <p>{{ post.content }}</p> </div> <div class="card-content"> <a href="#">Link blog</a> </div> </div> </div> {% endfor %} -
MODEL object has no attribute 'get' || django
I was trying to show the friends [model = FriendList] anyone have. so even if i used get to get the primary key....its giving an error. this is my models.py class Profile(models.Model): Gender = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(null=True, blank=True) birth_date = models.DateTimeField(null=True, blank=True, auto_now=True) gender = models.CharField(max_length=20, choices=Gender, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): if self.full_name == None: return "Full Name is NULL" return self.full_name class FriendList(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) profile = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str('%s -> %s' % (self.user.username, self.profile.user.username)) this is my views : def friend_list(request,pk): friends = FriendList.objects.get(id=pk) friend_list = None for i in friends: friend_list += i.user.username context={ 'friends':friend_list } return render(request, 'details/friend_list.html', context) why i'm gettig getting this error.....