Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
yum install httpd failing
to enable the https on my instance I wanted to work with yum. the apache2 is running fine but whenever I do something with sudo yum install httpd or sudo yum-config-manager --enable httpd but everytime I get this return Repository 'httpd': Error parsing config: Error parsing "baseurl = 'httpd'": URL must be http, ftp, file or https not "" I have tried to follow the instructions of the internet but my further research is not getting me anywhere so please help. What did I miss? -
ModuleNotFoundError: No module named 'allauth.accountallauth'
I've a app name cz Error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\ashis\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth.accountallauth' this is my settings.py file: from pathlib import Path from django.template.backends import django import os import allauth BASE_DIR = Path(__file__).resolve(strict=True).parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cz', 'allauth', 'allauth.account' 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ChatZone.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ChatZone.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { … -
(Django) How to clean an unbound form?
I have a problem. I looked at the web for a solution but did not find one. If my problem already have an answer, please give me the links. Here is the problem: I create a form inside one of my view with some initial values: form = MyForm(initial=initial) However, I do not have a full control over these initial values, thus I need to check is the form is valid. However, because the form in unbound .is_valid() always return False. So, I tried to create an bound form from the first step: form = MyForm(initial) However, I do not initialize all the field, simply because I do not know their name and how many they are, thus I cannot initialize all of them. The problem is that some of the field I do not initialize are required. Thus, the .is_valid() always return False because I do not provide required field(s). What I know is that all of the required field have a default value. When I created the form with initial values (i.e. MyForm(initial=initial)), the defaults value are provided. So I wish I could do something like: form = MyForm(initial=initial) form = MyForm(form) However, that obviously doesn't work. I … -
Error when creating a Django project using PyCharm
I'm using PyCharm Professional and when I'm trying to create a new Django project, I keep getting an error. Although the project is created, only the venv folder is generated. The standard Django starter files, mange.py, urls.py, etc. are not. Here are a few screenshots of the error. Here's the error I get. I can create a Django project in the terminal, but I was hoping that PyCharm would set this up for me. Apologies if I'm doing something wrong here. I'm new to both Django and PyCharm. Any help appreciated. Thank you. -
Serialize List of Objects based on Common Field in Django
In my Django app, I'd like to change the serialization output so my list of objects are keyed by encryption_protocol with a value containing an array of name values. I'm not sure how to do this and looking for some help. Current Output [ { "name": "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "encryption_protocol": "TLS 1.2" }, { "name": "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "encryption_protocol": "TLS 1.2" }, { "name": "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", "encryption_protocol": "TLS 1.2" }, { "name": "TLS_RSA_WITH_AES_128_CBC_SHA", "encryption_protocol": "TLS 1.1" }, { "name": "TLS_RSA_WITH_AES_256_CBC_SHA", "encryption_protocol": "TLS 1.1" } ] Desired Output [ { "encryption_protocol": "TLS 1.2" "names": ["TLS_DHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"] }, { "encryption_protocol": "TLS 1.1" "names": ["TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"] } ] models.py class Cipher(models.Model): name = models.CharField(max_length=settings.MAX_CHAR_COUNT, blank=False, null=False) encryption_protocol = models.CharField(max_length=settings.MAX_CHAR_COUNT, blank=False, null=False) class Meta: ordering = ['encryption_protocol', 'name'] serializers.py class CipherSerializer(serializers.Serializer): name = serializers.CharField(read_only=True) encryption_protocol = serializers.CharField(read_only=True) -
How to display the rows from a table in django in particular time each day in the interface of the user through the app
I want to display the contents of a table called recommendation in the interface django of the user in the morning of each day because i'm collecting recommendations and saving them in a table (each user have his own recommendations of course ) and i want to delete them after he check them. So i'm doing this but that is going to display the recommendations directly if i refreshed the page. HTML interface : <li class="word-bot-sent"><p>Do you want some recommendations today? </p></li> {% for obj in Recommendation %} {% if obj.user == request.user %} <li class="word-bot-sent"><p>{{ obj.title }}</p></li> <li class="word-bot-sent"><p>{{ obj.text }}</p></li> {%endif%} {% empty %} {% endfor %} So any ideas please, i need help as soon as possible thanks !! -
only getting the main track in output after concatenate
this is my function in my views.py but after merging the two audio files am getting only the current_song maybe it is happening because I am directly using the blob as my second audio. but if it is the actual reason then how to convert in blob into a regular audio file in python? def audiomarge(request): recorded_audio = request.FILES['audio'] new = tempSong(tempSongFile=recorded_audio) new.save() record_file_path = new.tempSongFile.url record_file_path = '.'+str(record_file_path) recorded_audio = request.POST.get('audio') songslug = request.POST.get('songslug') current_song = Song.objects.filter(slug=songslug)[0] current_song_path = current_song.songFile.url current_song_path = '.'+(str(current_song_path)) input_first = ffmpeg.input(current_song_path) input_second = ffmpeg.input(record_file_path) ffmpeg.concat(input_first, input_second, v=0, a=1).output('media/home/music/test.wav').run() return HttpResponse('yo') -
Do Django Cookies need to be set on every request?
My django project sets a cookie on login redirect, which works fine and they're visible in the browser. But when i make a request via python's request.post to my Django DRF API project, the WSGIRequest object on api shows there are no cookies attached. the settings file contains (for dev) SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_DOMAIN = '.localhost.com' SESSION_COOKIE_SECURE = False for both projects, who are on subdomains of localhost.com Do the cookies need to be explicitly added to the request on the front end project any time a call is made to the api for them to be attached? I'm sure this can't be the case, but I can't figure out why they aren't getting passed across.. -
Page not found error in django . handlerequest/<str:id> [name='handlerequest'] even when it exists
This is my views.py @csrf_exempt def handlerequest(request, id): order=Order.objects.filter(id=id), transaction_id = datetime.datetime.now().timestamp() form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': order.transaction_id=transaction_id order.complete=True print('order successful') else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'handlerequest.html', {'response': response_dict}) and this is my urls.py: path("handlerequest/<str:id>",views.handlerequest,name="handlerequest"), This handlerequest is a callback url of my paymentgateway in which I am passing order id.But when the page loads it gives page not found error.I know I maybe doing a silly mistake but I have gone through the code several times but I was not able to find what was causing the error. Please help.Thanks. -
Error in as_crispy_field got passed an invalid or inexistent field
The page returns the error as_crispy_field got passed an invalid or inexistent field after SUBMIT Button is cliked. I was trying to submit the form when the error is raised. A form for the template was created to setup the fields. The Form was instantiated in the views so that it could easily map the elements from the FORM to the TEMPLATE. What causing the error and how can I resolve it? FORM: Here is my form code class ModelCreateDescriptionForm(forms.ModelForm): name = forms.CharField(max_length=100) description = forms.Textarea() model_type = forms.ChoiceField( widget = forms.Select, choices = MODEL_TYPE_CHOICES, ) def __init__(self, project_id=1, *args, **kwargs): super(ModelCreateDescriptionForm, self).__init__(*args, **kwargs) # project = Project.objects.get(id=project_id) self.fields['model_type'].choices = MODEL_TYPE_CHOICES self.fields['model_type'].required = True class Meta: model = Model fields = ['name', 'description', 'model_type'] VIEW: Here is my view def modelCreationDescription(request, **kwargs): pk = kwargs.get('pk') project = Project.objects.get(id=pk) context = {} context['project'] = project if request.method == 'POST': form = ModelCreateDescriptionForm(pk, request.POST) name = request.POST.get(u'name') description = request.POST.get(u'description') model_type = request.POST.get(u'model_type') if not(name and model_type): messages.warning(request, f'Please fill model name and model type!') if form.is_valid(): formDescription = form.save(commit=False) try: formDescription.name = name formDescription.description = description formDescription.model_type = model_type formDescription.project = project except: messages.warning(request, f'Something wrong!') return redirect('all-model-listview') # save the … -
I want to create a doctor and user database in Django. But having problem in models please see the code below
This class is for the doctor info class doc_info(models.Model): doc_name = models.TextField() speciality = models.TextField() exp = models.TextField() contact = models.TextField() def __str__(self): return self.doc_name This class is for user information class usr_info(models.Model): age = models.TextField() blood_group = models.TextField() height = models.TextField() weight = models.TextField() vision = models.TextField() address = models.TextField() note = models.TextField() last_updated = models.DateTimeField(auto_now = True) name = models.ForeignKey(User ,on_delete = models.CASCADE) Here I am trying to add multiple docs to user_info recent_doc = models.ManyToManyField(doc_info) def __str__(self): return self.recent_doc I am getting SyntaxError: positional argument follows keyword argument -
How to filter, search and sort Django front-end records?
I have created a database that consists of about 2000 records. I'd like to allow user to perform searching, filtering or sorting it. That way I coded views.py: from django.views.generic.list import ListView from .models import Journal class JournalsView(ListView): model = Journal paginate_by = 50 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context And this is the template file: <!DOCTYPE html> <html lang="en"> <head> <!-- Meta tags --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <title>Journals' List</title> <!-- Bootstrap CSS & JS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body class="bg-light"> <div class="container"> <!-- Header --> <div class="py-5 text-center"> <h2>Journal Finder</h2> <p class="lead"> Journals list at glance. Search by name, sort by IF and ministerial points or filter for domains. <br> It is so simple! </p> </div> <div class="row"> <input class="form-control mb-4" id="tableSearch" type="text" placeholder="Type something to search list items"> <table class="table" id="journalsTable"> <thead> <tr> <th scope="col"> Title</th> <th scope="col"> IF</th> <th scope="col"> Ministerial Points</th> <th scope="col"> Domains</th> </tr> </thead> <tbody id="myTable"> {% for journal in object_list %} <tr> <td>{{ journal.title }}</td> <td>{{ journal.impact_factor }}</td> <td>{{ journal.ministerial_points }}</td> <td> {% for domain in journal.domain.all %} {% if not forloop.last %} {{ domain.domain_name }}, {% else %} {{ … -
nested dictionary in Django template
I am using the Django template, I have met one problem with the nested dictionary. {'Engineering Mathematics 1': {'Nov Dec - 2017': <FieldFile: Previous/Nov_Dec_2017.pdf>}, 'Engineering Physics': {'Nov Dec - 2016': <FieldFile: Previous/Nov_Dec_2016.pdf>, 'Nov Dec - 2018': <FieldFile: Previous/Nov_Dec_2018.pdf>, 'Nov Dec - 2019': <FieldFile: Previous/Nov_Dec_2019.pdf>, 'May June - 2017': <FieldFile: Previous/May_Jun_2017.pdf>, 'May June - 2018': <FieldFile: Previous/May_Jun_2018.pdf>, 'May June - 2019': <FieldFile: Previous/May_Jun_2019.pdf>}} I am trying to print all data in the HTML page by nested for loop. but it's not working on the HTML page. I have tried the code in Django shell and it working perfectly but when I come to HTML page it's not working. HTML Code {%for i, j in my_dict.items%} <----- from this line, code not working <h3> {{i}} </h3> {%for k, v in j.items%} {{k}} ---> {{v}} {%endfor%} {%endfor%} when I try the following code in HTML it prints the key_value of the main dictionary {%for i in my_dict%} <h3> {{i}} </h3> {%endfor%} output of the above code comes 'Engineering Mathematics 1' 'Engineering Physics' -
How to save data from form to django models?
I am working on CS50W project 2 - commerce and I've been working on the Create Listing point. I have a route /create where I have to get data and save it in models. I'll leave the code snippets below . I tried to use the ModelForm class , then validate the data and save() but it doesn't save data . I also ran queries in shell on the models to see if data is there but nothing. In the code snippets I'll leave only the useful parts to look cleaner. I checked and the imports ( importing models to views , other modules , etc) are fine. I think I made a mistake somewhere else , but I just can't see it. How to solve this? the ModelForm class AuctionsForm(forms.ModelForm): class Meta: model = Auctions fields = ['title' , 'description' , 'category' , 'image'] views.py @login_required def create(request): if request.method == "POST": form = AuctionsForm(request.POST) if form.is_valid(): form.save() else: form = AuctionsForm() return render(request, "auctions/create.html" , {"form" : AuctionsForm()} ) models.py class Auctions(models.Model): CATEGORY = [ ("No Category" , "No Category"), ("Fashion" , "Fashion"), ("Home" , "Home"), ("Toys" , "Toys"), ("Technology" , "Technology"), ] title = models.CharField(max_length= 50) description … -
Static files not deploying in heroku
I have deployed my app to heroku via GitHub. However when deploying i was getting a error stating: ! [remote rejected] master -> master (pre-receive hook declined) scrolling through the log it suggested setting heroku config:set DISABLE_COLLECTSTATIC=1.So i did that and re tried to deploy. This time the deployment worked. However, my static files aren't loading (ccs files). so i tried to reset heroku config:set DISABLE_COLLECTSTATIC to 0. However no joy, the ccs files dont want to load. Any ideas? -
How to get the value by its foreign key using a Django query?
I am building an application that allows a user to like a tournament. I have a query that gets all tournaments with the value of Like (this is a choice in the Like model). The query produces the correct count, but I can't get the name of the tournament, rather I get the id (which I do expect form the current query). I just haven't been able to figure out how to get the name of the Tournament. Here is the query: Like.objects.values('tournament', 'value').exclude( value='Unlike').annotate(like_count=Count('value')) The output for this query is: <QuerySet [{'tournament': 1, 'value': 'Like', 'like_count': 2}, {'tournament': 2, 'value': 'Like', 'like_count': 1}]> The expected output that I am looking for: <QuerySet [{'tournament': 1, 'name': 'Tournament 1', 'value': 'Like', 'like_count': 2}, {'tournament': 2, 'name': 'Tournament 2', 'value': 'Like', 'like_count': 1}]> This the Tournament class model class Tournament(models.Model): owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='tournaments') name = models.CharField(max_length=255) category = models.CharField(max_length=255) difficulty = models.CharField(max_length=255) likes = models.ManyToManyField( User, default=None, blank=True, related_name='tournament_likes') def __str__(self): return self.name I have a foreign key to Tournament. class Like(models.Model): OPTIONS = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) user = models.ForeignKey(User, on_delete=models.CASCADE) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) value = models.CharField(choices=OPTIONS, default='Like', max_length=10) def __str__(self): return str(self.tournament) -
django get field name on upload_to parameter
My Model: class SampleImage(models.Model): image1 = models.ImageField(upload_to=image_path) image2 = models.ImageField(upload_to=image_path) My upload_to method on image1: def image_path(instance, filename): ext = filename.split('.')[-1] filename = "some_file_name" + ext # Here is question. How can I get 'image1' field name programatically on image_path? used_field_name = "image1" #It would be 'image1' return os.path.join('photo/%s/%s' % (instance.__class__.__name__, used_field_name), filename) If field name is "image2", used_field_name on image_path would be image2 How can I get field name on where image_path is used? -
Django use datetime.date() as input for DateField to achieve past date input
I have a simple model where I want to input a past date as the DateField in the model. import datetime class BalanceSheet(models.Model): ticker = models.ForeignKey(Security, on_delete=models.CASCADE, related_name="balance_sheet") date = models.DateField(default=datetime.date) but I receive the following error when trying to add a record in the admin panel TypeError at /admin/financials/balancesheet/add/ function missing required argument 'year' (pos 1) Request Method: GET Request URL: http://localhost:8000/admin/financials/balancesheet/add/ Django Version: 3.1 Exception Type: TypeError Exception Value: function missing required argument 'year' (pos 1) Exception Location: /usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 831, in get_default Python Executable: /usr/local/bin/python Python Version: 3.7.8 Python Path: ['/code', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages'] Server time: Sun, 09 Aug 2020 11:40:48 +0000 -
Save tuple in django model... it does but shows duplicate error
I have models: #model class A(models.Model): # some fields . . class B(models.Model): # some fields . . class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) state = models.BooleanField(default=False, blank=False) objects = models.Manager() class Meta: constraints = [ models.UniqueConstraint(fields=['a', 'b'], name='ccc') ] in my view i have method myMethode: def myMethod(request): #some lines of code . . c_obj = C() c_obj.a = a_obj # a_obj object of class A c_obj.b = b_obj # b_obj object of class B c_obj.state = True if (some condition) else False c_obj.save() when i'm trying to save a tuple of class C, it DOES and saves tuple! but shows this ERROR: # ERROR django.db.utils.IntegrityError: (1062, "Duplicate entry '3-2' for key 'QA_c.ccc'") i don't understand what is wrong? and why it shows this error? -
need help on Django model form select_related
Django render making many queries even after select_related and prefetch_related looking to speed up bill edit rendering select_related and prefetch_related not working views.py @login_required def bill_edit(request, bill_id): bill = Bill.objects.select_related('station', 'transport').prefetch_related('transport__station').get(id=bill_id) ## filter(id=bill_id)[0] #.get(id=bill_id) form = BillEditForm(instance=bill) if request.method == 'POST': form = BillEditForm(request.POST, instance=Bill.objects.get(id=bill_id)) if form.is_valid(): form.save() return redirect(reverse('bills_list')) context = { 'bill': bill, 'form': form } return render(request, 'voucher/bill_edit.html', context=context) models.py class Bill(models.Model): billDate = models.DateField(default=datenow) number = models.CharField(max_length=16, unique=True) station = models.ForeignKey(Station, on_delete=models.CASCADE, blank=True, null=True) transport = models.ForeignKey(Transport, on_delete=models.CASCADE, blank=True, null=True) billAmount = models.IntegerField(blank=True, default=0) class Transport(models.Model): name = models.CharField(max_length=25) station = models.ManyToManyField(Station, related_name='stationTransport', through='TransportStation') class TransportStation(models.Model): transport = models.ForeignKey(Transport, related_name="trpt", on_delete=models.CASCADE) station = models.ForeignKey(Station, related_name="stn", on_delete=models.CASCADE) freight_rate = models.PositiveIntegerField(default=0) class Station(models.Model): name = models.CharField(max_length=25) forms.py class BillEditForm(ModelForm): class Meta: model = Bill fields = '__all__' bill_edit.html <form action="{% url 'bill_edit' bill.id %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-outline-primary">Submit</button> </form> here is the screen shot where 261 queries made for render Django debug toolbar image -
Django add previous date to model DateField
I have a simple model that I want to add a previous date as the DateField. I am defining a function but it will not allow me to input the date and I end up with a TypeError when trying to add to the db. how can I add a previously occuring date to a DateField in django ? class BalanceSheet(models.Model): ticker = models.ForeignKey(Security, on_delete=models.CASCADE, related_name="balance_sheet") def return_date(yyyy, mm, dd): return datetime.date(yyyy, mm, dd): date = models.DateField(default=return_date) -
Django multiple pictures one product
I have the following problem: I'm programming a webshop and every product has multiple pictures. So this is a one-to-many relation, where the foreign key is in the picture model. However, if i register the models "product" and "picture" to the admin site the user obviously needs to add a product then navigate to the pictures and add a picture and referencing a product within the picture creation process. Instead of this i want the user to be able to create a product and then add multiple pictures in the dropdown menu inside the same subpage inside admin-pannel. How can i accomplish this behaviour? It should look exact like it would with a many-to-many relation. But i don't want to use ManyToManyField sience i already tried it and then it lead to logical issues. models.py: class Picture(models.Model): picture = models.ImageField(upload_to='shop/static/shop/images/') product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.picture.url class Product(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name admin.py admin.site.register(Picture) admin.site.register(Product) -
Filtering X most recent entries in each category of queryset
Question is regarding filtering X most recent entries in each category of queryset. Goal is like this: I have a incoming queryset based on the following model. class UserStatusChoices(models.TextChoices): CREATOR = 'CREATOR' SLAVE = 'SLAVE' MASTER = 'MASTER' FRIEND = 'FRIEND' ADMIN = 'ADMIN' LEGACY = 'LEGACY' class OperationTypeChoices(models.TextChoices): CREATE = 'CREATE' UPDATE = 'UPDATE' DELETE = 'DELETE' class EntriesChangeLog(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, ) object_id = models.PositiveIntegerField( ) content_object = GenericForeignKey( 'content_type', 'object_id', ) user = models.ForeignKey( get_user_model(), verbose_name='user', on_delete=models.SET_NULL, null=True, blank=True, related_name='access_logs', ) access_time = models.DateTimeField( verbose_name='access_time', auto_now_add=True, ) as_who = models.CharField( verbose_name='Status of the accessed user.', choices=UserStatusChoices.choices, max_length=7, ) operation_type = models.CharField( verbose_name='Type of the access operation.', choices=OperationTypeChoices.choices, max_length=6, ) And I need to filter this incoming queryset in a such way to keep only 4 most recent objects (defined by access_time field) in each category. Categories are defined by ‘content_type_id’ field and there are 3 possible options. Lets call it ‘option1’, ‘option2’ and ‘option3’ This incoming queryset might contain different amount of objects of 1,2 or all 3 categories. This is can’t be predicted beforehand. DISTINCT is not possible to use as after filtering operation this queryset might be ordered. I managed to get 1 … -
How to join two table in django admin
In django i have two different tables 1st is customer and second is customerIp. In customer table customer id, name, etc are there and in customerIp customerid, ip, created_at fields are there i want to display all rows from custoerIp table with customer name in django admin and in my html page also please guide me how can i join these two table for admin panel as well as for html page Model.py class CustomerModel(models.Model): customer_id = models.CharField(max_length=200, unique=True) customer_group_id = models.CharField(max_length=200, unique=True) firstname = models.CharField(max_length=300) lastname = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) mobile = models.PositiveIntegerField() password = models.CharField(max_length=300) newsletter = models.BooleanField(blank=False) default_address_id = models.PositiveIntegerField() ip = models.GenericIPAddressField() status = models.BooleanField(blank=False) token = models.CharField(max_length=300) mobile_login = models.BooleanField(blank=False) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True) myobj = CustomMannager() class CustomerIp(models.Model): customername = models.ForeignKey(CustomerModel,related_name='name',on_delete=models.CASCADE) customer_id = models.PositiveIntegerField() ip = models.GenericIPAddressField() created_at = models.DateTimeField(auto_now=True) admin.py from django.contrib import admin from .models import CustomerModel,CustomerIp # Register your models here. class CustomerList(admin.ModelAdmin): list_display = ['customer_id', 'customer_group_id', 'firstname', 'lastname', 'email', 'mobile', 'password', 'newsletter', 'default_address_id', 'ip', 'status', 'token', 'mobile_login', 'created_at', 'updated_at'] class CustomerIpList(admin.ModelAdmin): list_display = ['customer_id', 'ip', 'created_at',] admin.site.register(CustomerModel, CustomerList) admin.site.register(CustomerIp, CustomerIpList) Output Required In admin panel customer name, customer id, Ip, created_at These fields i want to … -
Class based update view No Userinfo matches the given query
I am trying to update data of models using class based updateview but it's returning No Userinfo matches the given query. #views.py class Usersinfoupdate(LoginRequiredMixin, UpdateView): model = Userinfo form_class = UserinfoForm fields = '__all__' template_name = "user.html" def get_success_url(self): return reverse('user_info', kwargs={'pk': self.request.user.pk}) The userinfo model class Userinfo(models.Model): user = models.ForeignKey(accountUser, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) bio = models.TextField(max_length=800) fb = models.URLField(blank=True) insta = models.URLField(blank=True) twitter = models.URLField(blank=True) other = models.URLField(blank=True) def __str__(self): return self.user.username urls.py urlpatterns = [ path('user/<int:pk>/', views.Usersinfo.as_view(), name='user_info'), path('user/<int:pk>/edit', views.Usersinfoupdate.as_view(), name='user_update'), ]