Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Split received payment and send other account Paypal
ABC company charges money from the customer for the supplier and takes 1% commission and rest of the money goes to the supplier bank, what is the best gateway to achieve this milstone? Clearly define a detail and we need to be integrated with python django Currently i was working on paypal for this, but paypal payout api doesn't response well -
Creating a log in view page with Django?
I'm trying to create a login view page to go throuhg the process of authenticating and logging in a user without mixins or decorators. I have the following code: urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('accounts/login/', views.login_view, name="login"), views.py: def login_view(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: # login(request, user) return HttpResponse("logged in!") else: return HttpResponse("invalid credentials") return render(request, 'registration/login.html') templates/registration/login.html: {% block content %} <h1>Log in!</h1> <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login"> </form> {% endblock %} When I try to access the accounts/login page my table doesn't show up unfortuantely. What am I doing wrong here? -
How to use django variable in Javascript? [duplicate]
I'm trying to associate a button with a dynamic url with the following javascript: <script type="text/javascript"> var name = {{pp.name}}; var url = "{% url 'editproject' %}"; document.getElementById("myButton").onclick = function () { location.href = url + "/" + name }; </script> But I am getting an error when I try to click on the button. pp.name is a django variable that would return the name of the project, and the url I'm trying to access is path('editproject/<str:name>/', p.update, name="editproject"), -
I'm not receiving the password reset email link when I click on the Reset password in my Blogging Web App built using Django Framework
I'm not receiving the password reset email link when I click on the Reset password in my Blogging Web App built using Django Framework, although the info "An email has been sent with instructions to reset your password." is prompted as well. I'm guessing something with my setting USER_HOST_EMAIL and USER_HOST_PASSWORD in the environment variables. The settings.py in my Django setup looks like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') Any ideas on what could possibly be the problem? -
404 Error in Django Deployment with Cpanel
I have recently deployed my django application to my Linux CPanel-Shared hosting. After testing all works very well in development but soon after deploying, my application displays 404 Not Found pages every time a user tries to navigate to a URL (including the in-built Django Admin panel). Here is my deployment website: https://covid19.africansurveyors.net I contacted my hosting service provider to check for me where the problem could be but unfortunately it was not resolved as they mentioned about code error. So I then took my application to Heroku and managed to deploy. The URL to the Heroku App which is still the same app is: https://covid19zwe.herokuapp.com/. The application works perfectly fine on Heroku, but fails to run well on CPanel Shared hosting. I also checked the --tail of my server log files this is what came up. App 2247037 output: wsgi = imp.load_source('wsgi', 'passenger_wsgi.py') App 2247037 output: File "/home/<my_username>/virtualenv/public_html/covid19.africansurveyors.net/3.7/lib64/python3.7/imp.py", line 169, in load_source App 2247037 output: App 2247037 output: module = _exec(spec, sys.modules[name]) App 2247037 output: File "<frozen importlib._bootstrap>", line 623, in _exec App 2247037 output: File "<frozen importlib._bootstrap>", line 568, in _init_module_attrs App 2247037 output: File "<frozen importlib._bootstrap>", line 409, in cached App 2247037 output: File "<frozen importlib._bootstrap_external>", line … -
Deploy Django+React project in cPanel
What is a way to deploy both django and react apps to cpanel in the same domain. eg. www.domain.com for frontend and www.domain.com/api for the backend? -
Password field would not render
My forms.py looks like this: from django import forms enter code here class RegisterForm(forms.Form): username =forms.CharField() password =forms.PasswordInput() email =forms.EmailField(label='E-Mail') gender =forms.ChoicField(choices=[('Male', 'male'), ('Female', 'female')])`enter code here` When I run it every other field shows except for the password field. Please someone should help me out. -
Cannot resolve keyword 'workout_exercises' into field
I perform request http://167.71.57.114:8000/api2/workout-programs-ctype/ And receive an error FieldError at /api2/workout-programs-ctype/ Cannot resolve keyword 'workout_exercises' into field. Choices are: description, description_en, description_fr, description_ru, exercises, id, name, name_en, name_fr, name_ru, sub_category, sub_category_id, video_url I have an error in this line File "/app/backend/apps/workouts/api/serializers.py" in get_data 76. exercises = Exercise.objects.filter(workout_exercises__workout_program=obj) serializers.py class WorkoutProgramTypeChallengeSerializer(serializers.ModelSerializer): # data = ExerciseSerializer(source='workout_exercises.workout_exercises', many=True) type = serializers.CharField(source='workout_types') data = serializers.SerializerMethodField() class Meta: model = WorkoutProgram fields = ('name', 'type', 'data') def get_data(self, obj): exercises = Exercise.objects.filter(workout_exercises__workout_program=obj) data = dict() for i in exercises: data.update(ExerciseSerializer(i).data) return data views.py class WorkoutProgramTypeChallengeViewSet(viewsets.ModelViewSet): queryset = WorkoutProgram.objects.filter(workout_types='C') serializer_class = WorkoutProgramTypeChallengeSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['is_free'] http_method_names = ['get'] -
Cant set icon in bootstrap template
I am running a django server and I am using bootstrap for the front end but i cant seem to set the icon even though I am using the code from the template Here is my html code The icon I am using is 256x256 pixels Also the template I am using as a base is Greyscale and it can be found here https://startbootstrap.com/theme/grayscale -
Django - CSRF problem after moving to production server
I moved applications to the production server and I have a problem with CSRF - Access denied (403) CSRF verification failed. The request was aborted. I checked in my browser and I don't have a cookie named csrftoken Part of my settings.py looks like this: SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'Strict' #SECURE_HSTS_SECONDS = 31536000 #SECURE_CONTENT_TYPE_NOSNIFF = True #CSRF_COOKIE_SECURE = True #SESSION_COOKIE_SECURE = True #SESSION_COOKIE_SAMESITE = None #SECURE_HSTS_PRELOAD = True I haven't turned on HTTPS yet Everything worked fine on the development server. Where to find the cause and what to improve? -
How to connect two separate Django project
I'm having two separate django projects one project is the dashboard and the another is data visualization project. I need to connect or link my data visualization project into my dashboard project I'm wondering how should i do that -
How to implement smooth loading of objects in django pagination?
So, currently, I have infinite scroll feature working (I made it with the help of JS Waypoints). But I have footer on my page and it's unreachable because when user scrolls down, new content gets loaded and footer gets further. I thought of two ways of solving this problem but I found nothing on the net. The first way is to use not infinite scroll plugins but to use django pagination instead and smoothly load page objects when user scrolls down and provide a link when a page reaches let's say 20 objects. The second way is to use infinite scroll and when user reaches 20 objects provide him a link on the next page and stop loading next objects. I don't know how to do both because I'm beginner and as I mentioned it before, I tried googling solutions and found nothing. I hope I expressed my ideas clearly and I look forward for any advice! Here is my code: #views.py def index(request): posts = Post.objects.all().order_by('-id') paginator = Paginator(posts, 4) page_num = request.GET.get('page', 1) page = paginator.page(page_num) #I cut the part of code which handles different exceptions to keep things simple return render(request, 'index.html', {'posts': page}) #template <div class="infinite-container … -
Swagger compatibility with custom fields on Django serializers?
I was recently integrated into projects that are using the Django rest framework and swagger. I had to define a custom field for a serializer at some point and it works fine, but swagger doesn't recognize its type (it always marks it as string). Custom field: class InheritableAttribute(serializers.ReadOnlyField): def __init__(self, attribute_name, serializer_class=None): super().__init__() self.attribute_name = attribute_name self.serializer_class = serializer_class def get_attribute(self, instance): value = getattr(instance, self.attribute_name) if not value: value = getattr(instance.product, self.attribute_name) return value def to_representation(self, value): if self.serializer_class: return self.serializer_class(value).to_representation(value) return super().to_representation(value) Serializer (simplified): class Serializer: base_price = InheritableAttribute('base_price') keep_inventory_count = InheritableAttribute('keep_inventory_count') Swagger: swagger output Here, I want base_price to be float and keep_inventory_count to be bool, for example. Also, you may have noticed that the custom field is reused for different types of data, so the type should somehow be a parameter, but I can probably figure that stuff out; I just need to know how to set the type for a custom field so that swagger shows it correctly. -
Testing Try - Catch Django function. Need exception testing
it's probably a straightforward simple problem but i haven't found similar information. I want to test a get function, which throws a generic exception, in case any event if the model fails. This is my view: @api_view(['GET']) def get_group(request): """ Returns all works """ try: group = Group.objects.all() serializer = GroupSerializer(group, many=True) return Response(serializer.data) except Exception as e: return Response(data={'error': e.args}, status=500) I have the test that does not throw an exception, but I need it to cover the one that throws an exception and I can't find a way. I have tried several things but the closest thing to get right has been this. def test_get_group_list_fail(self): with self.assertRaises(TypeError): response = self.client.get('/groups/') resultados = self.group.objects.all() esperado = CrackingGroupSerializer(resultados, many=True) self.assertNotEqual(esperado.data, ['fail']) assert response.status_code == 500 If anyone knows a solution, it is appreciated in advance. -
Does heroku ignore django's setting.py file?
I have a django based Heroku app, I set it up so that the remote website is connected to the remote postgresql database. (After following the 'get started' tutorial on heroku documentation for django) I needed to make a local version of the same app as well, but for its database the local postgresql is used so I simply modified the DATABASES = { "default": { "ENGINE" : "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3") } } into DATABASES = { "default": { "ENGINE" : "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD":"loremipsum", "HOST": "localhost", "PORT":"" } } It works as expected and there is no problem. So the local app is connected to the local database. But the part I don't understand is that why the remote app after deploying the changes to remote heroku repository is still connected the remote postgresql? The changes in setting.py are also the part of that deployment. The gitignore file does not include the setting.py and actually when I clone the remote git repo for my heroku it shows that the setting.py has indeed updated to the one that is connected to the local database and not the remote one. However when accessing my web app online (example.heroku.com) … -
Django filter Ascii issue
I have created a graphene-django api and i'm using postgresql db. When i search an object i've had an issue with ascii characters. For instance if the object title is 'İŞÖÇÜĞÖ' and i search lowercase 'işöçüğö' it can not be filtered. request: query allArticles {allArticles(superSearch:"işöçüğö"){edges{node{title}}}} response: "message": "Expected 'ArticleFilter.super_search' to return a QuerySet, but got a NoneType instead." Thanks in advance. -
I need to consume data from an external API, in django but not return that as a render/html
I need to consume data from an external API in django, but not return that as a render/html. Most of the sites/eg that I came across consumes the data but uses it to render it as an HTML. I am using requests library but the response from it has to be rendered as an HTML, any way to avoid that. -
How to assign model fields to a custom variable in the view, and use it in context to pass to the template?
so I have a model in models.py, and it has a few fields. Next, I make a form in forms.py to make a creative form. Then I import that form from forms.py into views.py. In the views.py, I make the create view, with the creat form. But here's the problem. In the views.py, I have the model field space. now I want to do something with that field. I assign a custom variable to this space field and pass it in the context. But it gives an error called local variable not defined. models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') … -
Creating a list showing how many posts every user has posted on site
I'm working (or better I'm learning) in django, i want to create an html page with a list that shows how many posts every user has published so far. in views.py i set: @user_passes_test(lambda u: u.is_staff) #<-Because I want that only admin will see this def num_post(request): num_post = Post.objects.filter(author=request.user).count() return render(request, 'api/post_numbers.html', {'num_post' : num_post}) and in post_numbers.html i set: {{user.username}} : {{ num_post }} but i can only obtain the name and the post number of the current user... how can i solve this? Thank you in advance! -
Can't load static files in Django:
I've already invoked collectstatic with no effect Errors from chrome: Failed to load resource: the server responded with a status of 404 (Not Found) logo.png':1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.bundle.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) lightbox.min.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) all.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) style.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) bootstrap.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)lightbox.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) settings.py STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, 'btre/static')] base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> <title>BT Real Estate</title> … -
How to get the most liked users in django rest-api
So I have a social media app, where users can like the posts of other users. Now I want to fetch the top 20 users who have received the most number of likes. I am pretty much confused how to query my Likes Model My LIKES MODEL class PostLike(models.Model): user_who_liked = models.ForeignKey(User, on_delete=models.CASCADE) post_liked = models.ForeignKey(Post, on_delete=models.CASCADE) liked_on = models.DateTimeField(default=timezone.now) SIMPLIFIED POST MODEL class Post(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) caption = models.TextField() date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField( User, blank=True, through=PostLike) image = models.TextField() class Meta: ordering = ['-id'] SIMPLIFIED USER MODEL class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) user_name = models.CharField(max_length=100, unique=True) date = models.DateTimeField(default=timezone.now) profile_picture = models.TextField( default="https://www.kindpng.com/picc/m/24-248253_user-profile-default-image-png-clipart-png-download.png") bio = models.CharField(max_length=200, default="") objects = CustomManger() def __str__(self): return self.user_name ** My View ** @api_view(["GET"]) @permission_classes([IsAuthenticated]) def leaderboard(request): # I dont know how to query the PostLike model now to get the most liked user pass -
Show, for each field, how many items has each field DjangoREST
I'm working on a Django project, coding some API calls where people can reserve a parking place. I have a database, and I want to display how many reservations has each user. I know this can be done easily on SQL, but I can't find the way to do this on Python. I've already tried to do what the documentation says: https://docs.djangoproject.com/en/3.1/topics/db/aggregation/#cheat-sheet but it doesn't work for me. -
Django VariableDoesNotExist, Failed lookup for ket [currency]
I am facing to this problem with my django application on production dream-access.com I have 500 for this issue below: VariableDoesNotExist at /fr/ Failed lookup for key [currency] in <django.contrib.sessions.backends.db.SessionStore object at 0x7f31c7411ba8> can somebody hekp to fix this error ? Please. Thanks. -
Django dose not validate form
I have form with the name of CommentForm when the form is validated it has to return HttpResponse which is saying that the form is valid if does nothing forms.py models.py views.py Templat code -
Django: Allow Users With Permission to Edit Project Page
I have a model: uProjects that associates a user and a project and if that user has admin status, i.e. ifAdmin. I am trying to create a way to allow a user to editproject if that user has ifAdmin=True for that project. The way I am currently doing it is with a wrap function, but I have a problem because even if I am logged in with a user who has ifAdmin=True for project "x," and I go to project "x" page and try to edit project, I still get the HttpResponseRedirect('/'). model: class uProjects(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) ifAccepted = models.BooleanField(null = True, blank=False, default=False) #ifLeader = models.BooleanField(null = False, blank=False) ifAdmin = models.BooleanField(null = True, blank=False, default=False) title = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.user.username + ',' + self.project.name views.py def admin_check(function): @wraps(function) def wrap(request, *args, **kwargs): user = request.user name = kwargs.get('name') if uProjects.objects.filter(title=name, user=user, ifAdmin=True).exists(): return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap @admin_check def update(request): if request.method == "POST": pr_form = ProjectUpdateForm(request.POST, request.FILES, instance=request.project.name) if pr_form.is_valid(): pr_form.save() messages.success(request, f'This project has been updated.') return redirect('project') else: pr_form = ProjectUpdateForm(instance=request.user.profile) context = { 'pr_form': pr_form } return render(request, 'projects/updateproject.html', context) …