Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'HttpResponseSeeOther' object has no attribute 'url'
I'm looking to test for a 303 See Other status code when a User attempts to login. Django does not have a built in class to handle this status code, so I constructed a sub class of HttpResponse. from http import HTTPStatus from django.http import HttpResponse class HttpResponseSeeOther(HttpResponse): '''Represents a 303 status code''' status_code = HTTPStatus.SEE_OTHER Next, I constructed a TestCase to test a View's response when it is passed valid form data. However, the test raises this error: AttributeError: 'HttpResponseSeeOther' object has no attribute 'url' . Going over the Django docs, I cannot see any reference to a Response object having an URL attribute. How can I go about addressing this error so that a server returns a 200 OK response after a successful 303 See Other redirect? test_views.py class TestUserLoginPage(TestCase): @classmethod def setUpTestData(cls): User.objects.create_user(username="User", password="password") cls.login_creds = { 'username': 'User', 'password': 'password' } def test_successful_login_redirect(self): response = self.client.post( reverse("login"), data=self.login_creds, follow=True ) self.assertRedirects(response, reverse("photos:main_gallery"), status_code=303) self.assertTemplateUsed(response, "photos/main_gallery.html") views.py class LoginPage(View): def get(self, request): form = UserAuthenticationForm() return render(request, 'login.html', context={'form': form}) def post(self, request): import pdb; pdb.set_trace() form = UserAuthenticationForm(request, request.POST) if form.is_valid(): messages.success(request, f"Welcome {request.user}!") return HttpResponseSeeOther(reverse("photos:main_gallery")) messages.info(request, "Login Failed. Username not registered.") form = UserAuthenticationForm() return … -
How to show OrderItem in Order in Django Admin.py
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'payment', 'coupon' ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] inlines = [ OrderItemAdmin, ] Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, ------------------------------------------------------ status = models.CharField(max_length=50, choices=[('pending', 'Pending'), ('ofd', 'Out For Delivery'), ('recieved', 'Recieved')], default='pending') def __str__(self): return self.user.username -
Django - can I add a form on changelist_view?
I have a model admin with a simple custom change view page, can I add a form on it? class MyModelAdmin(admin.ModelAdmin): change_list_template = 'custom_template.html' def changelist_view(self, request, extra_content=None): # How do I link the form to this view ? # logic of handling data from the form return super(MyModelAdmin, self).changelist_view(request, extra_context=None) -
Django WebSocket Multiple Send
i try realize multiple send in websockets. In synchronous and only 1 to 1 work but if i try send message 1 to many or asynchronous 1 to 1 i don't see notification. Can you help please with code or rewrite this code. I'm not an expert in websockets, but I'm trying to write something. consumers.py class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() else: self.group_name = "user_id_" + str(self.scope["user"].id) for group in self.group_name: self.channel_layer.group_add( group, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.close() async def notify(self, event): await self.send(text_data=json.dumps(event["text"])) notify.py def send_notification(data, user, req_user, email): channel_layer = get_channel_layer() group_name = 'user_id_{0}'.format(user.id) async_to_sync(channel_layer.group_send)(group_name, { "type": "notify", "text": data, }, ) if email: send_mail(subject='Message', message=f"{data}", from_email=req_user.email, recipient_list=[user.email]) notify = Notification.objects.create(sender=req_user, message=data) notify.receivers.add(user) notify.save() Execute function send_notification('notify_text', user=[User.objects.get(username='applicant1'), applicant1 = User.objects.get(username='applicant0')], req_user=user_id,email=False) template <script> var loc = window.location var wsStart = "ws://" if (loc.protocol === "https:"){ wsStart = "wss://" } var webSocketEndpoint = wsStart + loc.host + '/notifications/' // ws : wss // Websocket URL, Same on as mentioned in the routing.py var socket = new WebSocket(webSocketEndpoint) // Creating a new Web Socket Connection // Socket On receive message Functionality socket.onmessage = function(e){ console.log('message', e) $("body").append("<h3>"+e.data+"</h3>") // Can write any … -
Django Filtering Foreign Key Item
I have problem using fk in django. I want to make a fk field that the parent's queryset has been filtered. I have app called user that has costumized User model in model.py class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) phone = models.IntegerField(_('phone number'), unique=True, blank=True, null=True) this User has ManyToMany Relationship with Group queryset: maker, checker, signer >>> print(Group.objects.all()) <QuerySet [<Group: maker>, <Group: checker>, <Group: signer>]> In other app called cleaning I have cln_daily model that has foreignkey relationship with that User model based on their group. class cln_daily(models.Model): . . user_maker = models.ForeignKey(User,verbose_name="Maker's Signature",on_delete=models.CASCADE, related_name="makerSignature", blank=True, null=True,) user_checker = models.ForeignKey(User, verbose_name="Checker's Signature",on_delete=models.CASCADE, related_name="checkerSignature", blank=True, null=True) user_signer = models.ForeignKey(User, verbose_name="Signer's Signature",on_delete=models.CASCADE, related_name="signerSignature", blank=True, null=True) So what I mean is user_maker queryset has users that only belong to group maker. user_checker has users that only belong to group checker and user_signer queryset has users that only belong to group signer. How to express filtered User model in that model.py? -
Use regroup with datetimefield
I want to regroup a queryset in my template : {% regroup events by date as events_group %} {% for event in events_group %} <div class="time-label"> <span class="bg-danger"> {{ event.grouper }} It's works but the "date" is a datetimefield. I want to group my results per day. Today the results are displayed like : 10 Oct 2020 16:59 event1 10 Oct 2020 16:55 event2 10 Oct 2020 16:54 event3 09 Oct 2020 12:59 event4 09 Oct 2020 11:59 event5 I want : 10 Oct 2020 event1 event2 event3 09 Oct 2020 event4 event5 How to do this ? -
convert Django raw sql return into object
my sql Django raw query returns : [ (datetime.date(1998, 10, 8), 'swe', 'tam', 'images/3.jpg', 190, 'female', 1), (datetime.date(2020, 10, 8), 'Sal', 'ws', '1_qvQ9V4k.jpg', 122, 'male', 4) ] I want to convert the below format .how to do that. <QuerySet [<player: Sal>, <player: lee>, <player: swe>, <player: pol>, <player: Pak>, <player: Ask>, <player: sal>]> becuase i want to use it for my custom filter function : myFilter = RankFilter(request.GET, queryset=player_features.objects.all().order_by('-ranking_points')) -
Django Python DetailView not working as expected. I get an issue when I try and view a specific note
Advice required. would someone point me in the right direction? Using Django 3.1.1 with Pycharm Community 2020.2 I'm working with ListView to show all To-Do notes on one page allTasks.html {% extends "app/base.html" %} {% load static %} {% block content %} <body> <div class="section"> <div class="container" id="heading"> <h3>List of all Tasks to-date</h3> </div> <div class="container"> <ul id="taskcontainer"> {% for i in obj %} <li> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ i.name }}</strong> <h6 class="mb-0">{{ i.date }}</h6> <div class="mb-1 text-muted">Team {{ i.team_project }}</div> <p class="card-text mb-auto">{{ i.notes }}</p> <p class="card-text mb-auto">Priority: {{ i.urgency }}</p> <strong class="d-inline-block mb-2 text-danger">Completed? {{ i.completed }}</strong> <span> <a href="{% url 'task-detail' task.id %}" class="link">View</a> <a href="#" class="link">Edit</a> </span> </div> </div> </div> </div> </li> {% endfor %} </ul> </div> </div> </body> From here I go into DetailView to each individual note task_detail.html {% extends "app/base.html" %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ object.name }}</strong> <h6 class="mb-0">{{ object.date }}</h6> <div … -
Object of type QuerySet is not JSON serializable Django with AngularJS
I have a Django project where am using AngularJs as frontend. I have a very simple search where user will search a code and if the code matches from the db table it will show it. Am pretty new with angularjs what i tried is fetching objects as an array. ** my view ** @csrf_exempt def hscodesearch(request): chaptercode = '' hs4code = '' chapter_description = '' chapter_description1 = '' if (request.method == 'POST'): data = json.loads(request.body) s_t = data.get('hs_search') hs_content = { "chaptercode": chaptercode, "chapter_description": chapter_description, "chapter_description1": chapter_description1, "search_test": s_t, "hs4code": hs4code, } result = [hs_content] return HttpResponse(json.dumps({"status": 1, "data": result}), content_type='application/json') my controller.js mainApp.controller('hsController', function($scope, $http, $compile, $timeout, $location) { $scope.data = {}; $scope.init = function() { console.log("angular loaded!") } $scope.data.form = { hs_search: "", result: "", }; $scope.data.formStyle = { hs_search: "" }; $scope.submitForm = function() { //console.log($scope.data.form) var error = 0; if(!$scope.data.form.hs_search) { $scope.data.formStyle.hs_search = "is_invalid"; error++; } else { $scope.data.formStyle.hs_search = ""; } if(error==0) { var jsonCall = $http({ method: 'POST', url:'/theapp/hs-code-search', data: $scope.data.form, headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }); jsonCall.success(function(data, status, headers, config) { if(data.status==1) { $scope.data.form.result = data.data console.log($scope.data.form.result) } }); jsonCall.error(function(data, status, headers, config) { if(data.status==0) { $.growl.error({ message: data.error}); } }); console.log($scope.data.form) } … -
Django rest framework, DELETE request responds with "Method \"GET\" not allowed." to every valid request
Here is my code for DELETE method for a "comment" model (views.py): class CommentDelete(DestroyAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer in urlpatterns it looks like this (urls.py): ... path('delete/', views.CommentDelete.as_view()), ... For some reason when I make a direct DELETE request, the result is "Method \"GET\" not allowed." I'm also using swagger, and it gets even more weird there. There is a DELETE option but it doesn't provide any parameter field even after I've specified it in views.py (lookup_field = 'id'). When I run it, it gives me an expected error: Expected view CommentDelete to be called with a URL keyword argument named "id". -
Nested foreign key serializer with customized response in Django not working
Part of models.py class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) image_name = serializers.CharField(required=False) class Challenge(models.Model): title = models.CharField(max_length= 1000, blank=False) supporting_organization = models.ForeignKey(Supporting_organization, related_name="supporting_organizationId",on_delete=models.CASCADE,blank=True) class Challenge_progressLog_detail (models.Model): challenge = models.ForeignKey(Challenge, related_name="challengeCreationId",on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) longitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) location_address = models.TextField(default='') photo_description = models.TextField(default='') part of serializers.py: class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) class Meta: model = Supporting_organization fields = '__all__' class ChallengeSerializer(serializers.ModelSerializer): supporting_organization = serializers.RelatedField(source='supporting_organizationId', read_only=True) class Meta: model = Challenge fields = '__all__' class Challenge_progressLog_detail_Serializer(serializers.ModelSerializer): challenge = serializers.RelatedField(source='challengeCreationId', read_only=True) class Meta: model = Challenge_progressLog_detail fields = '__all__' I want the Challenge_progressLog_detail_Serializer to return a nested object detail which will havechallenge detail with respective supporting organization. The categorization is straightforward, having a list of challenge progress log detail in the first level, challenge types in the second, and supporting organization items in the third level. Problem is that Challenge_progressLog_detail_Serializer only returns the first and second level only i.e. only the challenge detail is shown. But I want the full nested list of Challenge_progressLog_detail with Challenge Detail, And supporting organization detail items. I used below serializer class in in challenge_progresslog_detail ==> serializer.py file for get customized response in list. Apart from I used rest_framework serializer. class challengeListSerializer(serializers.ModelSerializer): challenge_id = serializers.SerializerMethodField() challenge_title = … -
Git db.sqlite and wsgi.py file keep reverting on pull
I have a python/django/wagtail project that I built locally using db.sqlite3. I did an initial push with everything to github, and then pulled it to my server. I made a change to the wsgi file and did some work in the cms which updated the database. I made some changes locally. I changed my .gitignore to exclude db.sqlite3 and wsgi.py. git add ., git commit, git push origin master. then, on the server, sudo git pull origin master. db.sqlite3 reverts back to before I made the cms changes and the wsgi.py reverts back to pointing to my dev settings. I made the changes back to the cms but now I need to do another update when I have made even more cms changes and I do not want to overwrite the database again. wsgi.py is a small fix but still. My .gitignore # Created by https://www.toptal.com/developers/gitignore/api/django # Edit at https://www.toptal.com/developers/gitignore?templates=django ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 db.sqlite3-journal media wsgi.py # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # <django-project-name>/staticfiles/ ### Django.Python Stack ### # Byte-compiled … -
Crispy form does not work with specific form field and button
I am trying to use crispy-forms but ran into the following two problems. This is the form.py from django import forms from menu.models import Item class TableCheckInForm(forms.Form): guest_count = forms.IntegerField(min_value =0) # item = forms.ModelChoiceField(queryset=Item.objects.all()) item = forms.IntegerField(min_value =0) and the template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Table{% endblock %} {% block content %} <div class="table_order_form"> <h1>Order</h1> <form action="{% url 'table_order_view' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class = "button table_order">PLACE ORDER</button> </form> </div> {% endblock %} And of course in the settings.py, I have declared: crispy_forms and CRISPY_TEMPLATE_PACK = 'bootstrap4' Problem 1: in forms.py, if the field item is a ModelChoiceField (the commented line), the form is out of whack, not "crispy" at all. But if I replace it with a usual form field such as IntegerField, the form is nicely formatted. Problem 2: in the template, I place a button right below the form, but when rendered, the button appears in parallel with the form, to its top right, and out of whack. Looking for some advice. Thanks. -
How to increment inside session in Django?
I try to create a counter inside session but I fail. the session is print out the result I added once and it doesn't increment the process when I want to add a new comment again. the comment will be added but counter is still equal to one so, how can I do increment into session: def post(self, request, user_slug, *args, **kwargs): my_question = UserAsking.objects.get(ask_slug=user_slug) userprof = UserProfile.objects.get(userasking__ask_slug=user_slug) comment_form = CommentForm(request.POST, instance=request.user) name = "%s %s" % (self.request.user.first_name, self.request.user.last_name) username = self.request.user.username logo = self.request.user.userprofile.logo.url if comment_form.is_valid(): comment_request = self.request.POST.get('comment', None) comment_form = Comment.objects.create(comment=comment_request, userasking_id=my_question.id, userprofile_id=userprof.id, name=name, username=username, logo=logo, comment_slug=my_question.ask_slug ) q = UserAsking.objects.get(ask_slug=my_question.ask_slug) c = comment_form u = comment_form.userprofile if 'notify_counts' in request.session: counter = request.session.get('notify_counts', 0) request.session['notify_counts'] = counter + 1 request.session.save() print('%s is commented your post: %s and comment is (%s) notify = %i' %(u, q, c, counter)) return redirect('community:question_view', user_slug) # return redirect('community:question_view', comment_form.userasking.ask_slug) return render(request, 'community/question_view.html', {'comment_form': comment_form}) -
Django - Business users to fill a form that is to be sent as an email
Here is the problem I got. I need non-developers to send occasional marketing emails via the Django admin. Nothing too crazy or customized to justify paying for mailchimp and/or similar services, but more than just plain old text (which is currently working). Markdown formatting will do. I am aware of render_to_strings and using html files. But, that would require either manipulation of those html files by non-developers or doing a lot of them to fit the marketing needs. Currently it's a simple TextField that gets sent as is to the customers. Here is the code. Models from django.db import models from django.conf import settings from django.core.mail import EmailMessage class Subscriber(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Email_update(models.Model): subject = models.CharField(max_length=150) content = models.TextField() -- *Change to Markdownx or something similar?* created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): subscribers = Subscriber.objects.all() email_list = [] for sub in subscribers: email_list.append(sub.email) email = EmailMessage( self.subject, self.content, "email@company", ["email@company.com"], email_list, ) email.send() Admin.py from django.contrib import admin from .models import Subscriber, Email_update # Register your models here. def send_email_update(modeladmin, request, queryset): for email_update in queryset: email_update.send(request) send_email_update.short_description = "Send selected Newsletters to … -
How can solve errors on cookiecutter django?
I tried running django using cookiecutter but while running it there were some errors error message: [2020-10-12 01:18:22,782 basehttp] ERROR: "GET /en/ HTTP/1.1" 500 23209 [2020-10-12 01:18:23,900 basehttp] INFO: "GET /favicon.ico HTTP/1.1" 302 0 [2020-10-12 01:18:23,928 log] WARNING: Not Found: /en/favicon.ico/ [2020-10-12 01:18:23,928 basehttp] WARNING: "GET /en/favicon.ico/ HTTP/1.1" 404 1335 -
DRF, read/write permission for own profile
There is a write problem about own profile. I arrange some permissions and now super user can read and write all profiles. No problem at this part. But when it comes to normal user, I give a permission that user can only read it's own profile and write it also... Read part is working, but not write part. Here is part of my code. permissons.py from rest_framework import permissions class IsSuperUser(permissions.BasePermission): def has_permission(self, request, view): return request.user and request.user.is_superuser class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: if request.user.is_superuser: return True else: return obj == request.user else: return False views.py class ProfileViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = ProfileSerializer def get_permissions(self): # not very sure how to handle get permissions function. # if I try [IsSuperUser, IsOwner] it's not quite working. self.permission_classes = [IsSuperUser] # # I pass the IsOwner in condition, but ofcourse then it can't write # it's own profile only read if self.action == 'retrieve': self.permission_classes = [IsOwner] return super(self.__class__, self).get_permissions() How to arrange that user can read/write it's own profile? -
How to control the format of a duration field in django
I am making a simple clock in app. You push a button to punch in, and push it to punch out. I am trying to display the hours/mins between the out-punch and the in-punch. The code works, but I would like to change the output of the code. The output I am getting is something like this: I am pretty new to django and python in general, and would like to know how I can make this output something better, maybe like x:hours y:minutes or something like that. I definitely do not need the milliseconds. For clarity, the code is as follows: The model for the process is: class Punch(models.Model): employee = models.ForeignKey("timekeeper.User", on_delete=models.CASCADE, related_name="employee_punch") punchDate = models.DateField(default='2020-01-01') punchInTime = models.TimeField(default='01:01:01') punchOutTime = models.TimeField(null=True) worked = models.DurationField(null=True) def __str__(self): return f"Emp: {self.employee}, Timestamp: {self.punchDate}, IN: {self.punchInTime}, OUT:{self.punchOutTime} -- Worked: {self.worked}" The view code is: # Create your views here. def index(request): # The punch button was pushed if request.method == 'POST': r = request.POST.get('punch_button') # Record the punch on the Punch table if r == "PUNCH IN": Punch.objects.create( employee=request.user, punchInTime=datetime.now().time(), punchDate=datetime.now().date() ) elif r == "PUNCH OUT": now = datetime.now() p = Punch.objects.filter(employee=request.user, punchDate=now.date()).last() p.punchOutTime=now.time() # Converting punch times to … -
Django TypeError: Field 'id' expected a number but got <homeworkForm bound=True, valid=Unknown, fields=(title;descripiton;due)>
I have been trying to allow staff users to post homework to a database however I keep running into the issue above. I've tried setting data['id'] = 0/'' as well as dropped the table and makemigrations/migrate. models.py from django.db import models from teachers.models import Teacher class Homework(models.Model): title = models.CharField(max_length=100) descripiton = models.CharField(max_length=500) due = models.DateField() teacher = models.OneToOneField( Teacher, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.title form.py from django import forms class DateInput(forms.DateInput): input_type = 'date' class HomeworkForm(forms.Form): title = forms.CharField(label='Title', max_length=100) descripiton = forms.CharField(label='Descripiton', max_length=500) due = forms.DateField(label='Due', widget=DateInput) views.py def homework(request): if request.user.is_authenticated & request.user.is_staff: if request.method == 'POST': data = request.POST.copy() data['teacher'] = request.user.username request.POST = data print(request.POST) form = HomeworkForm(request.POST) if form.is_valid(): post = Homework(form) post.save() messages.info(request, 'Form sent') print('worked') return render(request, 'index/index.html') else: print('error in form') form = HomeworkForm() return render(request, 'dashboard/setHomework.html', {'form': form}) else: form = HomeworkForm() return render(request, 'dashboard/setHomework.html', {'form': form}) else: return redirect('index') -
Django contenttype : Is it possible to create generic relation dynamically without explicitly defining GenericRelation(X) in a model?
Say if we want to define generic relation from Bookmart to TaggedItem, we would define in the model as follow: class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(TaggedItem) and if we want more than one generic relations to models. we would have to explicitly define multiple GenericRelation(x) statements. I was reading Django permissions documentation and stumble upon this code: content_type = ContentType.objects.get_for_model(BlogPost) permission = Permission.objects.create( codename='can_publish', name='Can Publish Posts', content_type=content_type ) As far as I see from the docs, BlogPost doesn't explicitly specify its generic relation(s). How is it doing it? -
Django, ERP/CMS software and E-commerce site on different servers
hope someone can help me with this. I am new to python and django, but already took some tutorials on how to create your own ERP/CMS and eCommerce projects on Django. My questions are... or what I want to do is: I want to install the ERP/CMS in my own local server (also it's gonna be the admin part for the eCommerce site) Install the eCommerce site on a Webhosting server Suppose that you have a business and you manage your operation with the ERP/CMS (inventory, employee, invoicing, etc) software created on Django. Then you realize that you want to create a website and sell online. So you create your eCommerce site on Django and deploy it in your preferred Webhosting. Questions: Considerations: Have to be in 2 separate servers and database For security reasons, both databases can not see each other or have any relation between them. In a situation your site gets hack, your primary database(ERP/CMS) will not be compromised. On the eCommerce site, the info the will be upload are Category, subcategory, products(description, attributes, availability[quatity > 0]), image, selling price, client, address. I know that Django can handle multiple databases. What will be the easiest and efficient … -
When I am writing the URL in browser the URL is not working- only the admin page is ascessed . Please show me a path
The name of my project is firstproject and web application is testapp. I am attaching urls.py , views.py and installed apps ` `` from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('hello/',views.greeting), path('admin/', admin.site.urls), ] from django.shortcuts import render from django.http import HttpResponse def greeting(request): s="<h1> hello this is greeting page</h1>" return HttpResponse(s) INSTALLED_APPS = [ 'testapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
_wrapped() missing 1 required positional argument: 'request': Issue with method decorator. (Django, Ratelimit Library)
I am attempting to use a method decorator so I can apply a decorator to the get_queryset method. My main goal is to limit the number of GET requests per minute to avoid query spam. Although, the problem is the decorator keeps throwing an error as written in the title. I've tried switching the order of and adding the self and request parameters, but so far no luck. Thanks! Ratelimit Library: https://django-ratelimit.readthedocs.io/en/stable/usage.html (Ctrl-F to class-based views section.) class ConnectMe(ListView, LoginRequiredMixin): model = Profile template_name = 'users/connect_me.html' context_object_name = 'profiles' paginate_by = 10 @method_decorator(ratelimit(key='ip', rate='1/m', method='GET')) def get_queryset(self): # original qs qs = super().get_queryset() .... -
Django Rest Framework & React Js ( Axios API Request ): After Incorrect authentication attempt, api returns 400
I'm creating a login system and basically, I have two inputs, one for username and the other for password. So when the user enters the correct credentials the API returns 200 response with some data but after incorrect credentials the django-rest-framework marks the request as 400 Bad Request and returns the response with 400 status code and no data, but this happens only when I'm sending a request from react js, after trying bad credentials from postman, the API returns: { "non_field_errors": [ "Incorrect credentials" ] } My Axios code: axios.post('http://192.168.0.29:8000/api/auth/login', { headers: { 'Content-Type': 'application/json' }, username: username, password: password }) .then((response) => { console.log(response.data); }) .catch(err => { console.log(err.data) alert('zjbs eroras') }); } -
What is the difference between the __lte and __gte in Django?
I am trying to figure out the difference between the __lte and __gte in Django. The reason being that I am trying to create a function with dates that can work only with a time frame, so I've been researching between Field Lookups Comparison. I've looked up several documentations https://docs.djangoproject.com/en/3.0/ref/models/querysets/#exclude but didn't reach a conclusive answer.