Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Is there any way in Django to create dynamic menu and sub-menu ??"
" Using Django, i want to create menu and sub-menu(i mean drop-down menu) " " If you have any source code in django for creating menu and sub-menu, please give me a link **** thanks in advance................................................................................................................................ " ### models.py from django.db import models # Create your models here. class Category(models.Model): category_name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) def __str__(self): return self.category_name class Sub_Category(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) Sub_category_name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) def __str__(self): return self.Sub_category_name class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) image = models.ImageField(upload_to='picture/') pub_date = models.DateTimeField(auto_now_add=True) description = models.TextField() def __str__(self): return self.title #### html page {% block content %} <h1 class="bg-success text-center">Home page </h1> <div class="row"> <div class="col-8"> {% for category in category_list %} <ul> <li>{{category.category_name}}</li> {% for sub_category in sub_category_list %} <ul> <li> {% if sub_category.category.id == id %} {{sub_category.Sub_category_name}} {% endif %} </li> </ul> {% endfor %} </ul> {% endfor %} </div> </div> </div> {% endblock %} ``` ### I want output will be like that... ### * Men Fashion * T-shirt * Pant * Men Fashion * Frog * beg -
how implement an efficient visits counter per page?
how implement an efficient visits counter per page? I've marketplace platform, but not a visits counter per product page, then, this is my question. what's is the better algorithm for implement this? I not think that this alghoritm is the better "update product set product.visits = (product.visits + 1) where ..." then, how? I'm accept sugestions Google Analytics? third party solutions? Alghoritm? thanks everyone Was developed in Django -
Send notification on post_save signal in django
I have a model called deposit and I am trying to send real time notification when a new row is added in table. Is it possible to do so using django-channels ? -
How to perform edit in inline_formset when its model contain multiple foreign key in it?
I used a form set to enter a schedule to course, When i try to edit the record it shows an error: inlineformset_factory() got multiple values for keyword argument 'form'. Model for that form contains multiple foreign key i tried to describe the foreign key fields in the inlineformset. views.py def edit_course_schedule(request,scheduleid): instance = CourseSchedule.objects.get(id=scheduleid) schedule_form = CourseScheduleForm() schedule_formset = inlineformset_factory( DynamicCoursePrice, CourseType, Course, CourseSchedule, can_delete=True, form=schedule_form, fk_name=('dynamic','course_type','course'), extra=0, max_num=1, fields= '__all__' ) schedule_form = CourseScheduleForm(instance=instance) scheduleformset = schedule_formset(prefix='schedule_formset',instance=instance) context = { 'scheduleid' : scheduleid, 'schedule_form' : schedule_form, 'schedule_formset' : schedule_formset, } return render(request,'myapp/edit_course_schedule.html', context) models.py class CourseSchedule(models.Model): dynamic = models.ForeignKey(DynamicCoursePrice, on_delete=models.CASCADE, blank=True, null=True) course_type = models.ForeignKey(CourseType, on_delete=models.CASCADE, blank=True, null=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateField("Start Date", blank=True, null=True) end_date = models.DateField("End Date", blank=True, null=True) hours = models.IntegerField("Hours", blank=True, null=True) time = models.CharField("Time interval", max_length=255,blank=True, null=True) day = models.CharField("Day", max_length=255,blank=True, null=True ) i want to edit schedule in formset view, so that i can add or remove new schedules to a course. please help me to find a way to solve this problem. -
How can I prefetch_related() everything related to an object?
I'm trying to export all data connected to an User instance to CSV file. In order to do so, I need to get it from the DB first. Using something like data = SomeModel.objects.filter(owner=user) on every model possible seems to be very inefficient, so I want to use prefetch_related(). My question is, is there any way to prefetch all different model's instances with FK pointing at my User, at once? -
How to serve static files for the frontend generated by ReactJs build in a django project?
I have a set of static files generated by ReactJs build command and which will serve as a front-end for my Django project. Both the Django application and react files will serve from the same server. How do I serve these static files as my front-end for the Django application and write urlpatterns properly - if required. I tried to copy all the files from the build folder to static/frontend folder My static/frontend folder has static/frontend /static /js /css index.html manifest.json ... settings.py is as follows STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] -
The empty path didn't match any of these
enter image description here enter code here path('admin/',admin.site.urls) path('notes/', include('notes_app.urls') from django.contrib import admin from django.urls import include , path -
How to pass the user id to a custom password hasher in Django?
I have migrated password hashes, that are salted using the user id. I have a custom hasher that extends PBKDF2SHA1PasswordHasher. But the parameters of the methods do not include any user info. class MyHasher(PBKDF2SHA1PasswordHasher): def encrypt(self, password, salt, iters, keylen, digestmod): How do I retrieve the user id inside the encrypt method, so I can correctly verify the incoming password? -
How can the router path be accessed by html in "Django rest framework"?
I am trying to build a simple blog in Django Rest Framework. I want to add like count by pressing the button on the list page to send post method to the server. This is views.py class BlogListView(viewsets.ModelViewSet): serializer_class = BlogSerializer renderer_classes = [JSONRenderer, TemplateHTMLRenderer] def create(self, request, *args, **kwargs): user = request.user like_id = request.POST.get('pk', None) add_like = Like.objects.get(pk=like_id) if add_like.likes.filter(id=user.id).exists(): add_like.likes.remove(user) else: add_like.likes.add(user) context = {'likes_count': add_like.total_likes} serializer = BlogSerializer(context) return Response(serializer, content_type='application/json') This is url. router = DefaultRouter() router.register('dashboard', views.ImitagramListView) app_name = 'imitagram' urlpatterns = [ path('', include(router.urls)), ] This is HTML. <button type="button" class="like" name="{{ like.id }}"> <script type="text/javascript"> $.('.like').click(function () { var pk = $(this).attr('name'); $.ajax({ type: "POST", url: "{% url 'imitagram:dashboard' %}", data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function (response) { id = $(this).attr('name'); $('#count'+pk).html('count: ' + response.likes_count); alert('success'); }, error: function (request.status.error) { alert('error'); } }); }) </script> But this url spits out this error. Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name. How can I get this resolved? -
update_or_create method raises IntegrityError
When using the update_or_create method, the error IntegrityError is raised. It also says "Violation of PRIMARY KEY constraint 'PK__Security__BCF928572A34AEAB'. Cannot insert duplicate key in object" I have tried adding the defaults=argument, adding the kwargs as a dict with **kwargs, and adding the Kwargs as parameters edit, created = MyTable.objects.update_or_create( SecurityIdentifier=places[0][0], EffectiveDate=places[0][1], defaults={places[0][2]: keyVals[0]} ) I am not sure why I am getting this error, Any help would be greatly appreciated! -
how to display foreign key value in django template?
Here I am filtering staffs by the joined year,month and organization name this code works fine also but the problem what i encountered is after selecting the year,month or organization option it performs the query well but in the select option there is not the value of selected month,year or organization. To display the selected organization,year or month in the select option I tried like this and with this it displays the organization pk but I want to display organization name instead of pk value. How can i display the organization name instead of pk in the select option here? Also i want to display month name instead of month value. It is working fine for year value. views.py year = request.GET.get('year') month = request.GET.get('month') # month_name = calendar.month_name[int(month)] organization = request.GET.get('organization') print('org',type(organization)) present_year = datetime.datetime.today().year year_list = range(2015, present_year + 1) organizations = Organization.objects.all() if not year and not organization and not month: messages.info(request, 'Nothing selected to filter.') return redirect('organization:view_staff_users') if year and month and organization: staffs = Staff.objects.filter(Q(joined_date__year=year) & Q(joined_date__month=month) & Q(organization=organization)) return render(request, 'organization/view_staff_users.html', {'staffs': staffs, 'year': year, 'month': month, 'organization': organization,'present_year':present_year,'years_list':year_list,'organizations':organizations}) template <form action="{% url 'organization:filter_staffs' %}" class='form-inline' > <select name="year"> <option {% if year %} … -
Deploy Django on Azure (Windows OS)
I try to deploy django web app about 1 month but it wasn't working. I can deploy it on Linux but Linux have no "MySQL in app". so I use Windows. Howerver, I can't fint "startup command" in Windows. Moreover, I have no permission to install package (i use cmd via kudu => i use python -m pip install -U --user -r requirements), so I can't run "gunircorn ...", I can't use pip install, .... Does anyone help me deploy Django on windows web app. I extremly tired ~~ it is difficult to deploy ~~ I deploy successfully on Linux (Azure webapp) -
TypeError at / context must be a dict rather than RequestContext. A bit strange case
I had an application that was build on Django 1.9 but now I have upgraded it to 2.2. Well, I have encountered a strange error and I'm unable to solve it using the existing similar solutions. In my case, we are fetching the templateResponse from a different file then the built in one [Say x.py]- class TemplateResponse(DefaultResponse): """A normal response involving data that can be sent to fill in a template. Since the template is specific to HTML responses, when a JSON response is desired, this class is indistinguishable from DefaultResponse.""" def __init__(self, template, data, status=200): self.data = data self.template = template self.status = status [Base.py]- def home(guts): return TemplateResponse(template, {'c_sk': c_nt, 'd_sk_count': d_sk_count} Traceback Error - response = get_response(request) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/new_cl/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/new_cl/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /usr/lib/python3.6/contextlib.py in inner return func(*args, **kwds) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/new_cl/lib/python3.6/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/main/x.py in g response = seed.sprout(context, format) … ▶ Local vars /home/gaurav/Desktop/a Upgrade Work/a/main/x.py in sprout return self.sprout_html(context) … ▶ Local vars /home/gaurav/Desktop/a Upgrade … -
How to make it work datetime datetime strptime
can you tell me why it doesn't translate the date into numbers? import datetime from datetime import datetime as dt from datetime import timedelta from django.db import models from django.utils import timezone from django.utils.timezone import now def end_date(): return datetime.date.today() + timedelta(days=7).strftime("%d %B, %Y") def add_date(): add_date = datetime.date.today() data_object = dt.datetime.datetime.strptime(add_date, "%d %B, %Y").date() return data_object class add(models.Model): add_date = models.DateField('Дата додавання', auto_now_add=True) as I do not output from the DB string month -
Django: How to join two models and get the fields of both as a result?
My models : I have 2 (simplified) models: class Message(models.Model): mmsi = models.IntegerField() time = models.DateTimeField() class LastMessage(models.Model): mmsi = models.IntegerField() time = models.DateTimeField() From the most recent Message, I want to check if there are Message not in LastMessage. I can get the most recent Message like that : recent_messages = (Message.objects.distinct('mmsi') .order_by('mmsi', '-time')) From there, I have no idea how to extract the informations I want from recent_message and LastMessage. I'd typically like to have the information displayed like this : MMSI | Message_Time | LastMessage_Time I can do that with SQL like this for example : SELECT r.mmsi, r.time as Message_Time, l.time as LastMessage_Time FROM recent_message as r INNER JOIN core_lastmessage as l on r.mmsi = l.mmsi WHERE r.time <> l.time LIMIT 10; ┌─────────┬────────────────────────┬────────────────────────┐ │ mmsi │ message_time │ lastmessage_time │ ├─────────┼────────────────────────┼────────────────────────┤ │ 2000000 │ 2019-09-10 10:42:03+02 │ 2019-09-10 10:26:26+02 │ │ 2278000 │ 2019-09-10 10:42:24+02 │ 2019-09-10 10:40:18+02 │ │ 2339002 │ 2019-09-10 10:42:06+02 │ 2019-09-10 10:33:02+02 │ │ 2339004 │ 2019-09-10 10:42:06+02 │ 2019-09-10 10:30:07+02 │ │ 2417806 │ 2019-09-10 10:39:19+02 │ 2019-09-10 10:37:02+02 │ │ 2417807 │ 2019-09-10 10:41:18+02 │ 2019-09-10 10:36:55+02 │ │ 2417808 │ 2019-09-10 10:42:23+02 │ 2019-09-10 10:30:39+02 │ │ 2470087 … -
How to inform a variable with a random value in Django 2.0?
I have a client list in Django, and I need to return a random number between 1 and 999 for each new client. Also, for each new client and random number generated, I need to inform whether or not the client is approved to receive a certain amount of credit. And, if approved, there are some conditions as well. I need this for a job interview as a Junior dev, who's gonna be working with Django RESTFramework and, in the future, a little bit of React as well. This is what I have tried so far: income = float() score = random.randint(1, 999) aprovado = False credit = float() if 0 < score < 300: aprovado = False elif 299 < score < 600: aprovado = True credit = 1000 elif 599 < score < 800: aprovado = True if income < 2000: credit = 1000 else: credit = income * 0.5 elif 799 < score < 951: aprovado = True credit = income * 2 else: aprovado = True credit = 1000000 The logic is working properly in a separate (blank) file, but I cannot find a way to insert this to the Django app. The 'score' needs to … -
How to Unit or Integration Test in Python Django Models in Docker
I watched this tutorial on YouTube https://www.youtube.com/watch?v=6wxO8hRIP4w and it helped me in a way but the tutorial lacks on how to test a Django Model. Here's the code I've got so far: conftest.py import pytest from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter import requests @pytest.fixture(name="homepage") def fixture_homepage(function_scoped_container_getter) -> str: service = function_scoped_container_getter.get('app').network_info[1] base_url = f"http://{service.hostname}:{service.host_port}" retry = Retry( total = 30, backoff_factor=10, status_forcelist = [500, 502, 503, 504] ) session = requests.Session() session.mount('http://', HTTPAdapter(max_retries=retry)) return base_url first_test.py from requests import get pytest_plugins = ["docker_compose"] def test_one(): assert 1==1 def test_initial_ticket(homepage: str): print("HOMEPAGE: ", homepage) temp_str = get(homepage+"/admin").text #check if the pytest can already open the admin login page assert "Admin Login" in temp_str When I run pytest integration_tests/initial_user_receipt_test.py -s, both of the tests in first_test.py passes. I can also see that when I run this script, the docker image is built. However, I want to test inserting to a model.py which is located in the same folder as the integration_tests folder. I have tried importing the model directly and some classes inside it but it doesn't work. My folder structure is as follows: - Project - integration_tests - conftest.py - first_test.py - apps.py - models.py #contains a User class -
cv2 can't open base64 decoded video
I had the video uploaded to my django-rest project by send the base64 encoding, but i need to check if the upload file is video by trying to open it using cv2 but it doesn't accept it and throws an error class VideoBase64File(Base64FileField): ALLOWED_TYPES = ['Video'] def get_file_extension(self, filename, decoded_file): try: cv2.VideoCapture(decoded_file) return 'Video' except: return 'non-valid' I want a way to check if the 'decoded_file' is a video -
How am I able to create a file structure based on the current date?
I'm trying to log changes in our CMS to a logging file. I make use of the def logging_on_activity(). What I want is a new file for each day to keep the log records a bit organised. I've already tried to use the datetime package to manually edit the filename. def logging_on_activity(platform, appname, msg): import datetime now = datetime.datetime.now() if SITE_TYPE == SiteType.LOCAL: filename = 'path_to/../logs/' + str(now.__format__('%Y')) + '/' + str(now.__format__('%m')) + '/' \ + str(now.__format__('%d')) + '/logging.log' import datetime date = datetime.date.today().isoformat() time = datetime.datetime.now().strftime('%H:%m:%S') # Write to file with open(filename, 'a') as handle: handle.write("{0} {1} [ii] [{2:^19}] [{3:^19}] {4}\n".format(date, time, platform, appname, msg)) The error I get is: FileNotFoundError at .. [Errno 2] No such file or directory: 'itdb_tools/logs/2019/09/11.log' Example of what I want? Date: 2019/09/11 -> System is writing to: path_to/../logs/2019/09/11/logging.log Date: 2019/09/12 -> System is writing to: path_to/../logs/2019/09/12/logging.log I hope what I want to achieve is possible. Thanks in advance and I hope someone can help me in the right direction! -
How to click through a datatables row and populate a detailed view with the data in django?
I have a datatables table that works fine and is populated with data. I would like to allow the user to click on one of the rows, which would then take them to a detailed view which would display the record in a more user friendly, readable format. I have the form ready, I am just not sure how to go about passing all the row data through to the target view - I've got a general idea how to do it by POSTing it as an AJAX request, capturing it in my views.py and getting the data out of it and passing it to the target view but I am not sure on the actual implementation. Does anyone have any kind of similar example that achieves this? Many thanks! -
Having trouble linking two fields with one anoter, then implementing them to another model
I'm working on a project which helps users find jobs. So one of the models, named Oferta is used for details about a job. Someone who is looking for emplooyes, just completes a form which is based on this model, and people will be looking at it. Here's this model: class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.CharField(max_length=50) dataSolicitare = models.DateField(default=date.today) denumireMeserie = models.CharField(max_length=50) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return self.cor The COR field is the code asociated to a job. Also, denumireMeserie means job name. So these should be linked. Let's say, if code 1 means "Cook", these should be link - there will be no other job with a different code, or another job for code 1. So, in my opinion, these two fields should have a OneToOne relationship between them, if I'm not mistaken. But these codes and jobs need to be implemented in the database - so they need a model too. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.OneToOneField(CodCOR, max_length=50, unique=True, on_delete=models.CASCADE) … -
Unit tests in Django with requests for different subdomains
With the help of the package "django-hosts", we have implemented two subdomains for our Django project. One subdomain is "registration" and another one is "lectures". The Django admin interface is located and accessible from both subdomains. We have a unit test in which a POST request is sent to the "lectures" subdomain. However, in the testing environment, Django uses "testserver" domain, so our POST request is sent to the "testserver/en/reset-credentials" instead of "lectures.ourdomain.com/en/reset-credentials" because the "reverse" method is from "django-hosts" package and it returns URLs with these subdomains. We use "django_webtest" package for implementing these requests. We tried using "HTTP_HOST" parameter with "lectures.ourdomain.com" as its value. However, that does not seem to work as expected, because after a successful request (which worked in the beginning, before subdomain implementation) no email is sent, and our view which accepts this POST request sends an email by default. In the local, development environment, subdomains are defined in the hosts file for testing purposes. What would be the best approach for writing unit tests with Django project that has subdomains? -
Django doesn't provide a DB representation for AnonymousUser
I doing custom reset password with email confirm. path('password_reset', views.reset_password_view, name='password-reset'), path('password_reset/done', views.reset_password_done_view, name='password_reset_done'), path('reset/<uidb64>/<token>/', views.password_confirm_view, name='password_reset_confirm') def password_confirm_view(request, uidb64, token): context = {} if request.method == 'POST': form = SetPasswordForm(data=request.POST, user=request.user) if form.is_valid(): form.save() #I have error update_session_auth_hash(request, form.user) return redirect('password_reset_done') else: form = SetPasswordForm(user=request.user) context['form'] = form return render(request, 'mdm/registration/password_confirm.html', context) Exception Type:NotImplementedError Exception Value:Django doesn't provide a DB representation for AnonymousUser. How i can autherisation user? I think, I must used (uidb64, token). -
'str' object has no attribute 'verified'
I am including OTP in my project with twilio. But When verifying phone number it throws following error. phone.verified = True AttributeError: 'str' object has no attribute 'verified' models.py class User(AbstractBaseUser, PermissionsMixin): phone = models.CharField(max_length=15, unique=True) is_active = models.BooleanField(default = True) is_staff = models.BooleanField(default = False) USERNAME_FIELD = 'phone' key = models.CharField(max_length=100, unique=True, blank=True) verified = models.BooleanField(default=False) objects = UserManager() views.py @api_view(['GET']) def send_sms_code(request, format=None): time_otp = pyotp.TOTP(request.user.key, interval=10000) time_otp = time_otp.now() user_phone_number = request.user.phone client.messages.create( body="Your verification code is "+time_otp, from_=twilio_phone, to=user_phone_number ) return Response(status=200) @api_view(['GET']) def verify_phone(request, sms_code, format=None): code = int(sms_code) if request.user.authenticate(code): phone = request.user.phone phone.verified = True phone.save() return Response(dict(detail = "Phone number verified successfully"),status=201) return Response(dict(detail='The provided code did not match or has expired'),status=200) it sends me a verification code but When I am going to verify it does not work properly. I know where the problem is but How can I solve it? Any help would be appreciated! Thanks beforehand! -
Django migrations no changes detected after changing directory structure
I have created a Django project using this directory structure : bi3online __init__.py migrations __init__.py static templates media manage.py models.py urls.py views.py wsgi.py ... When I run python manage.py makemigrations and python manage.py migrate it only creates migrations for auth app and then when I try again it says no changes detected. It seems that migrations work only with apps but I'm not sure.