Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to convert Django uploadedfile.InMemory into numpy array or Image
#Views.py-- I want to convert uploaded image file into numpy array(cv2.imread) .Please help me ``` def upload(request): if request.method == 'POST' and request.FILES['image_file']: f = request.FILES['image_file'] myfile = str(f.read()) array_np = cv2.imread(myfile)``` -
Get all items with all properties using django multi-table inheritance and django rest framework (Cart Product)
I'm using PostgresSQL as DB, Django as backend and HTML, CSS, Javascript as Frontend. I have refer this question link but doesn't help me. Let me explain the whole scenario about my website. 1. I am building website like, if person brought a house then, a person need all household product, then my website will help him to get all the details of the single product like for ex. Fans (speed, RPM, Power consumption etc.), Side Table (Height, wood used, colour etc.) and more than tons of product. 2. Then my first page look like this. 3. Then the user go to the specific page (if click refrigerator link button -> List of Refrigerator(price, brand, specification)) 4. Then the user choose the specific item then he/she will redirect to the main page with selected item. (ref. image down below.) Now, my problem is that I can't access the details of the child table (reference table or link table)[Using Multi table Inheritance] As you can see on the above image I can't access (Refrigerator or other models) Details. Now my code goes here: models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class … -
Run Django/Python Ecommerce website & Php payment gateway on SSL with same domain
I'm newbie to django/python. I've successfully developed ecommerce website using django/python but now i want to deploy it on server using SSL with domain name using nginx so that if server restart i do not have to start the python server every time. Till now I have tried to run PHP payment gateway on 8443 port with subdomain and python on 443 port with main domain. If but nginx not pointing it to the actual python directory or something else and python or payment gateway not working. can anyone please help me to deploy both the things with the mentioned circumstances. Thanks in advance. -
How to export ForeignKeyWidget in django-import-export
I thought it would be possible to export a ForeignKey field.I tried but it isn't working. Where am I going wrong?? And first of all is it even possible??? class ExportAllIssuesResource(resources.ModelResource): book_id__reg_no = fields.Field(attribute='book_id__reg_no',column_name='reg no.') book_id__book_name = fields.Field(attribute='book_id__book_name',column_name='book name') borrower_id__name = fields.Field(attribute='borrower_id__name',column_name='student') borrower_id__student_id = fields.Field(attribute='borrower_id__student_id',column_name='adm') borrower_teacher__code = fields.Field(attribute='borrower_teacher__code',column_name='t_code',widget=ForeignKeyWidget(TeacherIssue,'code')) borrower_teacher__name = fields.Field(attribute='borrower_teacher__name',column_name='t_name',widget=ForeignKeyWidget(TeacherIssue,'name')) def export(self, queryset = None, *args, **kwargs): queryset = Issue.objects.all().filter(borrower_id__school = kwargs['school']) return super().export(queryset,*args, **kwargs) class Meta: model = Issue fields = ('book_id__reg_no','book_id__book_name', 'borrower_id__name','borrower_id__student_id','issue_date','borrower_teacher__code','borrower_teacher__name') export_id_fields = ('book_id__reg_no',) export_order = ('book_id__reg_no','book_id__book_name','borrower_id__name', 'borrower_id__student_id','issue_date','borrower_teacher__code','borrower_teacher__name') The view def ExportAllIssuesView(request): dataset = ExportAllIssuesResource().export(school = request.user.school) response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="All issues.xls"' return response The models. class Issue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def __str__(self): return str(self.book_id) class TeacherIssue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_teacher = models.ForeignKey(Teachers,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def __str__(self): return str(self.book_id) -
IntegrityError (1048, "Column 'id' cannot be null")
I'm making kinds of the chat room with Django. But I got the following error when I send a text. Maybe I should link message_room_id and form but I can't. What is wrong with my code? models.py class MessageRoom(models.Model): post = models.ForeignKey(Post, verbose_name='MessageRoom Post', on_delete=models.CASCADE) inquiry_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=False, related_name='inquiry_user') def __str__(self): return str(self.id) class Message(models.Model): message = models.CharField(max_length=100) message_room = models.ForeignKey(MessageRoom, verbose_name='Message', on_delete=models.CASCADE) def __str__(self): return str(self.id) Views.py class MessageRoomView(LoginRequiredMixin, DetailView): template_name = 'adopt_animals/pets/message_room.html' model = MessageRoom form_class = MessageForm context_object_name = 'message_room' success_url = reverse_lazy('adopt_animals:message_room') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) message_list = Message.objects.all() context['form'] = MessageForm for message in message_list: return context def post(self, request, **kwargs): message_room = MessageRoom.objects.filter(id=self.kwargs['pk'], inquiry_user_id=self.request.user.id) form = MessageForm(request.POST) if form.is_valid(): # Try to link message_room_id and message.id form.message_room_id = self.kwargs['pk'] form.save() else: print(form.errors) return redirect('adopt_animals:message_room', pk=message_room[0].id) forms.py class MessageForm(forms.ModelForm): message = forms.CharField(label='message', required=True) class Meta: model = Message fields = [ 'message', ] message_room.html <form action="{% url 'adopt_animals:message_room' message_room.id %}" method="POST"> {% csrf_token %} {{ form.errors }} <div class="send-msg"> {{ form.message }} <button class="btn btn-warning" type="submit">Send</button> </div> </form> -
How to generate vertical table?
How can I generate the vertical table in pdf using WeasyPrint? Also, I want to show only 50 records per pdf page. If 50limit exceeds then-new the record should be displed in same pdf but on new page. Can I achieve this using WeasyPrint? Somebody, please help, I'm stuck on this. -
nativation bar in django
I tried to add navigation bar to my djagno site but it gives a error like "Reverse for 'about' not found. 'about' is not a valid view function or pattern name." I use this this answer to make this navigation bar [stack over flow answer][1] Please give me a another option to do this or help to debug this code .anyway here is my base.html full file <!DOCTYPE html> <html> <head> <title>Django Central</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> ... {% block nav %} <ul id="nav"> <li>{% block nav-home %}<a href="{% url 'home' %}">Home</a>{% endblock %}</li> <li>{% block nav-about %}<a href="{% url 'about' %}">About</a>{% endblock %}</li> <li>{% block nav-contact %}<a href="{% url 'contact' %}">Contact</a>{% endblock %}</li> </ul> {% endblock %} ... <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background:#3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } </style> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow" id="mainNav"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home' %}" >Django central</a> <button … -
Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
Why this is showing a warning as it default take the primary key from the User model so should I also declare the primary key the Registration or candidate model again. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Registration(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) # phone = models.BigIntegerField(max_length=10,primary_key=True) dob=models.DateField() user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) def __str__(self): return self.fname class candidate(models.Model): full_name = models.CharField(max_length=30) position = models.CharField(max_length=30) total_vote = models.IntegerField(default=0) def __str__(self): return "{} -- {}".format(self.full_name,self.position) problem occured WARNINGS: poll.candidate: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the PollConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. -
Get a value from the url to set it as a value of the form?
I'm making a poll app where you have 2 options yes or no (Boolean), I want to save not only a number of votes but also who voted so I decided to make a "pivot" model connecting the User model and the Poll model like this: models.py # Vote choices BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) class PollVotes(models.Model): user = models.ForeignKey(userModels.User, on_delete=models.CASCADE, blank=True) vote = models.BooleanField(choices=BOOL_CHOICES) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) Its easy to set the user value using form.instance.user = self.request.user this way: (views.py) class PollVote(CreateView): model = PollVotes form_class = VoteForm template_name = 'poll_vote.html' success_url = reverse_lazy('polls') def form_valid(self, form): form.instance.user = self.request.user form.instance.poll = ????? return super(PollVote, self).form_valid(form) I'm thinking of getting the poll pk from the URL, but don't know how to do it. Right now the URL gets a int value this way: path('poll/vote/<int:poll>/', PollVote.as_view(), name='poll-vote'), How to relate that int:poll to a PK of some Poll? And then setting the form.instance.poll as a Poll with the PK of the URL? Maybe it's the wrong approach, it's just what I think will be the easiest way. forms.py class VoteForm(forms.ModelForm): class Meta: model = PollVotes fields = ['vote'] widgets = { 'vote': forms.RadioSelect } -
how to handle 2 inlines in one save_formset in django admin
I have model class like class Notification(models.Model): title = models.CharField(max_length=255, default='', blank=True) body = models.CharField(max_length=1024, default='', blank=True) created_at = models.DateTimeField(auto_now_add=True) class NotificationGroup(models.Model): notification = models.ForeignKey(Notification, on_delete=models.CASCADE) group = models.ForeignKey('core.Group', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('notification', 'group') class NotificationUser(models.Model): notification = models.ForeignKey(Notification, on_delete=models.CASCADE) user = models.ForeignKey('core.User', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('notification', 'user') So i want to handle it in django admin like... class NotificationGroupInline(admin.TabularInline): model = nm.NotificationGroup raw_id_fields = ('group',) readonly_fields = ('created_at',) extra = 0 class NotificationUserInline(admin.TabularInline): model = nm.NotificationUser raw_id_fields = ('user',) readonly_fields = ('created_at',) extra = 0 @admin.register(nm.Notification) class Notification(admin.ModelAdmin): list_display = ('id', 'title', 'body') inlines = (NotificationGroupInline,) def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def save_formset(self, request, form, formset, change): super().save_formset(request, form, formset, change) when i add model object about notification i want to handle 2 models in save_formset sametime but i can handle only NotificationGroup model like # formset.cleaned_data [{'notification': <Notification: Notification object (7)>, 'group': <Group: Group1>, 'id': None, 'DELETE': False}] is there any solution handle all models? like this # formset.cleaned_data [{'notification': <Notification: Notification object (7)>, 'group': <Group: 푸시테스트>, 'id': None, 'DELETE': False} {'notification': <Notification: Notification object (7)>, 'user': … -
manage.py stops after exception occurs
def edit_question(request): req = json.loads(request.body) guided_answers=req["guided_answer"] for guided_answer in guided_answers: try: models.Answer.objects.filter(answer_id=guided_answer["answer_id"]).update( question_id=models.Questions.objects.get(pk=question_no), mark=guided_answer["mark"], model_ans=guided_answer["model_ans"], ) except ObjectDoesNotExist or FieldDoesNotExist: models.Answer.objects.get_or_create( question_id=models.Questions.objects.get(pk=question_no), mark=guided_answer["mark"], model_ans=guided_answer["model_ans"], ) return success({"res": True}) what my code above is doing is trying to update the model answer and question marks if it exist and if not it creates a new model answer and question marks the above code works the issue is that after i create a new object the manage.py will abruptly stop, i would like the code to continue even after the exception, i am aware that it should stop however i would like it to continue and no i cannot use update_or_create because it gives me errors which is why i am using this. -
Django admin input text color is white instead of black
since I am new to Django and I am facing this input text color problem in Django admin panel. input text color is white instead of black. how to solve this problem?enter image description here -
Form created dynamically always gets 403 forbidden on a django rest framework api POST
I have multiple text posts on my website. On clicking the edit button I dynamically create a form replacing the div to a form element. I have my POST api set up on the django side to get this form submit and edit the existing post. But my POST request always gets 403. First i assumed not having a csrf token is causing the problem. So i edited my js code to this- //form create const post_content_element = post.querySelector('div .text-content'); const post_content = post_content_element.innerHTML; let edit_form = document.createElement('form'); // Here I added the csrf token as a hidden input let inputElem = document.createElement('input'); inputElem.type = 'hidden'; inputElem.name = 'csrfmiddlewaretoken'; inputElem.value = '{{ csrf_token }}'; edit_form.appendChild(inputElem); edit_form.setAttribute('id', 'edit-form'); edit_form.setAttribute('method', 'POST'); let text_content = document.createElement('input'); text_content.setAttribute('type', 'textarea'); text_content.setAttribute('id', 'edit-content'); text_content.value = post_content; let submit = document.createElement('input'); submit.setAttribute('type', 'submit'); submit.setAttribute('id', 'edit-submit'); edit_form.appendChild(text_content); edit_form.appendChild(submit); still it gets 403 forbidden. My api looks like this- @api_view(['POST']) def edit_post(request): if request.method == "POST": # do something return Response(status=status.HTTP_201_CREATED) Please note I am using my User(AbstractUser) model for authentication. I am out of ideas. What could be the other reasons for this problem? -
I Faced an Error while trying to Logout from Admin Panel in Django
When I am trying to log out from the Django panel I got this error and don't know where this error is coming from, can anyone help me with this error. Error Image -
erro: __str__ returned non-string (type DetComponente) /
Hail Devs. I have had this erro during template rendering. I have tried several resources looking for the error and have not been able to resolve it. I would like some help as to which way to go. Thanks TypeError at /form_mat/ __str__ returned non-string (type DetComponente) Request Method: GET Request URL: http://127.0.0.1:8000/form_mat/ Django Version: 3.2 Exception Type: TypeError Exception Value: __str__ returned non-string (type DetComponente) Exception Location: C:\webcq\venv\lib\site-packages\django\forms\models.py, line 1253, in label_from_instance Python Executable: C:\webcq\venv\Scripts\python.exe Python Version: 3.8.6 models class DetComponente(models.Model): componentes = models.CharField (max_length=50, null=True) def __str__(self): return self.componentes class Componente(models.Model): componentes = models.ForeignKey (DetComponente, on_delete=models.CASCADE) descricao = models.CharField (max_length=50) def __str__(self): return self.componentes class EspecComponentes (models.Model): componentes = models.ForeignKey (Componente, on_delete=models.CASCADE) codigo = models.ForeignKey (Codigo, on_delete=models.CASCADE) espec_material = models.ForeignKey (EspecMaterial, on_delete=models.CASCADE) diametro1 = models.FloatField (blank=True) diametro2 = models.FloatField (blank=True) peso = models.FloatField (null=True, blank=True) class Meta: ordering = ['componentes'] def __str__(self): return str (self.componentes) views def view_mat(request, pk): data = {} data['db'] = EspecComponentes.objects.get(pk=pk) return render(request, 'materiais/view.html', data) -
How do I remove the JWT Authentication requirements from certain models? Django Rest API / Axios
I have a few models, some of them just holds images and information I want to display on the screen (BEFORE the user logs in) I followed a guide to setup my JWT authentication for users, and I created the other models myself. I'm getting Unauthenticated messages when I try to do a .get() on my other models, which I do not want them to need to be authenticated. I want anyone to be able to login, and see that information. What is a simple way, I can remove the authentication requirements from these models? I never set up any JWT for these models, so I am surprised the user model which has JWT is effecting these.. but anyways. I'm pretty new to coding. I cannot find anything on google to answer this question. How can I send some information through my axios get request to say, "HEY THIS DOESN"T NEED TO BE AUTHENTICATED." Like, a master key to get me through that requirement. enter image description here enter image description here enter image description here enter image description here -
I am lost here help me
I am trying to use python manage.py migrate but getting error so guide me please from django.db import models class Topic(models.Model): Top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.Top_name class WebPage(models.Model): topics = models.ForeginKey(Topic) 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.ForeginKey(Webpage) date = models.DateField() def __str__(self): return str(self.date) THIS IS THE ERROR:- File "E:\My_jango_code\sixth_project\sixth_app\models.py", line 15, in WebPage topics = models.ForeginKey(Topic) AttributeError: module 'django.db.models' has no attribute 'ForeginKey' -
How can I fetch data by joining two tables in django?
Looking for help got stuck at a point, I am new to python and django. There ARE two payments corresponding to one order, one COLLECTION and multiple TRANSFER and i need the payment corresponding to an order whose direction is COLLECTION only NOT transfered yet so that i can initiate TRANSFER against that order models.py class Orders(models.Model): id= models.AutoField(primary_key=True) payment_gateway_code = models.CharField(max_length=20,choices=[('PAYTM','PAYTM')]) is_active = models.BooleanField(default=True) class Payments(models.Model): id = models.AutoField(primary_key=True) orders = models.ForeignKey(Orders, on_delete=models.CASCADE) direction = models.CharField(max_length=20,choices=[('COLLECTION','COLLECTION'), ('TRANSFER','TRANSFER')]) settlement_status = models.CharField(max_length=50,blank=True, null=True,choices=[('YES','YES'), ('NO','NO')]) is_active = models.BooleanField(default=True) qualified_orders = Orders.objects.filter(payment_gateway_code='CASHFREE', Exists(Payments.objects.filter(order=OuterRef('pk'), direction='COLLECTION', settlement_status='YES')), ~Exists(Payments.objects.filter(order=OuterRef('pk'), direction='TRANSFER'))) But above query is not working -
TemplateView.get_template_names() and TemplateView.template_name return different templates
I'm trying to establish the template for a TemplateView based on what is contained within or not within a QueryDict. When the get_template_names() is truthy it is suppose to return questions/search_help.html. When template_name is accessed from the Template View it returns "questions/paginated_all_questions.html". What can be done in order for the TemplateView.template_name to equal what is returned from get_template_names()? In this case template_name == 'questions/search.html' class SearchPage(AllQuestionsPage): def get_template_names(self): if 'q' not in self.request.GET or self.request.GET['q'] == "": template_name = "questions/search_help.html" else: template_name = "questions/paginated_all_questions.html" return [template_name] def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if context['view'].template_name == 'questions/search_help.html': context['page_title'] = "Search" else: context['lookup_buttons'] = { 'relevence': False, 'newest': False } context['page_title'] = "Search Results" return context def get(self, request): context = self.get_context_data() if 'q' not in request.GET or request.GET['q'] == "": pass else: tab = request.GET.get('tab', 'relevence') q = request.GET.get('q', None) if not q: return HttpResponse(reverse('search')) if tab not in context['lookup_buttons'].keys() or tab == 'relevence': context['lookup_buttons'].update(relevence=True) else: context['lookup_buttons'].update(newest=True) regex1 = re.compile(r'[user|answers|score]+:\d+') search_match = re.match(regex1, q) regex = re.compile(r'\s*[?[a-z]+(?=])\s*|^\s*[a-z]+\s*$', re.I) tag_match = re.match(regex, q) if search_match: q_param, q_value = q.split(":") if q_param == 'user': user = get_object_or_404(User, pk=int(q_value)) context['questions'] = Question.objects.filter( user_account=user.user_account ) elif q_param == 'score': context['questions'] = Question.objects.filter( vote_tally__gte=int(q_value) … -
ValueError: Cannot assign "2": "Model.field" must be a "Model" instance
I have a registration system that works on otp. I have a custom user model class User(AbstractUser): password = models.CharField(max_length=128, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) dial_code_id = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100, blank=True, null=True) username = models.CharField(max_length=150, unique=True, blank=True, null=True) is_resource = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) skills = models.ManyToManyField(Skills) class Meta: db_table = "my_user" def __str__(self): return self.mobile_number I have created an 'otp' model to save otp. class Otp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) otp = models.IntegerField() created_on = models.DateTimeField(default=django.utils.timezone.now) class Meta: db_table = "otp" My views looks like this class UserCreateResponseModelViewSet(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() custom_data = { "status": True, "message": 'Successfully registered your account.', "data": serializer.data } generate_otp(serializer.data['id']) return Response(custom_data, status=status.HTTP_201_CREATED) else: custom_data = { "status": False, "message": serializer.errors, } return Response(custom_data, status=status.HTTP_200_OK) class UserCreateViewSet(UserCreateResponseModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer I have a function to generate and save otp def generate_otp(user_id): try: otp_obj = Otp.objects.get(user_id=user_id) except Otp.DoesNotExist: otp_obj = None if otp_obj is None: otp = random.randrange(1000, 9999) otp_obj = Otp(user=user_id, otp=otp) otp_obj.save() Serializer looks like class UserSerializer(serializers.ModelSerializer): mobile_number = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) class Meta: model = User fields = ['id', 'first_name', 'last_name', 'email', 'dial_code_id','mobile_number', 'is_resource', 'is_customer'] … -
How to send an Image stored in the cloud via Django EmailMessage as an attachment
I am trying to create an uber clone using Django where when a driver registers in our platform an email is sent to use to validate his account, in which I need to attach the image in the email which would be stored in an AWS S3 bucket. def driver_confirmation_email(request, user, profile): content = f""" A user has registered for the site and needs the approval to use our service. User ID: #{user.id} First Name: {user.first_name}, Last Name: {user.last_name}, Email: {user.email}, Phone Number: {profile.mobile}, Date of Birth: {profile.date_of_birth}, Gender: {user.get_gender_display}, District: {user.district}, NIC Number: {user.nic_number} Consider approving the user by this link http://127.0.0.1:8000/admin/user/profiledriver/{user.id}/change/ """ license = open(profile.license.path) EmailMessage( f"Approval of the new user {user.first_name} {user.last_name}", content, 'najaaznabhan@gmail.com', ['najaaznabhan@gmail.com'], ).attach(license).send() This is currently my code where user is the registered user and the profile is any other related information of the user being registered. For some reason, I am thrown with an error that the file can't be opened. Do we need to use io.BytesIO and create a buffer to hold the image and then attach it? I am not very sure how to get that done. Just in case this is my profile models.py... class ProfileDriver (models.Model): mobile = models.CharField(max_length=13) … -
django create object with null foreign key
I have defined class Directory as follows: class Directory(models.Model): dir_name = models.CharField(max_length=100) parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.dir_name When I enter a specific UI for the first time, the program will call a function in views.py to check if any directory exists, otherwise create the root directory: root, created = Directory.objects.get_or_create(dir_name='media/', **insert null to foreign key**) The reason of the above is that the root directory has no parent. How can I achieve this in django syntax? (I've tried something like parent='' and parent=null, but none of them worked). Thanks a lot in advance! -
How to delete a old image when it is updated?
I want the previous picture uploaded by the user to be deleted when the user updates it. I have tried modifying form_valid of the UserUpdate view and also in the save method of the form (Not sure where I should make this) This way: def form_valid(self, form): old_image = self.instance.picture.path os.remove(old_image) return super().form_valid(form) I get an error saying 'ImageFileDescriptor' object has no attribute 'path'. Couldn't find anything useful about ImageFileDescriptor. But if I do it in the form like this: def save(self): old_image = self.instance.picture.path os.remove(old_image) The picture I get is the one I'm about to upload in the form. -
How can I pattern match ID only making sure the variable number matches without having to hardcode all of the possibilities?
I've recently become familiar with Jquery selectors....and they work great. Starts with...ends with.... The problem I have currently is that all of my variable names essentially start with similar patterns and end with similar patterns. This ID is generated from somewhere else so I'm hoping I can do something to use it effectively. The pattern ID format essentially looks like... "#id_newbudgetlineitem_set-0-line_item_october" "#id_newbudgetlineitem_set-0-line_item_november" "#id_newbudgetlineitem_set-0-line_item_december" I want to essentially matching on the set-* but only if it's identical to the other ids in my array. Is this even possible without having to hard code anywhere from set-0 to set-1000? Unfortunately the class for each one is the same as is the name situation. Is there someway to say if the set numbers all match in a given array then add them up? I can't use starts with or ends with in this case...and don't want to hardcode 1000 possibilities. Thanks in advance for any ideas or thoughts. -
I have a problem with get billings from paypal
I have a big problem with the webhook for confirms a subscribe agreements. I'm used the SDK [https://github.com/paypal/PayPal-Python-SDK/blob/master/samples/subscription/billing_agreements/get.py] If somebody could help me, my errors is the next: Traceback (most recent call last): File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/django/core/handlers /exception.py", line 34, in inner response = get_response(request) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/jjorge/src/guru/guru-payments/apps/paypal/views.py", line 69, in post settings.PAYPAL_CLIENT_SECRET File "/home/jjorge/src/guru/guru-payments/apps/paypal/services.py", line 34, in execute paypal_secret_id File "/home/jjorge/src/guru/guru-payments/apps/paypal/payment_methods.py", line 154, in get_billing_agreement 'client_secret': paypal_client_secret File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/paypalrestsdk/resource.py", line 110, in find return cls(api.get(url, refresh_token=refresh_token), api=api) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/paypalrestsdk/api.py", line 268, in get return self.request(util.join_url(self.endpoint, action), 'GET', headers=headers or {}, refresh_token=refresh_token) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/paypalrestsdk/api.py", line 171, in request return self.http_call(url, method, data=json.dumps(body), headers=http_headers) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/paypalrestsdk/api.py", line 214, in http_call return self.handle_response(response, response.content.decode('utf-8')) File "/home/jjorge/venvs/payments/lib/python3.7/site-packages/paypalrestsdk/api.py", line 231, in handle_response raise exceptions.ResourceNotFound(response, content) paypalrestsdk.exceptions.ResourceNotFound: Failed. Response status: 404. Response message: Not Found. Error message: {"name":"RESOURCE_NOT_FOUND","debug_id":"9a7aa1a765763","message":"The requested resource was not found","information_link":"https://developer.paypal.com/docs/api/payments.billing-agreements#errors","details":[{"issue":"Requested resource ID was not found."}]}