Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset filtering is not working after .union()
The Set-Up: I have a situation where I filter out several querysets as usually, all from the same User model. Eg: if my_events: for event in my_events: users = User.objects.filter(attended_events__event=event).values("first_name", "last_name", "email", "phone_number", "attended_events__event__start_dt", ) list_of_user_qs.append(users) Then I union the querysets like so: final_qs = QuerySet for qs in list_of_user_qs: final_qs = final_qs.union(qs, all=True) so far all good. I keep all the records because in the next step I am counting email occurrences. I spent some time on trying to count occurences of the same email as I would usually but after unioning some methods do not work as usual but that is fine, I will do it manually. For that, I have the following code: emails_used = [] for obj in final_qs: the_email = obj["email"] if the_email in emails_used: pass else: obj["total_count"] = len(final_qs.filter(email=the_email)) user_activity = final_qs.filter(email=the_email).order_by("-attended_events__event__start_dt").first() user_activity["total_count"] = final_qs.filter(email=the_email).count() user_activity["last_visit"] = user_activity["attended_events__event__start_dt"] qs_with_count.append(user_activity) emails_used.append(the_email) What I am trying to do here is first get user email (always present as it is required). Then I check if the user with the email was already evaluated (because the email would be in the emails_used list. Now comes the strange part. Question: Although I filter the final_qs with the current email … -
python django admin - error when list-filter value is empty
I am decorating change_list_template = "admin/user_joined_status.html") by specifying a template in Admin. If I specify a date using list_filter = [("user_join_dts", Date RangeFilter)] of django admin, the count value that I want for the specified date will come out. The problem is, as on the capture screen, [range_gte_date_time = datetime.strptime (range_gte_string, "%Y-%m-%d")] when the date is not selected. There is an error from here. I don't know how to avoid errors when I don't choose a date. Please help me... admin.py @admin.register(UserJoinedStatus) class UserJoinedStatusAdmin(admin.ModelAdmin): list_filter = [("user_join_dts", DateRangeFilter)] list_display = ["id", "user_join_dts"] change_list_template = "admin/user_joined_status.html" def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} pro_today_secession = User.objects.filter( secession_dts__year=today.year, secession_dts__month=today.month, secession_dts__day=today.day, user_ty="US200200", ).count() pro_total_secession = User.objects.filter( is_secession=True, user_ty="US200200" ).count() pro_is_active_total = User.objects.filter( is_active=True, user_ty="US200200" ).count() ### Start the problem down here.### range_gte_string = request.GET.get("user_join_dts__range__gte") range_gte_date_time = datetime.strptime(range_gte_string, "%Y-%m-%d") range_lte_string = request.GET.get("user_join_dts__range__lte") range_lte_date_time = datetime.strptime(range_lte_string, "%Y-%m-%d") golfer_filter = User.objects.filter( user_join_dts__range=(range_gte_date_time, range_lte_date_time), user_ty="US200200", ).count() extra_context.update( { "pro_today_secession": pro_today_secession, "pro_total_secession": pro_total_secession, "pro_is_active_total": pro_is_active_total, "golfer_filter": golfer_filter, } ) return super().changelist_view(request, extra_context=extra_context) -
unsupported operand type(s) for +: 'QuerySet' and 'QuerySet'
I have model it is have two MantToManyField, How I can sum or compain this two fields, there is number for each field, I want to have have result of sum this fields. My model class Video(models.Model): viewers = models.ManyToManyField(Account, related_name='video_views') viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True) My view video_viewers_ip = video.viewers_by_ip.all() video_viewers = video.viewers.all() video_views = video_viewers_ip + video_viewers Or how to get the result number in a new field num_viewers = models.IntegerField('viewers_by_ip' + 'viewers') -
How to get value inside a div element using JS
Here I have a div element with class med and I want to access the value inside the div of the Prescribed:{{pro_id.prescribedmed}} .I tried JS to get the value by using the getattribute() but it does not show. how can get the value of it. Here is the piece of code <div class="column"> <!-- style="background-color:#bbb; --> <p class="newarrival ">Rs.{{pro_id.price}}</p> <h4>{{pro_id.name}}</h4> <p><strong>Category:</strong> {{ pro_id.category}}</p> <p><strong>Description:</strong> {{pro_id.smalldescription}}.</p> <div class="med hidden" > <p>Prescribed:{{pro_id.prescribedmed}}</p> </div> <button data-product={{pro_id.id}} data-action="add" type="button" class="btn-cart update-cart"> Add to cart </button> </div> i tired to get the element like var premed = document.getElementsByClassName('med').innerText; console.log(premed) here the output gives like undefined -
Set cookie domain in Django project
The host of two project are af-abc.com and abc.com. How to set SESSION_COOKIE_DOMAIN to share cookie in these two domain? -
django admin change form/update model form Violation of PRIMARY KEY constraint with ms sql backend
When I try to edit and update the form in django admin, I am getting IntegrityError at /admin/core/courses/144103/change/ ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK_dbo.Courses'. Cannot insert duplicate key in object 'dbo.Courses'. The duplicate key value is (144103). (2627) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") The admin model form has 2 inlines in it. Not able to understand why the issue is arising. I am not overriding any default behavior. -
How to retrieve data in the template from a custom MariaDB connector? (Django)
I have implemented the following connector following the MariaDB documentation. Documentation This is my db.py: #!/usr/bin/python import mariadb conn = mariadb.connect( user="user", password="", host="localhost", database="db") cur = conn.cursor() def get_some_data(): cur.execute("SELECT some_id FROM `db`.some_data") sid = [] for some_id in cur: sid.append(some_id) return sid conn.close() So far everything is clear, what I am not clear about is...how can I show in a html select a list with the values obtained from the query to the database on my django web page? Should I create a function in views.py and have it return something like this ?: def retrieve_from_db(request): #some code here return render(request, 'index.html', context) Do I need a context? Let's say my index.html is the following, how could I call retrieve_from_db(request) from the template and make this function call get_some_data() and display this information on the web? index.html {% extends "../base.html" %} {% load static %} {% load bootstrap4 %} {% block content %} {% bootstrap_javascript %} //Some form to retrieve the data from the .py scripts <form id="retrieve_db" action="someaction?" method="post"> <div class="form-group"> {% someforloop? %} <select name="myIdList" id="myIdList"> <option value="{{ some_id }}">{{ some_id }}</option> </select> {% endforloop %} </div> </form> {% endblock %} Let's say I want the … -
Django formset exclude fields will not be validated
I have this in my view: Itemform = modelformset_factory(OrderItems, form=OrderItemsForm, extra=ProductsCount, exclude=['OrderNo']) I set the value of OrderNo in the form.save methode: if Orderform.is_valid(): edit_form = Orderform.save() edit_order_id = edit_form.pk request.session['edit_order_id'] = edit_order_id instances = Formset.save(commit=False) for instance in instances: instance.OrderNo = Orders.objects.get(ID=edit_order_id) instance.save() But it goes not in the for loop because I get this error: The OrderItems could not be created because the data didn't validate. [{'OrderNo': ['This field is required.']}, {'OrderNo': ['This field is required.']}] If I exclude this field should it not be ignored? If I render the FK Field OrderNo and choose the latest order it goes throw the loop and override the value but it's not helping if there was never a order. -
FieldDoesNotExist: User_balances has no field named 'None' - ManyToManyField
I am having a difficulty with a ManyToManyField and cannot seem to figure out how to fix this. When I access the ManyToManyField I get this error Models class AccountBalance(BaseModel): user = models.ForeignKey( User, verbose_name=_('Account Owner'), on_delete=models.PROTECT, limit_choices_to{'is_staff': False}, help_text=_("""The owner of Account Balance.""")) class User(AbstractBaseUser): balances = models.ManyToManyField( AccountBalance, verbose_name=_("Account Balances"), related_name="account_balances", help_text=_("Account balances held by user.") ) Accessing User.balances or User.balances.all() etc. returns this error FieldDoesNotExist: User_balances has no field named 'None' What am I doing wrong here. I need help. Cannot seem to find any assistance even going through other suggestions, returns same error -
Django RestFramework: Token auth errors returning HTTP response instead of JSON
I have a DRF backend with a Vue frontend. It has been working for a while (alpha test), but I am trying to thoroughly test the authentication of the site. I login as a test user, then go directly to the database and delete that user from the authtoken_token table. I then hit a backend endpoint to see what error I get. I'm getting an AuthenticationFailed message, but it is an HTTP response, not JSON. Also, it is a "500 Internal Server Error" instead of a 401 or 403. Looking at the handle_exception() method (rest_framework/views.py), I see that it is checking for NotAuthenticated and AuthenticationFailed exceptions, so it should match the actual exception of AuthenticationFailed. def handle_exception(self, exc): """ Handle any exception that occurs, by returning an appropriate response, or re-raising the error. """ if isinstance(exc, (exceptions.NotAuthenticated, exceptions.AuthenticationFailed)): # WWW-Authenticate header for 401 responses, else coerce to 403 auth_header = self.get_authenticate_header(self.request) if auth_header: exc.auth_header = auth_header else: exc.status_code = status.HTTP_403_FORBIDDEN exception_handler = self.get_exception_handler() context = self.get_exception_handler_context() response = exception_handler(exc, context) if response is None: self.raise_uncaught_exception(exc) response.exception = True return response How to ensure I get a JSON response? -
Celery with django and rabbitmq as broker is skipping every alternate task
I have integrated celery with a Django application. Here I am using RabbitMQ as message broker. I am getting a strange issue on Linux . Celery is processing alternate requests only (First request, third request, Fifth Request) -
loop over a dictionary for specific(say first 3) values and then loop again for the next (next 3) values and iterate till the end in django template
My dictionary named 'data' can have any number of values that is multiple of 3(say, it can have 3 or 6 or 9 values). And the keys are like 1,2,3, and so on. I would like to loop over the dictionary for the first three values, then for the next three values and so on. I tried the following code but it's not working and i also don't know how to iterate for the next three values. {% for key,value in data.items %} <td>{{ value }}</td> {% if key%4==0 %} {% break %} {% endfor %} I also tried declaring variable inside django template and use it as a key to access dictionary values but it didn't work either: {% with k=1 %} <td>{{ data.k }}</td> {% k=k+1 %} <td>{{ data.k }}</td> {% k=k+1 %} <td>{{ data.k }}</td> {% endwith %} Any ideas? Thanks in advance. -
How I can count the video views in django by ip for Anonymous users
I created a view to get the Anonymous users IP, I want when this user what the video then register this ip has watched the video,I know it's now efficient because might the user use diffrent network, This my model of the user by ip: class UsersByIP(models.Model): ip_user = models.GenericIPAddressField() def __str__(self): return self.ip_user This model to make relationship between the vdeo and the number of viewrs by ip class Video(models.Model): viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True) I created this view to register the ip as view but I got this error: Field 'id' expected a number but got '127.0.0.1' and I couldn't solv it. The view: num_views_by_ip = Video.objects.annotate( num_views_ip=Count('viewers_by_ip'), ).order_by('-viewers_by_ip') data = get_object_or_404(num_views_by_ip, pk=pk) ip_user = UsersByIP(ip_user=request.META.get('REMOTE_ADDR')) if not request.user.is_authenticated: __, created = Video.viewers_by_ip.through.objects.get_or_create( video=data, usersbyip=request.META.get('REMOTE_ADDR') ) if created: data.num_views_by += 1 I would like to get any suggestions to solve this view or make a new view (logic) -
Django is sending error mails to admins but they don't reach Sentry
We have a site in production where Sentry is enabled but strangely some of the errors are not being reported to Sentry but are only being sent as emails to the admins set in the settings. Which logger settings we need to change so that only Sentry is used and no direct emails are sent? Our project is based on the cookiecutter-django code base. This is our current logger settings: General logger settings: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "root": {"level": "INFO", "handlers": ["console"]}, } and the Sentry config: SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=logging.WARNING, # Send errors as events ) sentry_sdk.init( dsn=SENTRY_DSN, integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()], ) -
How can I filter questions that are answered/unanswered?
In attempting to replicate the unanswered QuerySet functionality of Stack Overflow, I'm left stuck how this would be done at the table level? How would I go about implementing a QuerySet where it returns all unanswered questions when the Question model doesn't have any foreign key reference to Answer on the table itself? It's only when an individual question has been queried that reverse relationship of answers can be accessed. class QuestionStatusQuerySet(models.QuerySet): def unanswered(self): pass def newest(self): pass class Question(models.Model): title = models.CharField(unique=True, max_length=50) body = models.TextField() dated = models.DateField(default=date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answers" ) response = models.TextField() dated = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="answers" ) class Meta: ordering = ['-likes'] -
Django's 'python manage.py runserver' does not create a local website I can access
I am trying to follow this online class, and I am stuck on the part where I access a local website made by django. The tutorial that I follow is this one by freecodecamp, and I get stuck by the 11min mark where I try to access the output site http://127.0.0.1:8000/ . I am following this tutorial on the browser version of Jupyter Notebook. Tutorial: https://www.freecodecamp.org/news/create-an-e-commerce-site-with-django-and-vue/ The 'python manage.py runserver' line runs, and I get the following output: System check identified no issues (0 silenced). April 16, 2021 - 03:37:04 Django version 3.2, using settings 'djacket_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I copy and paste the server address into the browser, I just get the following error saying that I wasn't able to connect to the site: Unable to connect Firefox can’t establish a connection to the server at 127.0.0.1:8000. The only resource I really found that addressed this issue was the following post, but when I went through my netstat list, there were no IPs listing :8000, so I don't think that I am using up that address already. Post: Django manage.py runserver is not working -
I got the msg can't fork because you own this repository while share code to another git account multiple developers on same project
I got the message cannot fork because you own this repository I am trying to send the code on this repo to another account when I tried to share my code to another git account 'while working with multiple developers on same project" and I am new to git hub -
how to compare two lists in different functions in Python?
I am making a Django web Application and i am facing a problem in comparing two different lists in different functions def marks(correct): list1=[] l1=correct def score(and): list2=[] l2=ans how can I compare l1 and l2? -
Django serializer JSON file in database
I have model to load JSON file in my PostgreSQL database.When I migrate,getting some error message. This URL is my JSON field: https://jsoneditoronline.org/#left=cloud.aabe0ab0f87349deada424286dc5c737 First, I create model to load JSON file. from django.db import models WEEKDAYS = [ (1, ("Monday")), (2, ("Tuesday")), (3, ("Wednesday")), (4, ("Thursday")), (5, ("Friday")), (6, ("Saturday")), (7, ("Sunday")), ] class BookStore(models.Model): cash_balance = models.FloatField(null=False) store_name = models.CharField(max_length=100, null =False) opening_hours = models.ManyToManyField('OpeningHours') class Book(models.Model): books = models.ForeignKey(BookStore, on_delete=models.CASCADE) book_name = models.CharField(max_length=100, null=False) price = models.FloatField(null=False) class OpeningHours(models.Model): week_day = models.CharField(max_length=20, choices=WEEKDAYS) start_min = models.TimeField() end_min = models.TimeField() Then, I create 0002_load_json.py to loaddata jsondata.json in migrations directory import os from django.db import migrations from django.core.management import call_command from django.core import serializers book_store_json_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../data')) book_store_filename = 'book_store_data.json' def load_book_store(apps, schema_editor): book_store_file = os.path.join(book_store_json_dir, book_store_filename) call_command('loaddata', book_store_file) # book_store = open(book_store_file, 'rb') # objects = serializers.deserialize('json', book_store, ignorenonexistent=True) # for obj in objects: # obj.save() # book_store.close() # def unload_book_store(apps, schema_editor): book_store_model = apps.get_model("bookstore_api", "model") book_store_model.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('bookstore_api', '0001_initial'), ] operations = [ migrations.RunPython(load_book_store, reverse_code=unload_book_store), ] When I execute manage.py migrate myapps, I get some error message. django.core.serializers.base.DeserializationError: Problem installing fixture -
How to request get name value from <input name={{}}> in django view
I have code blew as: In djang view, how to get input value. if name is not variable, I can get value by request.POST.get("aaa"),but now, I dont know how to do it, pls help, thanks. {% for resu01 in Testpapers %} {{resu01.id}} {{resu01.subject}} {{resu01.duration}} {{resu01.passscore}} {{resu01.examendtime}} {{resu01.subject_id}} start {% endfor %} -
How to make charts using django
Hi I am new to web development and django. I am currently creating a clock in clock out system in a web app. Is there a way to get the clock in clock out information and turn it into a graph or chart? -
CSS file not reloading on change with nginx-gunicorn-django
Firstly I've tried most of the solutions suggested in Stack and from Google. None of the below solutions work when DEBUG MODE is off. sudo systemctl daemon-reload , sudo systemctl restart gunicorn to make sure its not a gunicorn issue Turned off all caching from nginx. Made sure this was the case with curl -I "https://swjungle.shop/2static/CACHE/css/output.9291a1ea98ad.css" returns Cache-Control: no-cache Checked Nginx config again. If debug=True the static files are still not reloaded until collectstatic. But after collectstatic it works. .staticfiles is my STATIC_ROOT location /2static { alias /home/.staticfiles; } sudo systemctl restart nginx also does not reload caching My browser caching is off and I did a hard reload , Ctrl + F5. Deleted all cookie. None of it works... Struggling to find a solution. -
Django is returning JsonResponse, can see the desired JSON response in browser Network tab, but unable to access on the FE
Not quite sure what I'm doing wrong here. I have a method in utils.py that returns the dictionary: import boto3 import base64 # Create a Rekognition client def detect_faces(photo): ... return { 'comment': comment, 'rekognition_response': response, 'url': url, } Which sent back to the views.py: from django.shortcuts import render from django.http import JsonResponse, HttpResponse from . import utils def index(request): return render(request, 'index.html') def submit(request): response = utils.detect_faces(request.body) return JsonResponse(response) I can see the response I'm expecting in the Network tab of the browser: But then on FE, I'm not seeing it in the res: const submitScreenshot = async () => { const picture = document.getElementById('webcam-picture-submit').src; const res = await fetch('/submit/', { method: 'POST', headers: { 'X-CSRFToken': csrftoken }, body: picture.replace('data:image/png;base64,','') }) console.log(res); console.log('Submitted.'); }; I get the sense this is something super basic I'm missing, what is it? -
How to query ManyToMany field using current user in django?
In my django app I have a Message Model with a sender (User) and some receivers (also Users). I want to display in a ListView, all messages that have the current logged user as one of its receivers (the current user must be in the receivers ManyToMany) How to I do that? Here is my code: class MessageModel(models.Model): MESSAGE_TYPE_CHOICES = ( ('draft', 'borrador'), ('new', 'nuevo'), ('red', 'leido'), ('deleted', 'borrado'), ) subject = models.CharField(verbose_name="Asunto",max_length=50) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+', verbose_name='destinatario', editable=False, null=True, blank=True) receivers = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name="destinatarios") received_date = models.DateTimeField(verbose_name="Fecha" ,auto_now_add=True) state = models.CharField( verbose_name="Estado", max_length=50,blank=False, null=False, choices=MESSAGE_TYPE_CHOICES, default="new") message_body = models.TextField(verbose_name="Mensaje") @property def get_receivers(self): return self.receivers.all() class Meta: verbose_name = "Mensaje" verbose_name_plural = "Mensajes" def __str__(self): return self.subject class MailboxListView(LoginRequiredMixin, ListView): model = MessageModel template_name = 'mailapp/inbox.html' context_object_name = 'messages' def get_queryset(self): # here i want to get only the messages in wich the current user is a receiver query_result = MessageModel.objects.all().order_by('received_date') return query_result -
no confirm send when user update his email but it saved new email without confirm - django
i create change email in user profile and when user change email to new one no confirm send to his new email but it saved new email without confirm , what is the problem here views.py : # Edit Profile View @method_decorator(login_required, name='dispatch') class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = True # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your site email ' message = render_to_string('user/emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete change email.')) return redirect('login') return self.request.user tokens.py : from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator()