Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to access form inputs which are looped with django?
I have this form to answer a survey a user received in a html file. <form method="POST" action="/answerSurvey"> <ol> {% for q in questions %} <li> <label for="questionBody"><b>{{ q.body }}</b></label> <ul style="list-style: none;"> {% for a in answers %} {% if q.id == a.question_id %} <li><input type="checkbox" name="{{ a.id }}"> {{ a.body }}</li> {% endif %} {% endfor %} </ul> </li> {% endfor %} </ol> <button type="submit">Submit</button> </form> I want to create a function to receive the user input to see which questions got ticked. Something similar to @app.route('/answerSurvey', methods=['GET', 'POST']) @login_required def answerSurvey(): question_answers = request.form['something'] so I can store them in a database table with the associated answer.id. -
ValueError: Unable to configure handler 'file_store'
I tried to setup handler of django logging for display my filtters in a file; This is my handler in settings.py: 'handlers': { 'file_store': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'phones.log'), 'formatter': 'verbose' } }, and this one is my logger in settings.py: 'loggers': { 'root': { 'phones': { 'handlers': ['file_store'], 'level': 'INFO', }, } } I interested to display my logger messages in a file in the name phones.log, but after I run ./manage.py runserver command, it shows me this error messeage: ValueError: Unable to configure handler 'file_store' -
Custom Django User with Default values
I am using Django 3.2 with Restframework. I have created a custom user for my project and given default values in Models for some fields. But the default values are not accepted when the POST request is made. Like for example, "date_joined" is left blank, then it has to be today's date, but while making request from postman, its taking it as mandatory field. What am I doing wrong? Models.py class MasterUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) date_of_birth = models.DateField(default="2020-10-10") is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) firstname = models.CharField(max_length=100,blank=True) lastname = models.CharField(max_length=100,blank=True) is_member = models.BooleanField(default=False) date_joined = models.DateField(default=datetime.now) last_signed_in = models.DateTimeField(default=datetime.now) is_subscription = models.BooleanField(default=True) category = models.CharField(max_length=100, null=True) contact = models.CharField(max_length=100, blank=True, unique=True) membership_id = models.CharField(max_length=100, blank=True) objects = MyUserManager() serializer class RegisterUserSerializer(serializers.ModelSerializer): ... ... def save(self): timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) account = MasterUser( email = self.validated_data['email'], firstname = self.validated_data['firstname'], lastname = self.validated_data['lastname'], is_member = self.validated_data['is_member'], date_joined = self.validated_data['date_joined'], last_signed_in = self.validated_data['last_signed_in'], is_subscription = self.validated_data['is_subscription'], category = self.validated_data['category'], contact = self.validated_data['contact'], membership_id = hashString(str(timestamp)) ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password doesnt matches'}) account.set_password(password) account.save() return account views.py def registration_view(request): if request.method == "POST": is_member = request.POST.get('is_member') timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) serializer = RegisterUserSerializer(data= request.data) data … -
using email and username for login in django
what do I do to put username and email login together in django? I mean something like: enter your Username/Email I tried this before: log = authenticate(request, username=username or email=email, password=password) but I faced an error is there any suggestion? -
Using a multi-table inheritance model as a through table
I'm trying to use a multi-table inheritance model as a through table, as shown below: class Base(models.Model): ... class Through(Base): ... class RelatedModel(models.Model): ... class Model(models.Model): field = models.ManyToManyField(RelatedModel, through='Base') instance = Model.objects.get(pk=1) related = RelatedModel.objects.get(pk=1) instance.add(related) # ValueError: Can't bulk create a multi-table inherited model However, I keep running into an error when adding a model to the ManyToMany relationship, as to how multi-table inheritance models cannot be bulk created. Is there any way around this? ManyToManyField.add doesn't take a bulk argument so it doesn't seem to be possible to disable bulk creation there. Does anyone know of a workaround for this without getting rid of the inheritance? -
django.db.utils.OperationalError: no such table: themes_theme
Django = 3.2.3 from django.core.exceptions import ValidationError from django.forms import ModelForm from themes.models import Theme class ThemeForm(ModelForm): def clean_archived(self): number_of_active_themes_without_current_instance = len(Theme.objects.filter(archived=False).exclude(id=self.instance.id)) number_of_active_themes_with_current_instance = number_of_active_themes_without_current_instance + int( self.instance.archived) if number_of_active_themes_with_current_instance > 1: raise ValidationError("Only one active theme is possible.") return self.cleaned_data['archived'] class Meta: model = Theme exclude = [] ########################################################################### from django.core.exceptions import ValidationError from django.forms import ModelForm from themes.models import Theme class ThemeForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.active_other_themes = Theme.objects.filter(archived=False).exclude(id=self.instance.id) def clean_archived(self): number_of_active_themes_without_current_instance = len(self.active_other_themes) number_of_active_themes_with_current_instance = number_of_active_themes_without_current_instance + int( self.instance.archived) if number_of_active_themes_with_current_instance > 1: raise ValidationError("Only one active theme is possible.") return self.cleaned_data['archived'] class Meta: model = Theme exclude = [] The former code inflicted the error after I did makemigrations: File "/home/michael/PycharmProjects/articles_outer/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: themes_theme Well, the latter code works with migrations. Could you explain to me why the former code is erroneous whereas the latter code is fine? -
Problem while deploying a webapp toheroku
I've been trying to deploy a webapp written in django to heroku but there always is an error: remote: Building source: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: e533e6e087af4e4a8897664c179c241ddd2833c3 remote: ! remote: ! We have detected that you have triggered a build from source code with version e533e6e087af4e4a8897664c179c241ddd2833c3 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku :main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to radiant-lake-54163 I tried somethings. Firstly, I created a new account in heroku and then tried and I still received … -
writing django queries for one to many relationships, (django query and taggit)
So i have a model called "Ad", for the sake of my question, let's say this is my model: from django.core.validators import MinLengthValidator from taggit.managers import TaggableManager title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) tags = TaggableManager(blank=True) where TaggableManager is from django-taggit module In my views, i am implementing search, which gives result filtering results based on title field: from django.db.models import Q class view(View): def get(self, request): strval = request.GET.get("search", False) if strval : query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) ad_list = Ad.objects.filter(query).select_related().order_by('-updated_at')[:10] What i wish to add is: if a user types in keywords which are from a tag rather than a tittle, the result should display the Ads which have those tags. I know it is possible to add this feature as i saw the support for ManyToMany Fields in django queries, but i am not sure if that would work with django taggit. Can someone please help me with this? -
How to convert image url into ImageField - Django
am creating a donation web application. Users are able to fill out a form and there donation is submitted into the database, I was wondering how I can have the user submit a url of an image and save it in the database, and then render it on another page. For example, if the user fills out the form and submits a url like https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80, how would I save this to the database as an Image and not a URL? I should then be able to render it out on another page. Html Form: <label class="label-input100" for="image">Image</label> <div class="wrap-input100"> <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required> <span class="focus-input100"></span> </div> My view: (There is a lot of stuff here that do not pertain to my question, I just included it in case it is needed) def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] date = datetime.datetime.now().date() ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, date = date ) ins.save() # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') … -
Getting error DecimalFields must define a 'max_digits' attribute
I'm having a problem with these DecimalField types. I have the next model: class Mediciones(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=30, verbose_name='Nombre dispositivo') dispositivo = models.ForeignKey(Dispositivos, on_delete=models.CASCADE) temperatura = models.DecimalField(max_digits=5, decimal_places=2) humedad = models.DecimalField(max_digits=5, decimal_places=2) ruido = models.DecimalField(max_digits=7, decimal_places=2) c02 = models.DecimalField(max_digits=7, decimal_places=2) alerta = models.BooleanField(null=False) fecha = models.DateTimeField(verbose_name="Fecha", blank = False) As you can see, I have four DecimalField, and all of them have defined both "max_digits" and "decimal_places", and max_digits is greater than decimal_places. Despite of that, I'm getting errors "DecimalFields must define a 'max_digits' attribute." when I try to make a migration. Do you know why? Thanks in advance! -
Optimal way to create test requests for Python (Django) REST APIs
I have an API/microservice written in Django which is computational in nature. Depending on the request parameters, the API does some computations and gives an output. I need to test the API by simulating various possible combinations of requests and corresponding responses. A few points to consider about my API: The request consists of around 20 parameters. Each parameter can be of different type, for eg. binary, lists, dictionary, etc. Based on the whole input request, the API does some computation which I need to test. Example of a dummy request with just 3 params: { param1: True/False, param2: list of strings param3: list of dictionaries } Each combination of parameter gives a different output. For example in the above request with 3 params, I can have 2 scenarios to test - by putting param1 as True and False. Similarly I can pass various strings in param2 list ( I have predefined set of eligible strings) and so on. Thus with around 20-25 parameters, I have a lot of requests possible with different combinations of parameters taken at a time. Currently I am storing each request in a file by manually creating the request for various combinations possible. Then I … -
Multiple Login Backend with django rest auth
I am using Django rest auth token authentication for a particular project. There are four different types of users (agent, admin, buyer, seller). I have implemented a custom login serializer with a contact number & password for login. But actually, for agent users, I want only employee id to authenticate the user, I have created the unique employee id. but don't know how to implement a different login backend for this particular user. can you share some ideas for this? For buyer, seller, the default login backend working with no issue. But for agents, I need to implement differently. -
Django - handling guest users
I have a general question about how to best handle the logic for guest users. What I have is a website (sort of HacknPlan clone) and when a non-registered (guest) user accesses the page, he/she can interact with the page (create tasks,...) the same as a registered one, but with limitations. I'm using this logic to determine and create a guest user in a database: class Account: def __init__(self, request): self.request = request def getUser(self): if not self.request.user.is_authenticated: ip = get_client_ip(self.request) if UserAccount.objects.filter(ip_address=ip).exists(): return UserAccount.objects.get(ip_address=ip) random_username = f"{randomString(10)}_guest" random_email = f"{randomString(5)}_guest@example.com" guest_user = UserAccount.objects.create( username=random_username, email=random_email, ip_address=ip, is_active=False ) return guest_user else: return self.request.user As you can see, I'm also adding the IP address to the guest user, so when the guest refreshes or revisits the page, I can get this particular guest from the database. Previously, instead of saving its IP, I was saving the session key, but I noticed the key was changing when for example I would log in with an already registered user. This was causing the creation of a new guest user every time I would log out a registered user. If the guest uses chooses to become a registered one, this I how the … -
Django get_FOO_Display() for range list choices
STATUS_APPROVE, STATUS_REJECT, STATUS_PROC, STATUS_PEND, STATUS_PAID = range(5) STATUS_CHOICES = ( (STATUS_APPROVE, 'Approved'), (STATUS_REJECT, 'Rejected'), (STATUS_PROC, 'Processing'), (STATUS_PEND, 'Pending'), (STATUS_PAID, 'Paid'), ) class ExpenseClaim(TimeStampedModel): status = models.PositiveIntegerField(default=STATUS_PEND, choices=STATUS_CHOICES, blank=False) class MileageClaimSerializer(serializers.ModelSerializer): status = serializers.ChoiceField(choices=STATUS_CHOICES) I cannot work out a way to get foo display for a choice list with range. So the range keys are used to store the point in list. I need the serializer to return the word and not the key. -
How to add a commented line with relative path to the first line of vim file
I am making a Django web app using Vim, and I want to add a commented line to the top of each file, I open or create, with its relative path. For example: # config/urls.py, using c-r and c-% for its relative path. So far I've been working on this bash script. #!/bin/bash echo "Enter file name" read newfile if [[ $newfile = *.py ]]; then `touch $newfile && echo "# $PWD"/"$newfile">>$newfile` vim $newfile; elif [[ $newfile = *.html ]]; then `touch $newfile && echo "<!-- $PWD"/"$newfile -->">>$newfile` vim $newfile; elif [[ $newfile = *.css ]]; then `touch $newfile && echo "/* $PWD"/"$newfile */">>$newfile` vim $newfile; else vim $newfile fi That opens with # /home/menashe/testdir/test1.py. How do I only add the relative path testdir/test1.py? Is it possible to put the Vim commands in the script? How do I append a comment to the first line of a file that isn't empty? Thank you -
Resizing images with django-resized
I'm using django-resized to reduce sizes of images when they are uploaded to AWS S3. The resizing works fine when the image is wider than its height. However, when image height is bigger than its width then the output image is rotated by 90 degrees and its width is bigger than its height. models.py from django_resized import ResizedImageField class Catch(models.Model): fish_type = models.CharField("Fish Type", max_length=50, choices=fish_choices, default="Carp") catch_id = models.AutoField(primary_key=True) weight = models.DecimalField("Weight", max_digits=5, decimal_places=2) length = models.DecimalField("Length", max_digits=5, decimal_places=2, blank=True, null=True) datetime = models.DateTimeField("Catch Time", auto_now=False, auto_now_add=False) image = ResizedImageField(size=[1080, 1350], quality=95, null=True, blank=True, default="default_img.png", upload_to="catch_images/") fisherman = models.ForeignKey(Fisherman, on_delete=models.CASCADE) trip = models.ForeignKey(Trips, on_delete=models.CASCADE) hookbait_name = models.CharField('Csali megnevezése', max_length=120, blank=True, null=True) hookbait = models.ForeignKey(HookBait, on_delete=models.SET_NULL, blank=True, null=True) settings.py DJANGORESIZED_DEFAULT_KEEP_META = True DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG' DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"} DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True I only want to reduce sizes of images while they're preserving the aspect ratio. Thanks in advance for any help. -
OpenTelemetry Python Auto Instrumentation in Django is giving error
Below is the setup I have done: export OTEL_TRACES_EXPORTER=otlp export OTEL_RESOURCE_ATTRIBUTES=service.name=Communication export OTEL_EXPORTER_OTLP_HEADERS=x-scope-orgid=XXXXX export OTEL_PYTHON_LOG_CORRELATION=true export OTEL_LOG_LEVEL=debug export OTEL_PYTHON_LOG_LEVEL=debug export DJANGO_SETTINGS_MODULE=nsl_vcs.settings.docker export OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS='path_info,content_type' export OTEL_PYTHON_TRACER_PROVIDER=sdk_tracer_provider export OTEL_PYTHON_METER_PROVIDER=sdk_meter_provider pip3 install opentelemetry-sdk pip3 install opentelemetry-instrumentation-django pip install opentelemetry-exporter-otlp opentelemetry-bootstrap --action=install opentelemetry-instrument python3 manage.py runserver --settings=nsl_vcs.settings.docker 0.0.0.0:7013 --noreload All the commands are successful and I didnt see any error. But when I fire the REST Call, then its giving below error. Please note that I am not getting the error without tracing: opentelemetry-instrument python3 manage.py runserver --settings=nsl_vcs.settings.docker 0.0.0.0:7013 --noreload 2021-07-13 10:38:55,169 DEBUG [/home/nsluser/.local/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py] [sitecustomize.py:82] [trace_id=0 span_id=0 resource.service.name=Communication] - Instrumented logging 2021-07-13 10:38:55,197 DEBUG [/home/nsluser/.local/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py] [sitecustomize.py:82] [trace_id=0 span_id=0 resource.service.name=Communication] - Instrumented grpc_client 2021-07-13 10:38:55,199 DEBUG [/home/nsluser/.local/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py] [sitecustomize.py:82] [trace_id=0 span_id=0 resource.service.name=Communication] - Instrumented grpc_server path2 /home/nsluser/base/code/communications/nsl_vcs/payment_gateways/templates ENV docker 2021-07-13 16:08:55,303 DEBUG [/home/nsluser/.local/lib/python3.8/site-packages/opentelemetry/instrumentation/auto_instrumentation/sitecustomize.py] [sitecustomize.py:82] [trace_id=0 span_id=0 resource.service.name=Communication] - Instrumented django Performing system checks... ENV From base import docker System check identified no issues (0 silenced). July 13, 2021 - 16:08:55 Django version 2.1, using settings 'nsl_vcs.settings.docker' Starting development server at http://0.0.0.0:7013/ Quit the server with CONTROL-C. Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 117, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/home/nsluser/.local/lib/python3.8/site-packages/opentelemetry/instrumentation/django/middleware.py", line 174, … -
JSON data saving using Django 3.3
As we know, Django=3 is supporting JSONField . I am trying to save JSON data in my Django Project using JavaScript, i have take data in a input field which looks like: [{"id":1,"Name":"Antenna","Pieces":"","Weight":"","Weight Types":"","Quantity":"12", "Cargo Charge":"12","Customs Charge":"12"}, {"id":2,"Name":"Soap","Pieces":"12","Weight":"12","Weight Types":"","Quantity":"", "Cargo Charge":"12","Customs Charge":"12"}] From the input field I save the data to MySql database using . product_list = self.request.POST['product_list_json'] Hence, product_list_json is the name of the inout field. But the saving data is given different view, the saved data look like: "[{\"id\":1,\"Name\":\"Antenna\",\"Pieces\":\"\",\"Weight\":\"\",\"Weight Types\":\"\", \"Quantity\":\"12\",\"Cargo Charge\":\"12\",\"Customs Charge\":\"12\"}, {\"id\":2,\"Name\":\"Soap\",\"Pieces\":\"12\",\"Weight\":\"12\",\"Weight Types\":\"\", \"Quantity\":\"\",\"Cargo Charge\":\"12\",\"Customs Charge\":\"12\"}]" The problem is that, data is saving with additional " \ " . What can i do to solve this? -
Django Query ManyToMany field as list
I want to query a manytomany field an save it directly as a list. Here is my query: inventory_list = list(Inventory.objects.filter(inventory_plant__plant_name = ikey ,inventory_product__pc1_product=ikey2).values( 'inventory_number', 'inventory_name', 'inventory_process_name__process_name' )) Here my result: inventory list = [{'inventory_number': 1211267, 'inventory_name': 'Käfig1', 'inventory_process_name__process_name': 'Turning'}, {'inventory_number': 1211267, 'inventory_name': 'Käfig1', 'inventory_process_name__process_name': 'Grinding'}, {'inventory_number': 1211267, 'inventory_name': 'Käfig1', 'inventory_process_name__process_name': 'Heat Treatment'}, {'inventory_number': 1217729, 'inventory_name': 'Käfig2', 'inventory_process_name__process_name': 'Grinding'}] What I want is, that the processes are directly in a list, depending on the 'inventory_number': inventory_list = [{'inventory_number': 1211267, 'inventory_name': 'Käfig1', 'inventory_process_name__process_name': ['Turning', 'Grinding', 'Heat Treatment']}, {'inventory_number': 1217729, 'inventory_name': 'Käfig2', 'inventory_process_name__process_name': 'Grinding'}] Here is my Model: class Inventory(models.Model): inventory_number = models.IntegerField(verbose_name="Inventory Number", unique=True) inventory_name = models.CharField(max_length=100, verbose_name="Inventory Name") inventory_process_name = models.ManyToManyField(Process, verbose_name="Processes") inventory_plant = models.ForeignKey(Plant, verbose_name="Plant", on_delete=models.CASCADE) inventory_product = models.ManyToManyField(TPZProductCluster1, verbose_name="TPZ Product Cluster 1") inventory_pot_per_shift = models.IntegerField(validators= [MaxValueValidator(600), MinValueValidator(0)], verbose_name="Pot per Shift in min") inventory_working_weeks_per_year = models.IntegerField(validators= [MaxValueValidator(52), MinValueValidator(0)], verbose_name="Working Weeks per year") inventory_comments = models.TextField(max_length=1000 ,verbose_name="Comments", blank=True) inventory_responsible_person = models.ForeignKey(ResponsiblePerson, verbose_name="Responsible Person", on_delete=models.CASCADE) updated_at = models.DateField(auto_now=True) class Meta: ordering = ['inventory_number'] verbose_name = 'Inventory' verbose_name_plural = 'Inventories' def processes(self): return ', '.join([p.process_name for p in self.inventory_process_name.all()]) def products(self): return ', '.join([p.pc1_product for p in self.inventory_product.all()]) def __str__(self): return str(self.inventory_number) + ', ' + self.inventory_name Is there a direct way … -
im using django and im unable to save the data of this checkbox
im using django and im unable to save the data of this checkbox using javascript. Kindly help me in this case. from my side its very difficult to handle <input type="checkbox" id="allowance" style=" zoom: 1.5;"> function savecontract(){ allowance = $('#allowance').val(); var data = new FormData data.append("allowance", allowance) var r = false; $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", contentType: false, processData: false, url: '/Employee/savecontract/', data: data, async: false, success: function (response) { if(response.status == "success"){ $('#cid').val(response.id) r=true; } else{ swal("Error","Something Went Wrong!","error") } }, error: function () { swal("Error","Something Went Wrong!","error") } }); return r; } }); -
How to update image of user in react-django using reducer (react-redux)
I am new to React, and I know how to work with django but not with rest framework, I have been following one tutorials in which he updated users basic information but not profile picture and I want to update profile picture so how can I ? Any help is appreciated thank you. -
Executing a Python program in Django with every new entry is posted in REST API
I'm fairly new to Django. I am creating an application where I am posting images from flutter application to Django REST API. I need to run a python script with the input as the image that gets posted in the API. Does anyone have any idea about this? -
can't use id and str:username together
I created a blog where you can go to the user's profile and see their posts. You can also see each post separately. However, I cannot use such url path path ('<str: username> / <post_id> /', post_view, name = 'tak'). This results in Reverse for 'tak' with arguments '(44,)' not error found. here is my code views.py def user_posts(request, username): posts = Post.objects.filter(author__username=username) return render(request, 'profile.html', {'posts':posts}) def post_view(request,post_id): post = Post.objects.get(id=post_id) context={'post':post} return render(request, 'post.html',context) urls.py path('<str:username>/', user_posts, name='profile'), path('<str:username>/<post_id>/', post_view, name='tak'), models.py class Post(models.Model): text=models.CharField(max_length=25) pub_date=models.DateTimeField('date published',auto_now_add=True) author=models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') # Create your models here. def __str__(self): return self.text profile.html {% extends 'base.html' %} {% block content %} {% for post in posts %} <ul><li> {{post}} <hr> <p> <a href="{% url 'tak' post.id %}">{{post}}</a></p> </li> </ul> {% endfor %} {% endblock content %} -
Hit counter for Django blog post
In my search to find a way to add hit counter to my blog posts without any third party library I found this answer on StackOverflow. However as I'm not a Django expert I can't figure out how to use that Mixin with my view. Here's how my model is defined: class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published')) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') And my views: def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) I would ask the user provided that answer, but he's inactive for more than 2 years. Appreciate your help. -
For Loop in Django template for nested dictionaries
I have a model with the following fields: name tag due_date I want to be able to present this data as follows in my template: tag1: -- Name1 -- Name2 tag2: -- Name3 -- Name4, etc. In order to do this, in my views.py function, I am first making a list of all the values within 'tag', and then using this list to put together a dictionary that groups all the instances as per the individual values in the list. For example, if this were a to-do app, the list would be tags such as ['home', 'office', 'hobby'...] and the final dictionary would look like: {'home': <QuerySet [<Task: Buy Milk>, <Task: Buy Food>]>, 'hobby': <QuerySet [<Task: Play guitar>, <Task: Read books>]>, 'office': <QuerySet [<Task: Send email>, <Task: Schedule Meeting>]>} Once I have this dictionary of dictionaries, I pass it on to template as context. def bytag(request): value_list = Task.objects.values_list('tag', flat=True).distinct() group_by_value = {} for value in value_list: group_by_value[value] = Task.objects.filter(tag=value) context = {'gbv': group_by_value} return render(request,'tasks/bytag.html', context) I have tried out these queries in the shell, and they work fine. So in the template, I am trying the following to loop over the data: {% block content %} {% for …