Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customizing Reponse in Serializer with Django Rest Framework
I have two models like, class ModelA(models.Model): counter = models.SmallIntegerField(db_column='counter', blank=False, default=0) class ModelB(models.Model): a = models.ForeignKey(ModelA, on_delete=models.CASCADE, null=False, related_name='relation_a') Serializer of ModelB. I am looking if there is already a row of ModelA in table ModelB. If there is any I increase the value in ModelA; otherwise, I create one and put the counter value 1 in ModelA. The response is the counter value coming from ModelA. The problem is, the response is the old value before executing this create function. class ModelBSerializer(BaseSerializer): a = serializers.IntegerField(read_only=True, source='a.counter') def create(self, validated_data): try: bInstance = ModelB.objects.get(a__id=validated_data.get('modelA').id) aInstance = ModelA.objects.get(pk=validated_data.get('a').id) aInstance.counter = 1 aInstance.save() except DealThumbsCounter.DoesNotExist: bInstance = ModelB.objects.create(**validated_data) aInstance = ModelA.objects.get(pk=validated_data.get('modelA').id) aInstance.counter += 1 aInstance.save() bInstance.save() return bInstance class Meta: model = ModelB fields = ['counter'] I am using drf-nested and url is POST /modelA/{model_a_id}/modelB/ How can I get the updated counter value? Thanks in Advance. -
read text from url line by line in python
I am trying to read data from url which is text file line by line, but i'm getting whole data instead of line by line.but when the size of row is large i'm getting the right data. url = request.GET.get('url') data = [] with closing(requests.get(url, stream=True)) as f: data = [list(map(int, line.split('\n'))) for line in f] The above code gives me right answer for files having large row size but it's not working for small data. -
Deploying VGG16 model into production
I have a trained VGG16 model which is around 512 MB. I want to deploy it to a Django website. Is there a way to upload the model into cloud and draw inference from it online? -
Unhandled exception in thread started by <function wrapper at 0x7f7491e1a050> TypeError: unhashable type: 'bytearray'
Platform: Ubuntu: 19.10.3, mysql: 8.0.19, django: 1-11.28, mysql-connector-python: 8.0.5 Hello experts, I am trying to set up mysql as an external db table in my application (HUE) and I keep getting the error TypeError: unhashable type: 'bytearray'. I tried all the suggestions that I can find from google and it has taken me weeks, but I am still not able to resolve this error. I even tried to insert .decode('utf-8') in introspect.py, but doesn't work. My mysql db are all utf-8 character set, so I don't understand where the problem is coming from. Could somebody please help me? Unhandled exception in thread started by Traceback (most recent call last): File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/core/management/commands/runserver.py", line 127, in inner_run self.check_migrations() File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/db/migrations/executor.py", line 20, in init self.loader = MigrationLoader(self.connection) File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/db/migrations/loader.py", line 52, in init self.build_graph() File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/db/migrations/loader.py", line 210, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/brandon/hue/build/env/local/lib/python2.7/site-packages/Django-1.11.22-py2.7.egg/django/db/migrations/recorder.py", line 66, in applied_migrations return set(tuple(x) for x in self.migration_qs.values_list("app", "name")) TypeError: unhashable type: 'bytearray' -
Is it possible to encrypt a bytes stream using PyCrypto?
I'm working on an app where users upload a file and the app processes it automatically for them. For data security, I want to encrypt these files. These files can be of varying sizes from small to very large (2MB to upwards of 30MB). I came across PyCrypto as the de facto encryption/decryption package. The files are read into io.BytesIO() after being processed and then a file is created from the bytes stream. I was wondering if it is possible to 'encrypt' the bytes stream and then create the file. So that when I read the file into io.Bytes(), I can decrypt it and serve the file to the user. -
How to get all instances in serializer method field
How to get all instances in serializer method field I have a serializer method field and I am passing list data in the form of context to serializer like below. name_list = [ "abc", "def",....] obj_list = abc.objects.all() Serializer = abcSerializer (obj_list, context=name_list, many=True) Class abcSerializer (serializers.ModelSerializer): class Meta: model = abc xyz = serializers.SerializerMethodField ("getXYZ", read_only=True) def getXYZ (self, data): # here I want all instanceses, but I got only one instance in data. I want to attach name_list data one by one to instace data with same index? How I can get all instanceses in my serializer method field? -
get_form_kwargs() from FromSet
>>> from django.forms import BaseFormSet >>> from django.forms import formset_factory >>> from myapp.forms import ArticleForm >>> class MyArticleForm(ArticleForm): ... def __init__(self, *args, user, **kwargs): ... self.user = user ... super().__init__(*args, **kwargs) >>> ArticleFormSet = formset_factory(MyArticleForm) >>> formset = ArticleFormSet(form_kwargs={'user': request.user}) The form_kwargs may also depend on the specific form instance. The formset base class provides a get_form_kwargs method. The method takes a single argument - the index of the form in the formset. The index is None for the empty_form: >>> from django.forms import BaseFormSet >>> from django.forms import formset_factory >>> class BaseArticleFormSet(BaseFormSet): ... def get_form_kwargs(self, index): ... kwargs = super().get_form_kwargs(index) ... kwargs['custom_kwarg'] = index ... return kwargs Ive taken the above code from the Django documentation, the documentation says that the form_kwargs which is the dictionary passed in when instantiating FormSet it may depend on a specific instance but it does not say how When get_form_kwargs() is called in FormSet class with an index, its parent class method get_form_kwargs() is called to retrieve supposedly kwargs from a form instance Where is kwargs defined for the form instance? Django documentation writers should be sacked -
Data not saving to database properly Django ManyToManyField
I have a webapp with a friends feature, which is all working except for the bit of saving the current user into the requested user's ManyToManyField Here is my model friends = models.ManyToManyField(User,blank=True,related_name='user_connections') And my view class AddFriendRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): username = self.kwargs.get("username") obj = get_object_or_404(UserProfileInfo,slug=username) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: print("User is authenticated") if user in obj.friends.all(): obj.friends.remove(user) user.user_connections.remove(obj) #this line isnt saving the obj to the database else: obj.friends.add(user) user.user_connections.add(obj) # this line isnt saving the obj to the database return url_ And finally my urls path('profile/<str:username>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), Everything is working except for saving for the user.user_connections.add(obj). On obj.friends.add(user), it adds the current user to their Manytomanyfield, but it's just not working on the user.user_connections.add(obj) one. I have tried heaps of things, including user.friends.add(obj) user.userprofileinfo.friends.add(obj) user.userprofileinfo.user_connections.add(obj) UserProfileInfo is my custom UserProfile model I am just confused as to why this isn't working, and it's weirder because no errors are being thrown either. Thanks for any help -
Django Ajax Post with HTML content using JSON.stringify then json.loads error
I have a textarea within a form on a webpage that has "HTML" content. <!-- HTML --> <textarea id="my-textarea"> <div class="this">Content here &amp; here!</div> </textarea> I fetch the content with Javascript and use encodeURIComponent to safely encode the string for AJAX JSON. and store it into a key/value array. (python dict) // Javascript var textarea = document.getElementById('my-textarea').value; var data = {}; data['html'] = encodeURIComponent(textarea); console.log(data); // prints --> {html: "%3Cdiv%20class%3D%22this%22%3EContent%20here%20%26amp%3B%20here%3C%2Fdiv%3E"} // In AJAX function. var json = "data=" + JSON.stringify(data); I then send the data to Django class based view and in post I have # Python / Django if request.is_ajax(): print(request.POST) # prints --> <QueryDict: {'data': ['{"code":"<div class="this">Content here &amp; here</div>"}']}> data = request.POST.get('data', None) if data: data = json.loads(data) This throws an error as below: Traceback (most recent call last): File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/tr/dev/host-root/apps/trenddjango2/django/common/views/dashboard/mixins.py", line 56, in dispatch return super(TemplateDashboardMixin, self).dispatch(request, *args, **kwargs) File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/tr/dev/host-root/apps/trenddjango2/django/common/views/dashboard/catalogue.py", line 550, in post data … -
it always gives false ,i used this hasGroup function in other apps in all the apps this function returns false
from django.contrib.auth.models import Group def hasGroup(user,groupName): group = Group.objects.filter(name=groupName) return True if group in user.groups.all() else Falseenter image description here -
In django without using pagination i want to display record page wise
I am trying to do is display record page by page but without using pagination. -
Django - How to hide Server [HTTP Response header] parameter in middleware file?
In my Django application, the following settings ensure that the response headers have the standard key-value pairs enabled. However, the 'Server' name and version information is still visible by default which needs to be hidden (exposed server name and version is an OWASP vulnerability). middleware.py class BrandReputationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response['X-XSS-Protection'] = "1; mode=block" del response['Server'] # this line of code has no effect. return response Also as suggested in other posts, this middleware.py is declared in the first order of middlewares in settings.py: MIDDLEWARE = [ 'MyApp.middleware.BrandReputationMiddleware', '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', ] In the above snippet, the idea is not to use del operator but rather to just hide the 'Server' parameter from getting displayed in the response headers, which I am unable to accomplish. -
Django, restricting access to pages
I have various applications in a Django project, but I only want users who are logged in to be able to access those pages. How can I restrict all access to different pages except the login page which is my main page. For instance, mywebsite.com/home/user should be only available to user and if someone types in that it should redirect them to mywebsite.com Currently I have to apps, main and Home, I am using ClassBased views on my Home app how can I restrict access to all my pages except login page and show a message as well? -
Django admin model method field in fieldsets with readonly_fields
i have a model with 2 custom methods class User(AbstractUser): uid = models.CharField( "uid", max_length=255, null=True, blank=True) phone_number = models.CharField( "Phone number", max_length=255, null=True, blank=True) nickname = models.CharField( "Nickname", max_length=255, null=True, blank=True) def eth_address(self): try: wallet = UserWallet.objects.get(user=self, currency=2) return wallet.address except Exception: return None eth_address.short_description = 'eth_address' def evt_address(self): try: wallet = UserWallet.objects.get(user=self, currency=1) return wallet.address except Exception: return None evt_address.short_description = 'evt_address' In order to show custom model methods in admin i need to add the method name to both fields and readonly_fields, which worked great on previous admin models But when i try to use fieldsets with readonly_fields: class UserAdminCustom(admin.ModelAdmin): list_display = ('id', 'email', 'phone_number', 'status', 'created') list_display_links = ('id', 'email', 'phone_number', 'status', 'created') change_form_template = 'admin/backend/user_change_form.html' # verbose_name = "General" # exclude = ('password', 'last_login', 'is_superuser', 'is_staff', 'groups', # 'user_permissions', 'username', 'first_name', 'last_name', 'is_active', 'date_joined', 'eth_private_key', 'evt_private_key', 'modified') inlines = [ UserKycInline, UserWalletInline, UserBankInline, CardBindingInline, TopUpsInline, TransfersInline, WithdrawalsInline, ] fieldsets = ( ('General', { 'fields': ('id', 'uid', 'phone_number', 'email', 'nickname', 'eth_address', 'evt_address', 'created', 'modified',), }), ) readonly_fields = ('eth_address', 'evt_address', ) it return me the following error: Unknown field(s) (eth_address, evt_address) specified for User. Check fields/fieldsets/exclude attributes of class UserAdminCustom. The only way to use model … -
Django app sensitive information in Github
Django app settings.py when uploaded to Github shows secret key, password and other sensitive information about the app. How do you address this? -
Convenient way of using multiple instances of the same Form subclass within a template?
I'm trying to write an application that manages Tasks. One of my requirements is to be able to view a day's tasks and reschedule them, if the user needs to complete this later. models.py: class Task(models.Model): due_date = models.DateField() is_complete = models.BooleanField(default=False) description = models.CharField(max_length=100, blank=True) ## other fields These Tasks are processed by a subclass of DayArchiveView, which uses date_field=due_date and context_object_name=task_list. The resulting template renders each Task as a row in a table. Within this interface, I'd like to provide a way to change the due_date. Because it changes data, a seems to be the best option. My current version uses native HTML mixed into the template: tasklist.html <table> <thead> <tr> <th>Due Date</th> <th>Description</th> <th>Complete?</th> <th>Change Due Date</th> </tr> </thead> <tbody> {% for task in task_list %} <tr> <td>{{ task.due_date }}</td> <td>{{ task.description }}</td> <td>{{ task.is_complete }}</td> <td> <form method="post" action="{% url 'reschedule' %}"> {% csrf_token %} <!--the following field is actually a more complicated dropdown using tempusdominus-bootstrap-4--> <input type="date" name="change_date"> <input type='hidden' name='task_id' value='{{ task.id }}'> <button type="submit">Reschedule</button> </form> </td> </tr> {% endfor %} </tbody> </table> The question I'd like answered is whether there's a good way within a view (CBV or FBV) to pass multiple instances … -
I want make charts in js |
I am looking for bar chart ,for this values , anyone help me, Tanks in advance! ['Year', 'Sales', 'Expenses', 'Profit'], ['2014', 1000, 400, 200,500], ['2015', 1170, 460, 250], ['2016', 660, 1120, 300], ['2017', 1030, 540, ] -
Django how to compute the Percentage using annotate?
I want to compute the total average per grading categories and multiply it by given number using annotate this is my views.py from django.db.models import F gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subject).filter\ (Grading_Categories__in = cate.values_list('id')).values('Grading_Categories').annotate( average_grade = Avg * F('Grading_Categories__PercentageWeight') / 100) this is my models.py class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() class studentsEnrolledSubjectsGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, related_name='grade', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='subject', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='student', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='category', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='period', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) For more info: For example the average of Quiz(Grading categories) is 80 and it will multiply with 15(PercentageWeight) Total = 80(Grading_Categories) * 15(PercentageWeight) total=total / 100 The result must be 12 -
We are trying to have authentication based on tokens plus I am confused about tokens in Django libraries
Our project is entirely on Django Rest Framework, so the front-end user interface features of Django are not used. The front-end is on ReactJS. I was told that the built-in authorization creates only 1 token which gives access to everything and without even a refresh token. I'm not sure if this is true. The documentation and reading has led me to that JWT provides refresh tokens only, so seems that this is not in the built-in auth library of django. Also what is the best practice? My co-worker is saying, that we provide a refresh token through JWT, then this refresh token is renewed automatically every 1 hour. We also need to make the login based on email address or phone number, rather than the username as the built-in django auth provides. Is OAth2 really more secure than the built-in django library and JWT? Or is it that only when we want to make our Django server authorize access to our server (does implementing OAth2 as a server on Django makes it like Google or Facebook when they are using OAth2, where they become a 3rd party that authorizes access and login to other websites.) What shall we do? -
Python Pandas Groupby - No objects to concatenate
I have a Dataframe with following values: df = route stop_code stop_name 900 92072 Eastbound @ 257 Kingston Road East 900 1590 Kingston Westbound @ Wicks 900 2218 Kingston Eastbound @ Wicks 900 93152 Salem Northbound @ Kingston 92 728 Kingston Rd. @ Salem Rd. 224 92071 Salem Southbound @ Twilley 215 92071 Salem Southbound @ Twilley 215 92054 Northbound @ 133 Salem 224 92054 Northbound @ 133 Salem 215 93152 Salem Northbound @ Kingston What I want is to group routes by stop_code or stop_name, something like: df2 = route stop_code stop_name 900 92072 Eastbound @ 257 Kingston Road East 900 1590 Kingston Westbound @ Wicks 900 2218 Kingston Eastbound @ Wicks 92 728 Kingston Rd. @ Salem Rd. 224, 215 92071 Salem Southbound @ Twilley 215, 215 92054 Northbound @ 133 Salem 215, 900 93152 Salem Northbound @ Kingston I tried to do the following: df2 = df.groupby(['stop_code']).agg(set).reset_index() while it did work fine in my test environment, when I deployed it in Django (Python Anywhere), I got the following error (maybe due to different versions of Pandas / Python / Django): ValueError: No objects to concatenate can anyone please guide me sort it out? TIA -
Deploying django app to digital ocean unsuccessful (502 Bad Gateway)
Good day guys, I am in a bit of a mess here with deploying a Django app to the digital ocean using Gunicorn and Ngnix. I am following the steps in a video tutorial I bought on udemy, where we are following a link https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#disable-root-login. while following the tutorial, everything worked to the point before I set up gunicorn, which means I was able to see the website through the IP address. but, only that the static files were not handled by Nginx and I was running the server using python manage.py runserver 0.0.0.0:8000 when I was at this point https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#run-server. when I followed the step and configured gunicorn and Nginx, I was getting 502 Bad Gateway when I visited using the IP address. I was wondering why I was getting this issue, and I noticed that when I checked the status of gunicorn using sudo systemctl status gunicorn.socket I was getting: gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: failed (Result: service-start-limit-hit) since Fri 2020-02-28 03:03:11 UTC; 7s ago Listen: /run/gunicorn.sock (Stream) here is a link to the project I was trying to add to the server if needed https://github.com/opeodedeyi/medxFinal please I really need help. -
campaign_name = models.ForeignKey(Campaign, on_delete=models.CASCADE)
class Campaign(models.Model): id = models.AutoField(primary_key=True) campaign_name = models.TextField() class SessionLog(models.Model): date = models.DateField() campaign_name = models.ForeignKey(Campaign, on_delete=models.CASCADE) ERROR FROM WEBSITE: OperationalError at /admin/session/sessionlog/ (1054, "Unknown column 'session_log.campaign_name_id' in 'field list'") WHAT I AM TRYING TO DO: create a drop-down list on SessionLog to populate campaign_name based on entries in Campaign. I am new to asking questions. Please be kind if I have explained myself wrong. -
Access Django through model extra fields in m2m_changed signal handler
Let's say I have the following Django models, which represents a sorted relationship between a Parent and Child: class Parent(models.Model): name = models.CharField(max_length=50) children = models.ManyToManyField("Child", through="ParentChild") class Child(models.Model): name = models.CharField(max_length=50) class ParentChild(models.Model): class Meta: constraints = [ models.UniqueConstraint(fields=["parent", "child"], name="uc_parent_child"), models.UniqueConstraint(fields=["parent", "sort_number"], name="uc_parent_child"), ] parent = models.ForeignKey(Parent, on_delete=models.CASCADE) child = models.ForeignKey(Child, on_delete=models.CASCADE) sort_number = models.IntegerField() def save(self, *args, **kwargs): exising_sort_numbers = self.parent.parentchild_set.values_list( "sort_number", flat=True ) if self.sort_number in exising_sort_numbers: raise Exception(f"Duplicate sort number: {self.sort_number}") super().save(*args, **kwargs) Now if I create the relationships using the through model, I get the exception for a duplicate sort_number: ParentChild.objects.create(parent=parent, child=child1, sort_number=0) ParentChild.objects.create(parent=parent, child=child2, sort_number=0) # raises Exception However, if I create the relationships using the .add method, I don't get the exception: parent.children.add(child1, through_defaults={"sort_number": 0}) parent.children.add(child2, through_defaults={"sort_number": 0}) # does NOT raise Exception I know using the .add method doesn't call the .save method on the through model so I need to use the m2m_change signal to run this logic. But I'm not sure how to get the sort_number within this signal. Here's the code I have for the signal so far: @receiver(m2m_changed, sender=Parent.children.through) def validate_something(sender, instance, action, reverse, model, pk_set, **kwargs): if action == "pre_add": for pk in pk_set: child = … -
Can't migrate Django project in new database
I just created a new database for my Django project. When I did the first round of migrate, I got the error: File ".../lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 784, in get_db_prep_value value = self.get_prep_value(value) File ".../lib/python3.6/site-packages/django/contrib/gis/db/models/fields.py", line 186, in get_prep_value obj = GEOSGeometry(obj) File ".../lib/python3.6/site-packages/django/contrib/gis/geos/geometry.py", line 715, in __init__ raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.') ValueError: String input unrecognized as WKT EWKT, and HEXEWKB. I suspect it's related to this GeoDjango model field: from django.contrib.gis.db import models as geomodels class image(models.Model): ... location = geomodels.PointField(null=True, blank=True) ... I can't figure out why it's not working when it worked fine before the database change. The postgis extension has been created in the database. I tried assigning a default value to the field with no change. Am I missing a step in setting up the database? What else could trigger this error? -
Django INSTALLED_APP Resolving to "ModuleNotFoundError"
The pip module Im using needs to be listed included in installed apps as such: INSTALLED_APPS = [ ..., 'django_apscheduler', ... ] But I keep getting the following when I build my app: ModuleNotFoundError: No module named 'django_apscheduler' Even though the app is clearly listed in my pip list. The module in question is Django APScheduler.