Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Performing operations when data is added from admin site in django web application
I have the following models class Order_Ingredient(models.Model): day = models.DateField(auto_now_add=True,blank=True) ingredient = models.ForeignKey(Inventory, on_delete = models.CASCADE) amount = models.IntegerField(help_text = "in grams") class Inventory(models.Model): ingredient_name = models.CharField(max_length=100,unique=True) quantity = models.IntegerField(help_text = "in grams") min_quantity = models.IntegerField(help_text = "in grams") cost_price = models.IntegerField(help_text = "cost per gram") I have registered both the models to the admin site. Now I want to implement the fuctionality that whenever I insert data from the admin site in the Order_ingredient model, I can perform some additional operations like updating the quantity of ingredient referenced by foreign key. One way to do this was to override __init__ in model. But everywhere I searched, it was advised to avoid this method. Is there a workaround to this problem? -
Hidden input field didnot show the correct value which was access from views.py in Django
Before I asked this question, I have searched online and found similar solutions. However, it does not work for my case. I would like to pass the hidden input value in views.py but it didn't show the right value. when I hardcoded the value it passes the correct one but when I passed the value which was access from one of the functions of views.py it didn't show the correct value in the console. here is my html template where i access the value in hidden input tag <label > <h1>All grade:</h1></label> <form action="show_topics" method="post" > {% csrf_token %} {% for cat in show_grades %} <div class="col-sm-4"> <div class="card"> <div class="card-body"> <label><h5 class="card-title" style="color: hotpink">{{cat.grade}}</h5></label> <!-- <input type="hidden" name="gradeid" value="{{to.grade}}"> --> <button class="btn btn-outline-success" type="submit" name="classname" value="{{cat.grade}}" ><h4>View Class</h4></button> <input type="hidden" name="ids" id="idss" value="{{cat.id}}"> <!--<a href="#" class="btn btn-primary">Go somewhere</a>--> </div> </div> </div> {% endfor %} </form> view.py (from that function retrieved the value which is used in hidden input field) def add_grade(request): if request.method == "POST": teacher_id=request.POST.get('submit') #tech_id=int(teacher_id) print("teacher id retrieved") print(teacher_id) print("===") #print(tech_id) grade = request.POST.get('addgrade') # classes=request.POST.get('class') grade = Add_Grade(grade=grade, username_id=teacher_id) grade.save() show_grades = Add_Grade.objects.raw("Select * from Add_Grade where username_id = %s",teacher_id) context={ 'show_grades':show_grades, } #allgrade=Add_Grade.objects.all() return render(request,'teacher_dashboard.html',context) … -
'ArticleSerializer' object has no attribute 'get'
The article serializer: class ArticleSerializer(serializers.ModelSerializer): class Meta: model=Article fields='__all__' settings: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } model: class Article(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) email=models.EmailField() date=models.DateTimeField(auto_now=True) def __str__(self): return self.title view function: def article_list(request): if request.method== 'GET': article =Article.objects.all() serializer = ArticleSerializer(article,many=True) return JsonResponse(serializer.data,safe=False) if request.method == 'POST': data = JSONParser.parse(request) serializer = ArticleSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status=400) i just created a simple serializer but whenever i try to get the response it says that the ArticleSerializer i created has no attribute 'get'. Error -
Pass extra_context directly to django.contrib.auth.urls?
I created this url pattern and I hoped the extra context would be passed on to the views. But the views, which use the correct templates, seem to ignore the extra context. path('accounts/', include('django.contrib.auth.urls'), {'extra_context': {'home_title': settings.HOME_TITLE, 'domain': settings.HOSTNAME}}), I wonder if is is possible at all to pass extra context to the django.contrib.auth.urls or whether I have to create my own views for login/signup/logout in order to use the extra context? -
How I can get log of all objects accessed in Django in a simple way?
I need request log in database with additional information about objects, that used during request processing. Now I have a middleware and function, that I call every time, when I load object from database. class LogMiddleware(MiddlewareMixin): def process_response(self, request, response): project_id = request.accessed_objects.get('project_id', None) Log.objects.create( user_id=request.user.id, request_url=url[0:256], request_method=request.method, project_id=project_id, ) def custom_get_object(request, queryset, **filter_kwargs): obj = get_object_or_404(queryset, **filter_kwargs) project = get_project(obj) # all objects connected to some project via foreign key of through other object request.accessed_objects['project_id'] = project.id return obj I want to make the same things without calling custom_get_object in every place, switch to some ORM hook on loading objects from db, or something like that. -
Django can't find the URL pattern
I'm new to Django and I'm making wiki website based on markdown. I am having one problem. Django can't match the path in html to urls.py. It happens when I try to open wiki entries. It gives me the following error. I have already passed the parameter to 'page', I honestly have no idea what to do. Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order: admin/ [name='index'] wiki/<str:page> [name='page'] search [name='search'] create [name='create'] addentry [name='add_entry'] nomatches [name='nomatches'] results [name='results'] edit/<str:page> [name='edit'] random [name='random'] The current path, { url 'page' entry }, didn't match any of these. Please, tell me how can I fix this. index. html: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href="{ url 'page' entry }"><li>{{ entry }}</li></a> {% endfor %} </ul> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:page>", views.viewpage, name="page"), path("search", views.search, name="search"), path("create", views.create, name="create"), path("addentry", views.add_entry, name="add_entry"), path("nomatches", views.search, name="nomatches"), path("results", views.search, name="results"), path("edit/<str:page>", views.edit, name="edit"), path("random", views.random, name="random") ] part of views.py: def index(request): return render(request, "encyclopedia/index.html", … -
update DateTimeFIeld Django from post request
I want to update Datetime field on Django, but not with now() datetime but with the datetime given by post method. views.py serializer = PlantationSerializers(plantation, data=datum) theDate = datetime.strptime(datum['updated_at'], '%a %b %d %H:%M:%S GMT+02:00 %Y') if plantation.updated_at < theDate: serializer.save() WIth print I can saw that when theDate is more recent, I go in, that change every fields but not the field updated_at ... models.py class Plantation(models.Model): # Some other fields updated_at = models.DateTimeField(auto_now_add=True) I need that auto_now, but I want to edit it when I update it from post method. Sorry for my bad english :/ -
Undo changes in VS Code?
Well, this is a bit embarrassing. I was able to push/commit a functioning version of my web app files to git from VS Code. But then I made some very drastic changes and need to revert back to everything I had since my last commit. Is there a way to do that? Pretty new to this, my apologies. -
how can i query another schema using Django tenancy Schemas
I'm working on a CRM project using Django / Multi-Tenancy Schema, I would like to know how a user can access another schema ( how I can query another schema ) I googled my query but I couldn't find any answer -
Optimize collection of paginated REST API data
I need to collect several thousand records from a 3rd party REST API, but each call is limited to 99 records at most. Additionally, the API doesn't return any information about the total number of records or page count, it only returns a boolean "more_records". Having to make several hundred API calls to collect data for a page is obviously very slow, and it's causing one of my routes to timeout. My first thought for optimization is to split out the API calls into asynchronous tasks, but because there's no stopping information besides "more_records" I'm not sure how to handle calling those tasks. I'm using Django for this and I already have Celery set up for other purposes. The route that times out collects and manipulates this and other data and returns it as JSON to populate a gross report. One idea I had was to break down this JSON route so that my gross report's Javascript makes many smaller API calls and manipulates the data itself, but that only solves the timeout since no one call takes too long. The only ways I see to optimize the response time is to reduce the number of API calls or handle … -
Unable to resolve `Bad file descriptor` from django logging
I'm trying to add Papertrail logging to a Django app, which is build alongside an older Falcon app. Due to some of the v1 to v2 transition, this is how it's setup (a lot of code removed for simplicity): import logging import logging.config logger = logging.getLogger('api') ... logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'logstash': { 'level': 'INFO', 'class': 'logstash.TCPLogstashHandler', 'host': LOGSTASH_HOST, 'port': LOGSTASH_PORT, 'version': 1, 'message_type': 'django', 'fqdn': True, }, { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'address': ('logs.papertrailapp.com', int(CREDENTIALS_PAPERTRAIL_ADDRESS)) } } 'loggers': { 'api': { 'handlers': ['console','SysLog'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, "gunicorn.error": { 'handlers': ['console','SysLog'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, "gunicorn.access": { 'handlers': ['console','SysLog'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, 'access_logs': { 'handlers': ['logstash'], 'level': 'INFO', 'propagate': False, }, }, }) The gunicorn stuff comes from https://github.com/benoitc/gunicorn/issues/2016 In a test file, I have logger.warning('test asdf'), which I see get spit out to the console, however, it also throws: Traceback (most recent call last): File "/usr/local/lib/python3.7/logging/handlers.py", line 940, in emit self.socket.sendto(msg, self.address) OSError: [Errno 9] Bad file descriptor Thing is, the access logs stuff works; we're seeing that stuff go to logstash, but I cannot seem to figure out this socket issue for … -
AJAX not rendering on django template
So I am trying to render some text dynamically on a webpage using AJAX. I created an empty div and attempted to fill it with some data but it renders nothing. Firstly, my question is how do I pass extra data to the AJAX call? Below is the HTML <div> {% for user in searched_users %} <p>{{ user.user.username }}</p> </div> <div id = "links"> <a id = "follow" href="{% url 'add' name=user.user.username %}">Follow</a> <a id="unfollow" href="{% url 'unfollow' name=user.user.username %}">Unfollow</a> <a href = "{% url 'match' name=user.user.username %}">Perform Match?</a> </div> <div id = "display"> </div> {% endfor %} <script> element = document.getElementById("follow"); target_element = document.getElementById("display"); data = user.user.username element.onclick = () =>{ $.ajax({ url : "/follow/", data : data, success: display } )}; function display (data) { if (data) { console.log(data); // Add the http response to element target_element.innerHTML = data; }} </script> {% endblock %} it has a couple of href-s used for following, unfollowing a user. When a user clicks on the follow href, I want to display the HTTPresponse of this view. def follow(request, name): sender = User.objects.get(username = request.session["username"]).userprofile display = User.objects.get(username=name) receiver = User.objects.get(username= name).userprofile if receiver not in sender.get_friends() and sender != receiver: relationship … -
django - annotate based on the count of a foreignkey?
I have the three models below: class User(AbstractBaseUser): ... thing_prefer = models.ForeignKey(thing, on_delete=models.SET_NULL, null=True) class ThingType(models.Model): name = models.CharField() class Thing(models.Model): type = models.ForeignKey(ThingType, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField() # this would have choices defined I currently am using a ListView to list ThingTypes, and I am currently annotating each ThingType with the number of Things with different states, as below: def get_queryset(self) -> QuerySet: queryset = ThingType.objects.all().annotate( count_good=Count( "thing", filter=Q( thing__state="good", ), ), ) .order_by("name") ) return queryset How would I extend this to include the count of Users that have set their thing_prefer to a Thing which references ThingType? (Or, for each ThingType returned, how would I annotate with the number of Users that have set their thing_prefer to a Thing that references the ThingType being investigated?) Thank you! -
Django & docker-compose - psycopg2 connection error
I am trying to run a simple Django app with PostgreSQL using docker-compose. The PostgreSQL container runs fine and is accessible but I am unable to reach it from inside the Django container using python. Here is my docker-compose.yaml: version: "3" services: db: image: "postgres" restart: always environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} volumes: - pgdata:/var/lib/postgresql/data django: build: ./qc_django ports: - "8080:8080" environment: - DB_NAME=django - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_HOST=db - DB_PORT=5432 - DEBUG=True depends_on: - db volumes: pgdata: Here are the database settings inside of the Django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } The error it spits out after a minute or so: django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "db" (172.21.0.2) and accepting TCP/IP connections on port 5432? -
Django: redirection if user is logged
Although there are many questions of this type, the answers that the collaborators have given do not work for me in any case. I need to prevent logged in users from accessing the login page. urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), views.py def user_login(request): if request.user.is_authenticated: return HttpResponseRedirect('dashboard') settings.py LOGIN_REDIRECT_URL = 'dashboard' But it does not work. Please, help. Thanks!! -
How to use sudo command via PuTTY
I'm trying to depoly django app on a hosted server. My local PC has Windows as OS so I'm using PuTTY to connect to the server (which has GNU/Linux). Once I connect to the server, I install Python and setup vierualenv, but when i try to install the postgresql I receive the error ModuleNotFoundError: No module named '_ctypes' I know that it's quite a common problem mentioned in numerous threads (for example, Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing) which can be solved by intalling "libffi-dev" by the command sudo apt-get install libffi-dev However, when I try to use the sudo command I receive the following error: -bash: sudo: command not found I tried to find a solution, but my experience with Linux is rather limited. From what I found, it may be caused by me not being logged as a superuser, but I could not find clear instruction how to enable it when I access Linux server via SSH (PuTTY) from Windows. Does anyone know a way how could access sudo command or how to install "libffi-dev" in a way which does not require sudo commands?Thank you in advance for any help. -
İn Django, how to make a div visible after only when scrolled down to some px
I am new to Django. I am building a website which has a side-bar but I want it to be seen when user scrolled a bit. In my opinion, I can do it with writing some css codes such as an "if statement on html code using "!important" " The main problem is to make it, I need something which will trigger the if statatement. How can I put down on codes the triggering part ? To be clearer, how can I write the code which says when scrollbar goes down 200px. As I said I am new to Django and also new to web development. I have not learned javascript or jquery yet.Can it be done without these ? Thank you. -
Not getting fields prefilled with previous values while editing a form in django
I have a form(EditProfileForm) which I created to edit the profile details. My issue is that whenever I go to the EditProfileForm page in the browser the fields are not filled with previous values which I gave while making the profile for the first time, I have to fill the entire form however if I make some change in the value then the change is being made successfully. my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pic.jpg', upload_to='profile_pictures') location = models.CharField(max_length=100, blank=True, null=True) bio = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.user.username my EditProfileForm in forms.py: class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['image', 'location', 'bio'] my two views regarding profile and edit profile: @login_required def profile_page(request): user = request.user posts = Post.objects.filter(author=user) posts_count = posts.count() profile = Profile.objects.get(user=user) return render(request, 'blog_app/profile.html', {'user': user, 'posts_count': posts_count, 'profile': profile}) def edit_profile(request, id): profile = Profile.objects.get(id=id) if request.method == 'GET': form = EditProfileForm(request.FILES, instance=profile) else: form = EditProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): # deleting old uploaded image. image_path = profile.image.path if os.path.exists(image_path): os.remove(image_path) # the `form.save` will also update the newest image & path. form.save() return redirect('profile') return render(request, 'blog_app/edit_profile.html', {'profile': profile, 'form': form}) my two urls … -
Why do I have a 'KeyError' error when using when using Django's coverage tool
Im developing a django API. Now im doing some tests on the endpoints and when i execute 'python manage.py test' everything goes well. But when i use the flag '--with-coverage' or 'coverage run --source='.' manage.py test app && coverage report' i get the error 'KeyError: 'BREAK_LOOP'. Someone can help me? -
django models distinct is still returning duplicates
Im stumped ... and its probably obvious but i cannot seem to get distinct to remove the duplicates here q = SubscriberPhoneNumber.objects.values_list('phone_number',flat=True).order_by('phone_number').distinct('phone_number') print(q) <QuerySet ['9711231234', '5095551212', '9994441212', '9994441212', '9711231234']> as you can see 9711231234 appears twice (as does 9994441212) (note these are not real phone numbers...) here is the model class SubscriberPhoneNumber(models.Model): subscriber = models.ForeignKey(SystemStatusSubscriber, on_delete=models.CASCADE) phone_number = EncryptedCharField(max_length=24, **null) country_code = models.CharField(max_length=8, default='+1') I feel like im losing my mind ... and dont understand why distinct is not eliminating the duplicates (I really want distinct on country_code and phone_number but just included phone_number to simplify the problem) (I also do not need values_list but thought that might help select only the columns i am interested in) (note that i can certainly cast the result to set to get unique values... but i feel like distinct is the right way to approach this, and cannot figure out how to make it work... ) -
Django Password Decrypt in PHP (with salt and cypher)
in Django we have a hashed password like "pbkdf2_sha256$150000$wRUxY0PmiVfeGva48bzZTtaCKG5QgYNzr8VRw/ezSwEQptgqg=" and a password cypher like "gAAAAABgXg4aYTztisoQEduXbaYX81hY_xEStrI2IHewIKcBxLWAtX8uY8SxzujRhm84LzgKzSJ6Zu5i8wKoL8mUvNvSmKGAQg==" and a salt like "-GcGi6r3TmMNz5cD8Cagpfli3Es-hz_s3hda5vr5G60=" in Python i decrypt password with Fernet Library like f = Fernet(salt) password = f.decrypt(bytes(password_cypher.encode())).decode() as anyone can see we just using cypher and salt. and question is how Decrypt like this method in php...? (Laravel & PHP) -
Django ORM date field wrong output
I want to select the objects that date field equal to the latest date in the model. So I pick the latest date by >>> latest_date = StockPrice.objects.latest('date').date >>> latest_date datetime.date(2021, 4, 9) but the latest date in my model is 2021-4-13. then I tried this >>> StockPrice.objects.filter(date=latest_date) <QuerySet []> I use latest_date just got, but nothing show after filtering Can't figure it out how does this happened. ./models.py class StockPrice(models.Model): date = models.DateField() symbol = models.IntegerField() open = models.FloatField() high = models.FloatField() low = models.FloatField() close = models.FloatField() shares = models.IntegerField() volume = models.IntegerField() pe = models.FloatField() pb = models.FloatField() yield_rate = models.FloatField() *** [click to data inserted to the model][1] [1]: https://raw.githubusercontent.com/ycy-tw/python-django-stock/main/demodata/stockprice.csv -
Django NameError:name 'request' is not defined [closed]
I am getting this error on writing the below code: return render(request, 'index.html') This is the error: return render(request, 'index.html') NameError: name 'request' is not defined PS: I was not able to find a solution on this that's why I am posting this question -
Create a custom function as a filter in proxy model, django admin
I need help to convert CashInhandAdmin->expense as a filter (high and low), have tried below filter but failed because proxy model is inherited from user_profile model but want to filter expense sum that is different model. Filter class ExpenseFilter(admin.SimpleListFilter): title = 'Expense' parameter_name = 'Expense' def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. """ return (("low", "Filter by low amount"), ("high", "Filter by high amount")) def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ if self.value() == "low_price": return queryset.order_by("expense") elif self.value() == "high_price": return queryset.order_by("-expense") else: return queryset.all() Model class CashInhand(user_profile): class Meta: proxy = True verbose_name = "Cash In Hand" verbose_name_plural = "Cash In Hand" Admin class CashInhandAdmin(admin.ModelAdmin, admin.SimpleListFilter): def get_queryset(self, request): print(request.GET.get("Expense")) qs = super(CashInhandAdmin, self).get_queryset(request) return qs.filter(employee__isnull=False).distinct("employee_id").order_by("employee_id") def has_delete_permission(self, request, obj=None): return False def expense(obj): exp = models.Expense.objects.filter(created_by_id=obj.employee, status='1').annotate( as_float=Cast('amount', FloatField())).aggregate(Sum("as_float")) if exp["as_float__sum"]: return int(math.ceil(exp["as_float__sum"])) else: return str(0) list_display = (expense,) list_filter = … -
getting number of days between twoo dates
I don't figure out how to get the number of days betwen twoo dates: this is the models I have : class Reservation(models.Model): """A typical class defining a reservation model.""" # Fields id_reservation = models.BigAutoField(primary_key=True) start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) client_id = models.ForeignKey(Client, on_delete=models.CASCADE) chambre_id = models.ForeignKey(Chamber, on_delete=models.CASCADE) # Metadata class Meta: ordering = ['-end_date'] # Methods def get_absolute_url(self): """Returns the url to access a particular instance of MyModelName.""" return reverse('model-detail-view', args=[str(self.id_reservation)]) def __str__(self): return self.id_reservation and try to calculate the days between the end_date and the start_date in my generic view: class ReservationsListView(generic.ListView): """ReservationsListView: produce a list of all Reservations """ model = Reservation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['periode'] = Reservation.end_date-Reservation.start_date return context can please help doing this.