Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare values with each other and color the difference red
I have a django application. And I try to mark the difference of both the values red. So I have this to functions: pdf data: from django.utils.safestring import mark_safe from tabulate import tabulate class FilterText: def show_extracted_data_from_file(self): def show_extracted_data_from_file(self): verdi_cost = [3588.20, 5018.75,3488.16] regexes = [verdi_cost] matches = [(regex) for regex in regexes] columns = ["kosten fruit"] return mark_safe( tabulate( zip_longest(*matches), # type: ignore headers=columns, tablefmt="html", stralign="center", ) ) excel data: from django.utils.safestring import mark_safe from tabulate import tabulate class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): dict_fruit = {"Watermeloen": 3588.20, "Appel": 5018.75, "Sinaasappel": 3488.16} columns = ["naam fruit", "totaal kosten fruit"] return mark_safe( tabulate( dict_fruit.items(), headers=columns, tablefmt="html", stralign="center" ) ) So I want to compare the values from the excel data and the values from the pdf data. and the views.py: def test(request): filter_excel = ExtractingTextFromExcel() filter_text = FilterText() content_excel = "" content_pdf = "" content_pdf = filter_text.show_extracted_data_from_file() # type:ignore content_excel = filter_excel.extract_data_excel_combined() context = {"content_pdf": content_pdf, "content_excel": content_excel} for ((fruit, a), b) in zip(content_excel, content_pdf): if (a, b): return fruit return render(request, "main/test.html", context) and the template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% … -
View admin page if the log in user is admin in Django
I am doing a Django project. If the user is admin, then the admin will view the admin-profile page after logging in. But if the user is researcher, then the researcher can view the researcher-profile page after logging in. django_project/settings.py LOGIN_REDIRECT_URL = 'researcher-profile' blog/views.py from django.shortcuts import render from .models import Post, Category from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PostForm # get all posts of the logged in user class UserPostListView(LoginRequiredMixin, ListView): model = Post # query the post model to create the list of articles template_name = 'blog/researcher-profile.html' context_object_name = 'posts' ordering = ['-created'] def get_queryset(self): return Post.objects.filter(author = self.request.user) researcher-profile.html {% extends 'users/base.html' %} {% block content %} {% for post in posts %} {% if post.approved %} <div class="card mb-3"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title|truncatechars:70 }}</h5> <p class="card-text">{{ post.content|truncatechars:200|safe }}</p> <a href="{% url 'post-detail' post.aid %}" class="btn btn-primary"> See Details </a> </div> <div class="card-footer text-secondary"> <a class="mr-2" href="{% url 'researcher-profile' %}">{{ post.author }}</a>|| {{ post.created|date:"F d, Y" }} </div> </div> {% endif %} {% endfor %} {% endblock content %} admin-profile.html {% extends 'users/base.html' %} {% block content %} <h1> Admin Post Apporval Portal</h1> … -
I want to add flag field to users in User model(inbuilt) to manage account as active and deactivate in django
J want to change users flag field to disable,how to manage user profiles by flag field. Adding flag field by Boolean and manage accounts as active state and de activated state. -
Django, Nginx, and Docker. DEPLOYMENT
I want to deploy my app which is made by django and flutter and i have used docker to dockerize the django and the nginx. Here what i has so far and what should i add or change: docker-compose.yaml: version: '3.8' services: api: build: context: ./api command: gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 volumes: - ./api:/app/ - static:/app/static/ expose: - 8000 depends_on: - db db: image: postgres:latest volumes: - data:/var/lib/postgresql/data/ server: build: context: ./server volumes: - static:/app/static/ - media:/app/media/ - certs:/etc/nginx/certs ports: - 443:443 - 80:80 certbot: image: certbot/certbot depends_on: - api volumes: data: static: media: certs: dockerfile (django): FROM python:latest ENV SECRET_KEY 123 ENV DATABASE_PASSWORD postgres ENV DEBUG 0 RUN mkdir /app WORKDIR /app COPY . . RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py collectstatic --no-input dockerfile (nginx): FROM nginx:latest RUN mkdir /server RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/conf.d/ WORKDIR /server nginx.conf: server { listen 80; server_name mydomain.com return 301 https://$server_name$request_uri; location / { proxy_pass http://server; } location /static/ { alias /server/static/; } } server { listen 443 ssl; server_name mydomain.com; } Thanks for your time I have tried searching online but i couldn't find much answers -
How to change the size of UserCreationForm?
I wanna modify the weight of the fields in UserCreationForm. How ist that possibly? class SignUpForm(UserCreationForm): username = forms.CharField( widget=forms.TextInput(attrs={ "class": "input", "type": "text", "placeholder": "Username", }) ) email = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "email", "placeholder": "Email" })) password1 = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "password", "placeholder": "Password" })) password2 = forms.CharField(widget=forms.TextInput(attrs={ "class": "input", "type": "password", "placeholder": "Password" })) class Meta: model= User fields = [ "username", "email", "password1", "password2" ] I wanna modfy the size of the fields: Username, Email, Password1 and Password2 More precisely, I want the fields longer -
How to Optimize a loop "For" in Django
I want to optimize this functions, because they take too long, each of them bring specific atributes, if you can help me. I think there's maybe a way to call the atributes in the function. The functions are made with python and Django. This is what i've done so far. Definition of the functions. cand_seleccionados = ListaFinal.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) seleccionados_ids = cand_seleccionados.values_list('interesado_id', flat=True) cand_postulados = Postulados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=seleccionados_ids) postulados_ids = cand_postulados.values_list('interesado_id', flat=True) cand_entrevistados = Entrevistados.objects \ .filter(interesado__id_oferta=efectiva.oferta.id) \ .exclude(interesado_id__in=postulados_ids) This is the loop for cand_Postulados, the others are the same so i thought it wouldnt be necesary to put more for p in cand_postulados: postulado = dict() telefono = Perfil.objects \ .values_list('telefono', flat=True) \ .get(user_id=p.interesado.candidato.id) postulado['id'] = p.interesado.candidato.id postulado['nombre'] = p.interesado.candidato.first_name postulado['email'] = p.interesado.candidato.email postulado['teléfono'] = telefono if p.interesado.id_oferta.pais is None: postulado['pais'] = "Sin pais registrado" else: postulado['pais'] = p.interesado.id_oferta.pais.nombre postulado['nombre_reclutador'] = p.interesado.id_reclutador.first_name postulado['id_reclutador'] = p.interesado.id_reclutador.id postulados.append(postulado) -
Deploying Django Postgres to Digital Ocean Droplets
I have to deploy a Django API to Digital Ocean, a service that should scale a bit over the next year. I also need a database to save all the data from the users, and I will use Postgres. Recently I saw a lot of video tutorials, official guides from the digital ocean and so on that tell us to use the Postgres that you install on the Droplets "locally" as the database, so install locally postgres and put there all the data. It actually can make sense since the droplet I will pay for is about 25 GB that I will never really reach. So, my question was if this approach makes sense at all, or is way better to set up right now a different possibility, like a database on the digital ocean itself? If I keep these settings, will I be able to easily migrate in the future? Or will it be painful if not impossible? Is there a very good cost-efficient way to do this, or this solution is good enough even for a platform that needs to scale (let's say 100,000 users and a really high amount of requests for each one of them at … -
How to add email to be able to log in via Google oauth Django
I'm building a Django project and I have 3 applications. Students log in to complete the given items. Teachers log in to manage the list of student actions. Administrators manage permissions and logins. Administrators will add student and teacher email addresses. to check that only the added email will be able to log in and my project is using only google oauth login, can anyone guide me what i need to do? If you want an admin to add an email address And only the added email will be able to login. what i tried views.py def admin_user_setting(req): if req.method == "POST": email_user = req.POST.get('email_user') obj = Add_User_Email_User(email_user=email_user) obj.save() return redirect('/admin_user_setting') else: obj = Add_User_Email_User() obj = Add_User_Email_User.objects.all() AllUser = Add_User_Email_User.objects.all() page_num = req.GET.get('page', 1) p = Paginator(AllUser, 10) try: page = p.page(page_num) except: page = p.page(1) context = { "AllUser": Add_User_Email_User.objects.all(), "page" : page, } return render(req, 'pages/admin_user_setting.html', context) urls.py urlpatterns = [ path('admin_user_setting',views.admin_user_setting, name="admin_user_setting"), ] forms.py class UserForm(ModelForm): class Meta: model = Add_User_Email_User fields = ['email_user'] admin.py admin.site.register(Add_User_Email_User) models.py class Add_User_Email_User(models.Model): email_user = models.CharField(max_length=500, null=True) def __str__(self): return self.email_user -
I want to make a subscription system with django
How can I make an auto incrementing timer, for example, it will count forward 1 year from now and these transactions will be saved in the database. -
How to check django login status in JavaScript?
What is the best way to check django user is authenticated in JavaScript file? -
How to implement recursive in Django Serializers
My serializers class class ConditionSerializers(serializers.ModelSerializer): class Meta: model = TblCondition fields = ['id','operator','condition','relation'] class ConditionSerializers(serializers.ModelSerializer): relation_with=ConditionSerializers(many=False) class Meta: model = TblCondition fields = ['id','operator','relation_with','condition','relation'] class RuleSerializers(serializers.ModelSerializer): conditiontbl=ConditionSerializers(many=True) class Meta: model = TblRule fields = ['rule_table_no','rule_no','rule_name','columns','data_file','true','conditiontbl' ] My model class class TblRule(models.Model): rule_table_no=models.AutoField(primary_key=True) rule_no=models.IntegerField(blank=False) rule_name=models.CharField(max_length=100,blank=False) columns=models.CharField(max_length=100) data_file=models.CharField(max_length=100) true=models.CharField(max_length=100) class TblCondition(models.Model): rule=models.ForeignKey(TblRule, on_delete=models.CASCADE,related_name='conditiontbl') operator=models.CharField(max_length=100) condition=models.CharField(max_length=100) relation=models.CharField(max_length=50,blank=True) relation_with=models.OneToOneField(to='self',null=True,blank=True,on_delete=models.CASCADE) Getting these results in postman API by calling ruletbl models [ { "rule_table_no": 2, "rule_no": 1, "rule_name": "Age Discritization", "columns": "Age", "data_file": "Data1", "true": "Teen", "conditiontbl": [ { "id": 4, "operator": ">", "relation_with": null, "condition": "15", "relation": "" }, { "id": 5, "operator": "<=", "relation_with": { "id": 4, "operator": ">", "condition": "15", "relation": "" }, "condition": "25", "relation": "and" } ] }, { "rule_table_no": 3, "rule_no": 1, "rule_name": "Age Discritization", "columns": "Age", "data_file": "Data1", "true": "Young", "conditiontbl": [] } ] You can see conditiontbl list fileds in ruletbl model (e.g. in JASON results), inside conditiontbl filed we have objects of tblcondition models with fileds ("relation_with"), and this relation_with filed is again refering to its own tblcondition model you can see its second object. I want this refering in relation_with fileds to its own conditiontbl model to be recursive. Any solution ? -
Prevent form from resubmitting after button click
I have a Django project where I have a few forms. What is happening is when I click button submit 30 times, my data is inserted 30 times in the database. I did my research and I saw lots of jquery or javascript solutions in general but I am not familiar much with them so I am trying to find a more pythonic/django solution. Here is my code: views: @method_decorator(login_required(login_url='index', redirect_field_name=None), name='dispatch') class CreatePostView(views.FormView): model = Post form_class = CreatePostForm template_name = 'posts/create_post.html' def form_valid(self, form): post = form.save(commit=False) post.user = self.request.user post.save() return redirect('index') template: <form action="{% url 'create post' %}" method="POST" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <p> <button type="submit" class="btn btn-secondary">Submit</button> </p> </form> model: class Post(models.Model): MAX_TITLE_LENGTH = 20 MIN_TITLE_LENGTH = 3 MAX_DESTINATION_LENGTH = 30 MIN_DESTINATION_LENGTH = 3 MAX_DESCRIPTION_LENGTH = 550 MIN_DESCRIPTION_LENGTH = 5 title = models.CharField( max_length=MAX_TITLE_LENGTH, validators=(MinLengthValidator(MIN_TITLE_LENGTH), name_and_title_validator), error_messages={ 'max_length': f'Post title must be a maximum of {MAX_TITLE_LENGTH} characters.', 'min_length': f'Post title must be at least {MIN_TITLE_LENGTH} characters long.', }, null=False, blank=False, ) photo = CloudinaryField( folder='mediafiles/post_photos', public_id=get_photo_name_by_post_name, null=False, blank=False, ) destination = models.CharField( max_length=MAX_DESTINATION_LENGTH, validators=(MinLengthValidator(MIN_DESTINATION_LENGTH), ), error_messages={ 'max_length': f'Destination must be a maximum of {MAX_DESTINATION_LENGTH} characters.', 'min_length': f'Destination must be at least {MIN_DESTINATION_LENGTH} … -
using tabula with excel data with Django
I have a django application. And I try to format data from excel, But I get this error: Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 1) So I have this function: class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): dict_fruit = {"Watermeloen": 3588.20, "Appel": 5018.75, "Sinaasappel": 3488.16} # calculate_total_fruit = self.calulate_total_fruit_NorthMidSouth() columns = ["naam fruit", "totaal kosten fruit"] print("\n".join(f"{a} {b:.2f}" for a, b in dict_fruit.items())) return "\n".join( f"{a} {b:.2f}" for a, b in mark_safe( tabulate( dict_fruit.items(), headers=columns, tablefmt="html", stralign="center", ) ) ) then views.py: def test(request): filter_excel = ExtractingTextFromExcel() content_excel = "" content_excel = filter_excel.extract_data_excel_combined() context = {"content_excel": content_excel} return render(request, "main/test.html", context) and template: <div class="form-outline"> <div class="form-group"> <div class="wishlist"> {{ content_excel }} </div> </div> </div> question: how to format data from excel correct with tabula? -
How to simulate a Field storing only hours and minutes in Django
I would like to store for a model "House", in django, a field stocking an hour and a minute, and to be able to edit it easily by only editing hour and minute. I am aware that TimeField exists in django, but its editing in Django admin is not so great : You have to set your value like this : 10:59:00 (for 10:59am) I would like to be able to get a line with : Hour [...] Minute [...] to be able to input two numbers (with validators so that the hour has to be between 0-23 and minutes between 0-59). My best idea at this point was to make a OnetoOneField in the "House" model to an "Hour" Model which get two IntegerField (And using validators). It works great, but the downside is that while editing an instance of House in admin, i can see the Hour instances linked to other instances of House. For exemple if i have two "House" instances, House1 and House2, when i edit House2, i can see the Hour instance linked to House1 in the scrolling menu. (Problem that i would not get if i had directly two IntegerField in "House" for exemple). … -
Getting query length with Ajax / Django
According to the selection in the form, I want to get the number of records that match the id of the selected data as an integer. Here is my view : def loadRelationalForm(request): main_task_id = request.GET.get('main_task_id') relational_tasks = TaskTypeRelations.objects.filter(main_task_type_id = main_task_id) data_len = len(relational_tasks) return JsonResponse({'data': data_len}) Here is my ajax : <script> $("#id_user_task-0-task_types_id").change(function () { const url = $("#usertask-form").attr("data-relationalform-url"); const mainTaskId = $(this).val(); $.ajax({ url: url, data: { 'main_task_id': mainTaskId, }, success: function (resp) { console.log(resp.data); } }); }); I want to write the number of relational tasks associated with the main_task_id of the selected data in the form. But I couldn't do it. Thanks for your help. Kind regards -
ModuleNotFoundError: No module named 'myapp.urls'
I tried to change setting to below but doesn't work: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp'] my directory: manage.py django_project __init__.py asgi.py settings.py urls.py wsgi.py myapp migration __init__.py admin.py apps.py models.py tests.py urls.py views.py it keeps showing ModuleNotFoundError: No module named 'myapp.urls' views.py from myapp: from django.shortcuts import render, Httpresponse def index(request): HttpResponse('Welcome!') urls.py from myapp: from django.urls import path urlpatterns = [ path('', views.index ), path('create/', views.index) path('read/1/', views.index) ] urls.py from django_project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] Thank you! -
Django dynamic localization not working as expected on mobile devices
I have question about show current language on mobile devices if I populate my language list in template dynamically (got from languages array from settings)... So, this code working properly: <a href="#" id="language-en" class="pure-drawer-link{% if LANGUAGE_CODE == 'en' %} active{% endif %}"> EN </a> BUT, when I'm trying this code, I can't achive that active class added to current language: {% for lng in settings.LANGUAGES %} {% if not lng.0 == "ru" %} <a href="#" id="language-{{ lng.0 }}" class="pure-drawer-link{% if LANGUAGE_CODE == '{{ lng.0 }}' %} active{% endif %}"> {{ lng.0|upper }} </a> {% if LANGUAGE_CODE == '{{ lng.0 }}' %} active {% else %} nonactive{% endif %} => this always return nonactive {% endif %} {% endfor %} Can anyone help to understood why this is happening? -
Displaying one field of a django form based on another field
I'm new to django and I've been using it for only 3 months. I have some groups named sprint 1, sprint 2 etc. Every group has a specific user set. What I want to acquire is when a sprint group is selected the user set associated with that sprint group should be shown below so that I could pick an user from the options. forms.py file class BugForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.Select(),initial="Pending", disabled=True) platform = forms.ChoiceField(choices = platform_choice, widget= forms.Select()) phn_number = PhoneNumberField() screeenshot = forms.ImageField() assigned_to = ?? class Meta: model = Bug fields = ['name', 'info','platform' ,'status', 'assign_sprint', 'phn_number', 'screeenshot'] widgets = {'assign_sprint': forms.Select()} views.py file class BugUpload(LoginRequiredMixin, generic.CreateView): login_url = 'Login' model = Bug form_class = BugForm template_name = 'upload.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.uploaded_by = self.request.user inst = form.save(commit=True) message = f"Bug created. Bug id:{inst.bug_id}" messages.add_message(self.request, messages.SUCCESS, message) return super().form_valid(form) models.py file class Bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") assign_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='assigned', blank= True, null= True) assign_sprint = models.ForeignKey(Sprint, on_delete= models.CASCADE) phn_number = PhoneNumberField() uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name='user_name') created_at = models.DateTimeField(auto_now_add= … -
Ajax With Django Not Reload Page But Loop will reload
<div class="container" id="cd"> <div class="row"> <div class="col-2"> <label for="serialno" class="h4 text-center mx-4"> S.No </label> </div> <div class="col-3"> <label for="billno" class="h4 text-center"> Bill No</label> </div> <div class="col-5"> <label for="Items" class="h4 text-center"> Items</label> </div> <div class="col-2"> <label for="total" class="h4 text-center"> Total</label> </div> <hr> </div> {% for b,d in history.items %} <div class="row" id="refresh"> <div class="col-2 py-2"> <label class="h6">{{forloop.counter}}. | {{b.created_at}}</label> </div> <div class="col-3 py-2"> <label class="h5">{{b}}</label> </div> <div class="col-5 py-2"> {% for i in d %} <label class="h6">{{i.itemname}} x {{i.qty}} {{i.subtotal}}</label><br> {% endfor %} </div> <div class="col-2 py-2"> <span class="h6">&#8377;</span> <label class="h6">{{b.grandtotal}}</label> </div> </div> {% endfor %} </div> <script> $(document).on('change','#myform',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'history' %}", data:{ tb1:$('#cal').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(response){ }, }); }); </script> How Can I reload this {% for b,d in history.items() %} without refresh a page using ajax Any way to change history value using ajax Important Note value processed by onchange event I am trying to reload the loop without a page reload I want to change the history.items() django variable value after the ajax call and corressponding values can be iterated -
How can I render html which extends 'admin/change_list.html'?
I have a requirement where I take CSV file upload and make validations on it before persisting it to the DB. My admin page looks like this: I added this Upload With CSV button. When I click on this, I get to a page which looks like this. Here, I want to redirect back to admin changelist page and notify user that he/she added objects successfully, like this. However, currently my code does not render as I want it to. My code is as follows: def upload_csv(self, request): form = CsvImportForm() data = {"form": form} if csv_file := request.FILES.get("csv_upload"): csv_data = read_csv(csv_file) serializer = CampaignProductCSVUploadSerializer(data=csv_data, many=True) try: with transaction.atomic(): serializer.is_valid(raise_exception=True) old_campaign_id = serializer.return_previous_campaign_id() processed: List[CampaignProduct] = [] for row in csv_data: code = row.get("code") if code is None or not isinstance(code, str) or code.strip() == "": raise serializers.ValidationError(gettext_lazy("Each CampaignProduct object needs to have " "a code.")) obj, *_ = CampaignProduct.objects.update_or_create( code=row["code"], campaign_id=row["campaign"], defaults={ "name": row["name"], "type": row["type"], "is_active": True } ) processed.append(obj.id) CampaignProduct.objects.exclude(id__in=processed).filter(campaign_id=old_campaign_id).update( is_active=False) except Exception as e: raise e return render(request, "admin/csv_upload_success.html", data) return render(request, "admin/csv_upload.html", data) The csv_upload_success.html looks like this: But when I upload the CSV file, I get error as follows: Why can't I just render … -
Connecting a user's MongoDB account to store their data
I'm a beginner, so I'm sorry if this sounds dumb but I want to make a website using django and React where I want to store sensitive information about a user. I want the user to be the only one who can see/access the data entered by them, I do not want to store everyone's data on a MongoDB account made by me. Is it possible to link a MongoDB account specified by the user so that their data is saved into their private MongoDB account? Complete privacy is the goal here. How else can I go about this problem? I tried to look for connecting multiple MongoDB accounts but I didn't find anything related to what I'm looking for. I might have been looking in the wrong direction. Would really appreciate any help! -
Matching query does not exist (Django)
I created a forum website. When pressing on a user profile i get and error in console that library.models.SiteUser.DoesNotExist: SiteUser matching query does not exist. And in the browser it also displays: DoesNotExist at /profile/1/ SiteUser matching query does not exist. Browser highlights this line userprof = SiteUser.objects.get(id=pk) This is my views.py: def userProfile(request, pk): user = User.objects.get(id=pk) **userprof = SiteUser.objects.get(id=pk)** posts = user.post_set.all() post_comments = user.comment_set.all() interests = Interest.objects.all() context = { 'user': user, 'userprof': userprof, 'posts': posts, 'post_comments': post_comments, 'interests': interests } return render(request, 'library/profile.html', context) models.py: class SiteUser(models.Model): page_user = models.OneToOneField(User, on_delete=models.CASCADE) about = HTMLField() profile_pic = models.ImageField('profile_pic', upload_to='covers', null=True) Any help would be greatly appreciated. -
Unable to process Paytm in django rest framework
Im trying to integrate paytm with django rest framework. But don't know why I get checksum mismatch. That is while initiating payment app a checksum is generated but when verifying the checksum it is different. #Views - initiating payment context = { "MID": settings.PAYTM_MERCHANT_ID, "INDUSTRY_TYPE_ID": settings.PAYTM_INDUSTRY_TYPE_ID, "WEBSITE": settings.PAYTM_WEBSITE, "CHANNEL_ID": settings.PAYTM_CHANNEL_ID, "CALLBACK_URL": settings.PAYTM_CALLBACK_URL, "ORDER_ID": str(order.order_number), "TXN_AMOUNT": str(amount), "CUST_ID": str(user.id), } context["CHECKSUMHASH"] = Checksum.generate_checksum( context, settings.PAYTM_MERCHANT_KEY ) return Response({"context": context}) After initiating it Iam sending the CHECKSUMHASH in post request along with MID, ORDERID through postman and check for the checksum validation def VerifyPaytmResponse(response): response_dict = dict() print('in VerifyPaytmResponse 0') if response.method == "POST": data_dict = dict() form = response.POST for key in form.keys(): data_dict[key] = form[key] print('ENTERING HERER') if key == 'CHECKSUMHASH': check_sum = data_dict[key] MID = data_dict['MID'] ORDERID = data_dict['ORDERID'] verify = Checksum.verify_checksum( data_dict, settings.PAYTM_MERCHANT_KEY, check_sum) if verify: STATUS_URL = settings.PAYTM_TRANSACTION_STATUS_URL headers = { 'Content-Type': 'application/json', } data = '{"MID":"%s","ORDERID":"%s"}' % (MID, ORDERID) check_resp = requests.post( STATUS_URL, data=data, headers=headers).json() if check_resp['STATUS'] == 'TXN_SUCCESS': response_dict['verified'] = True response_dict['paytm'] = check_resp return (response_dict) else: response_dict['verified'] = False response_dict['paytm'] = check_resp return (response_dict) else: response_dict['verified'] = False return (response_dict) response_dict['verified'] = False return response_dict This is getting failed because the function to verify … -
how to Subscriber system with django
I want to add an is_subscriber field in django using django ready-made user library Where do I need to add this is_subscriber field? Or how else can I do -
LookupError: No installed app with label 'salesforce'. Did you mean 'salesforce_db'?
After upgrading from Django 2.2 to 3.2 the django-salesforce APP is throwing this error when trying to run my django app Traceback (most recent call last): File "...lib/python3.7/site-packages/django/apps/registry.py", line 156, in get_app_config return self.app_configs[app_label] KeyError: 'salesforce' . . . During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "...lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "...lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "...lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File ".../lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File ".../audit/apps.py", line 18, in ready self.init_auditlog() File ".../audit/apps.py", line 47, in init_auditlog auto_register(all_apps) File ".../audit/utilities.py", line 30, in auto_register app_models = apps.get_app_config(app_name).models File "...lib/python3.7/site-packages/django/apps/registry.py", line 167, in get_app_config raise LookupError(message) LookupError: No installed app with label 'salesforce'. Did you mean 'salesforce_db'? The django-salesforce version is 3.2 salesforce is in INSTALLED_APP, double and triple checked. No syntax errors in model files.