Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying foreign key in django admin panel
I cant seem to find the correct answer to display 1 foreign key value: it displays "house label" in the correct "table" it displays the value. but it does not give the perfect "column" name. i would love to display "house_name" in the table.. any idea's? admin.py from django.contrib import admin from .models import UserProfile,House # Register your models here. class UserProfileAdmin(admin.ModelAdmin): def house_label(self, obj): return obj.house.house_name list_display = ('user', 'api_key','house_label') admin.site.register(UserProfile,UserProfileAdmin) admin.site.register(House) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class House(models.Model): house_name = models.CharField(max_length=500,blank=False, null = False) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ="profile") api_key = models.CharField(max_length=500, blank=False, null = False) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name = "house") -
Django overriding ModelAdmin classes with a function requiring Model name
In my admin.py, I have a lot of ModelAdmin classes and I want them to all override a function, has_module_permission. I want to base the module permission off of the user's permissions for the model corresponding to the ModelAdmin, and to do that I need to know the model name in order to run request.user.has_perm('app.add_<model>') or something similar. I think an easy way of doing this is to create a class that has this function which is somehow able to get the model name, and then have each of the ModelAdmin classes inherit from that. The problem is that I don't know how to access the model's name from ModelAdmin. What's the best way of doing this? -
Model field not updating in admin page even if value changes
I apologize for my confusing title but I hope the code explains it better. In my views.py file I have the follow view def create_view(request): context = {} form = CreateForm(request.POST) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() instance.author.profile.participating_in = Post.objects.get( title=instance.title ) instance.save() print(instance.author.profile.participating_in) context["form"] = form return render(request, "post/post_form.html", context) when I print out the value of instance.author.profile.participating_in it shows up in my terminal however when I check the admin page it doesnt update at all. I'm sure I messed up somewhere silly but I cant seem to find it. Thanks! -
Check if item exists in database by field value
I have a class called Product and I want to check if there is already a product in the database with the same title. class Product(models.Model): title = models.CharField(max_length=255) ... for (something in something): check if db contains product with a title of 'Some Product' -
Limit django channels connections
I'm building some simple django sockets with channels. How can I limit the number of simultaneous connections accepted? Something like class BridgeConsumer(WebsocketConsumer): def connect(self): print('Bridge connected') # Accept only if there are at most N connections self.accept() def disconnect(self, close_code): print('Bridge disconnected') This seems trivial but I was unable to find an answer Thanks -
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data, how can I resolve this error [closed]
I am trying to fetch data from django with JS, but I get the error, and I cannot find where the problem is can anyone help. Using Dango admin I have sample post for the application but fetching the data is problematic. The html <body> <div id="posts"></div> <script src="{% static 'network/network.js' %}"></script> </body> The JS Code document.addEventListener("DOMContentLoaded", displayPost) function displayPost(){ const post_item = document.createElement('div') fetch('/allPost') .then(response => response.json()) .then(posts => { //console.log(posts); posts.forEach(function(post){ postContent = `<div> <p>${post.poster}</p> <p>${post.content}</p> <p>${post.datetime}</p> <p>${post.like}</p> </div>` post_item.innerHTML =postContent; document.querySelector('#posts').append(post_item); }); }); } the url.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newPost", views.new, name="new"), path("allPost", views.allPost, name="allPost"), ] the view.py def allPost(request): posts = Posts.objects.all() posts = posts.order_by("-dateTime").all() return JsonResponse([post.serialize() for post in posts], safe=False) the models.py class Posts(models.Model): posterUsername = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_creator") postContent = models.CharField(max_length=64) dateTime = models.DateTimeField(auto_now_add=True) like = models.IntegerField() # def __str__(self): # return self.id def serialize(self): return { "id": self.id, "poster": self.posterUsername, "dateTime": self.dateTime.strftime("%b %d %Y, %I:%M %p"), "like": self.like } -
Django Form Will Not Validate On Ubuntu/Apache2
I've been having some trouble getting this form to be valid. I've been able to get it to run locally and on Heroku. However, I am now trying to get it to run on Ubuntu/Apache2 and the form will not validate. This is sample of my form and view. The date1 and date2 variables get plugged into an API request, however, since the form is not valid, I keep getting a local variable is referenced before its assignment. #****** Form ******# class RequestForm(forms.Form): start_date = forms.DateTimeField(input_formats=["%Y %m %d %H:%M:%S"],widget=forms.TextInput(attrs={ 'class':'form-control inputDate ', 'type': 'datetime-local' })) end_date = forms.DateTimeField(input_formats=["%Y %m %d %H:%M:%S"],widget=forms.TextInput(attrs={ 'class':'form-control inputDate', 'type': 'datetime-local' })) #****** END Form ******# #*********** View *****************# class ReportView(TemplateView): template_name = 'reports/report.html' def get(self, request): form = RequestForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = RequestForm(request.POST) if form.is_valid(): date1 = form.cleaned_data['start_date'].strftime("%Y-%m-%d %H:%M:%S") date2 = form.cleaned_data['end_date'].strftime("%Y-%m-%d %H:%M:%S") url = "****" payload = "{\"request\": {\"method\": \"switchvox.callLogs.search\", \"parameters\": {\"start_date\": \""+date1+"\", \"end_date\": \""+date2+"\", \"account_ids\": [\"1139\",\"1140\",\"1143\"], \"sort_field\": \"start_time\", \"sort_order\": \"ASC\", \"items_per_page\": \"8000\", \"page_number\": \"1\"}}}" headers = { 'User-Agent': 'curl/7.47.1', 'cookie': "lang_locale=en_us", 'Content-Type': "application/json", 'Authorization': "******" } urllib3.disable_warnings() response = requests.post(url, data=payload, headers=headers, verify=False) call_report = response.json() print(type(call_report)) itemBank = [] for i in call_report["response"]["result"]["calls"]["call"]: itemBank.append(( i["uniqueid"], … -
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') …