Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Login error TypeError: Object of type User is not JSON serializable
I have an issue with use login on my Django app. I created a custom user model and it works fine with the database . Some how the login page is not working , it is expecting Json data. I have no idea why it is doing it to. I have the following model class AdminAccounts(BaseUserManager): def create_user(self, user, password=None): """ Creates and saves a User with the given email and password. """ if not user: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(user), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, user, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( user, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, user, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( user, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): id = models.BigAutoField(primary_key=True) user = models.CharField(max_length=50,unique=True,verbose_name='User name') name = models.CharField(max_length=50,verbose_name='User name',default=None,blank=True, null=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser objects= AdminAccounts() # notice the absence … -
Images from the database not displaying in react when using DRF
The tutorial was going smoothly until I got to Lecture 18 (Serializing Data). When the data from the database is being serialized, the images stop displaying in react but {product.image} shows the path of the image. Please I want to know why the image isn't displaying in react but is working perfectly in django. Whenever I click on the image link in the admin page the product gets displayed. The images displayed in react when fetching the products as python array from django, but when I turn to drf it stops displaying. I'm using Django 4.0, I have no Idea whether this has any effect on the issue. When using DRF, EVERY OTHER PROPERTY OF THE PRODUCT IS BEING DISPLAYED IN REACT EXCEPT THE IMAGE Here's the part of the React component where the image is referenced <Link to={`/product/${product._id}`}. <Card.Img src={product.image} /> </Link> urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) STATIC_URL = 'static/' MEDIA_URL = '/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = 'static/images -
Django QuerySet Filter() Not Returning Anything, But When I Use Mongo Compass To Search, It Does Exist
I tried to change the id to string and into integer to test if its due to the type, but both did not work, any help is appreciated thanks! All other code using filter() works except this particular one. Views.py: baseQuery = messageData.objects.using('telegram').filter(from_id = {'user_id':1029783740}) print(baseQuery) Terminal Output: <QuerySet []> MongoDb Compass Search Results: -
This was likely an oversight when migrating to django.urls.path()
I am getting a warning when I run server in django3.2.9. WARNINGS: ?: (2_0.W001) Your URL pattern 'activate/(?P<uid>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$' [name='activate'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Here is my code: path('activate/(?P<uid>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate') I know I need to use the re_path. How should I rewrite above line using re_path? -
IntegrityError at order/order/add/ null value in column "total_incl_tax" violates not-null constraint DETAIL: Failing row contains
When I try to add price to django oscar I get this error and this field is not editable in the model or writable I need help to get this done IntegrityError at order/order/add/ null value in column "total_incl_tax" violates not-null constraint DETAIL: Failing row contains class AbstractOrder(models.Model): """ The main order model """ number = models.CharField( _("Order number"), max_length=128, db_index=True, unique=True) # We track the site that each order is placed within site = models.ForeignKey( 'sites.Site', verbose_name=_("Site"), null=True, on_delete=models.SET_NULL) basket = models.ForeignKey( 'basket.Basket', verbose_name=_("Basket"), null=True, blank=True, on_delete=models.SET_NULL) # Orders can be placed without the user authenticating so we don't always # have a customer ID. user = models.ForeignKey( AUTH_USER_MODEL, related_name='orders', null=True, blank=True, verbose_name=_("User"), on_delete=models.SET_NULL) # Billing address is not always required (eg paying by gift card) billing_address = models.ForeignKey( 'order.BillingAddress', null=True, blank=True, verbose_name=_("Billing Address"), on_delete=models.SET_NULL) # Total price looks like it could be calculated by adding up the # prices of the associated lines, but in some circumstances extra # order-level charges are added and so we need to store it separately currency = models.CharField( _("Currency"), max_length=12, default=get_default_currency) total_incl_tax = models.DecimalField( _("Order total (inc. tax)"), decimal_places=2, max_digits=12) total_excl_tax = models.DecimalField( _("Order total (excl. tax)"), decimal_places=2, max_digits=12) # Shipping charges … -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use roompicture.set() instead
I am a beginner in Django and I am stuck with podting nested images, in my project I want to post images of a hotel and images of the room inside the hotel. but I am getting the following error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use roompicture.set() instead. This is the code with the problem: room = Room.objects.create(hotel=hotel, **room_data) Hier is my serializers.py: class RoomPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = RoomPicture fields = ['id', 'room', 'location'] class RoomSerializer(serializers.ModelSerializer): roompicture = RoomPictureSerializer(many=True) class Meta: model = Room fields = ['id', 'roompicture'] class HotelPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = HotelPicture fields = ['id', 'hotel', 'location'] class HotelSerializer(serializers.ModelSerializer): hotelpicture = HotelPictureSerializer(many=True) rooms = RoomSerializer(many=True) class Meta: model = Hotel fields = ['id', 'hotelpicture', 'rooms'] def create(self, validated_data): hotelpictures_data = validated_data.pop('hotelpicture') rooms_data = validated_data.pop('rooms') hotel = Complex.objects.create(**validated_data) for hotelpicture in hotelpictures_data: HotelPicture.objects.create(hotel=hotel, **hotelpicture) for room_data in rooms_data: room = Room.objects.create(hotel=hotel, **room_data) room_pictures_data = room_data.pop('roompicture') for room_picture_data in room_pictures_data: RoomPicture.objects.create(room=room, **room_picture_data) return hotel Hier is the views.py: class PictureViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet, UpdateModelMixin): queryset = Hotel.objects.all() serializer_class = HotelSerializer Hier is my model.py: class Hotel(models.Model): country = models.CharField() hotel_name = models.CharField(max_length=20) … -
How to dynamically update the modified fields of a Model
Let's say I have the model Project. The model Project has > 100 fields. I can create new Projects from the front-End using forms. When I want to edit/update some field of a Project in the back-end I've been doing something like this (truncated): def edit_project(request): if request.method == 'POST': project_to_edit = Project.objects.get(pk=request.POST['project_id']) project_to_edit.description = request.POST['description'] project_to_edit.name = request.POST['name'] #repeat the same process for each field...(>50) project_to_edit.save() return redirect('project_page/') return redirect('index') The problem is that new fields are constantly being added to the Projects model. Is there a dynamic/ pythonic way to update each field in the model without having to do it 'manually' for each field and save lines of code? -
Django admin site callable attrs seems not working with python regex
I'm adding an additional column to the Django.admin site, according to the document, it oughts to work, but once I introduced re package to this function, things went wrong. here's code sample: class InfoAddrAdmin(ModelAdmin): list_display = ('id', 'machineId', 'uptime', 'repath') list_filter = ('machineId',) def repath(self, obj): res = re.search(r"10\.1\d+\.\d+\.\d+", obj.ipaddr) return res.group()<-Exception comes from here and the related Model is defined as: class RemoteAddress(models.Model): id = models.AutoField(primary_key=True) machineId = models.CharField(max_length=32) uptime = models.DateTimeField(default=now) ipaddr = models.TextField() a piece of text with lots of IP addresses(i.e. the result of command ipconfig) is stored in the ipaddr attr, and that regex searchs for an IP with prefix like '10.1xx.xxx.xxx', which proved working fine. and the main error is: AttributeError: 'NoneType' object has no attribute 'group' You may find some information from https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display -
Method Not Allowed (POST): /
I'm trying to make a simple one-paged shop. I made a ListView of the items and it renders no problem. The shopping cart will be in a modal. I made the buy button, but whenever I press it, it says: Method Not Allowed (POST): / Method Not Allowed: / [22/Dec/2021 11:40:04] "POST / HTTP/1.1" 405 0 Here are my views: from django.shortcuts import render from django.views.generic import ListView from .models import Item from .forms import AddCartForm class ItemsListView(ListView): model = Item template_name = 'main_page.html' def aBuy(request): form = AddCartForm if request.method == 'POST': print('BUY BUY') return render(request, 'main_page.html', {'form':form}) This is the form: class AddCartForm(ModelForm): class Meta: model = Item fields = ['price', 'quantity'] The form in html: <div class="col" style="text-align:left"> <form name="buy" method="POST"> {% csrf_token %} {{ form }} <input type="submit" class="btn btn-info butt" value="Buy"> </form> </div> I cannot continue making the logic for adding it to the future cart because of it. print('BUY BUY') is just for testing. In the url file it's only the main page with ItemListView.as_view. I tried putting the aBuy function in it and out, same problem remains. -
How to Get Authentication from Oauth2 on Angular that using Django REST-Framework as Back-end
I want to build Authentication server for my user and easily to access other my new application without singing up again on the new apps using Oauth2 my current project are below: 1st Project: Authentication Provider (Django implemented Django Oauth Toolkits) 2nd Project: Client Angular using Django REST Frameworks as back-end. So I don't want user sign up on Client app. Just want them on singup on Authentication provider and request access to Client app without signup on it. I have successful implement on Client back-end is working with Authentication Provider but I don't know how to implement on Angular for this case. But Angular is not yet. I don't know how to implement for Angular and Back-end working properly to get authentication from Authentication Provider. Please help to share me the tutorials for practice projects. Thank in advance. -
from django.core.management import execute_from_command_line not working
I am working on a bug project. Which is on Python 2.7, we are migrating to Python 3.9. I am getting import errors in manage.py during importfrom django.core.management import execute_from_command_line. For python 2.7 it is fine but for python 3 it is not working. I've created separate virtual environment for Python 3. manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "best_buy_mall.settings") try: from django.core.management import execute_from_command_line except ImportError: try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) dir tree: my_app/django_site/manage.py my_app/venv (for python2) my_app/v_env (for python3) -
Mandrill API to send email with recipients(cc), but It also send mail to recipients(cc) as 'TO' using Django==1.11.10
Code: def send_mandrill_subscribe_wac(link,user_email, from_user, from_email='examplecc@abc.com'): mandrill_client = mandrill.Mandrill(MANDRILL_API_KEY) #template_name = "Invited-user-email-for-someone-without-an-account" template_name = "invited-user-email-for-someone-without-an-account" template_content = [{'content': 'example content', 'name': 'example name'}] message = { 'from_email': 'examplecc@abc.com', 'to': [ { 'email': user_email, 'type': 'to' }, { 'email': from_email, 'type': 'cc' }, { 'email': 'examplecc2@abc.com', 'type': 'cc' } ], 'global_merge_vars': [ {'content': user_email}, {'name': "redirect_link", 'content': link}, {'name': 'from_user', 'content': from_user} ], } return mandrill_client.messages.send_template(template_name=template_name, template_content=template_content, message=message) In official Documentation they mentioned preserve_recipients set to True to send recipients, But don't know where to add this parameter. Need help please -
return single instance of message django
i'm trying to create a p2p messaging system in my chat app (not using channels) so in my view.py i list out all messages, but i don't want it to list out multiple messages from a single user, just the most recent, sad to say it does the exact opposite, if brings out all messages between 2 people instead of only the most recent, i tried creating a different models so i can filter by that and add the distinct function, but still didn't work, i really wanna get this done by christmas, so i appreciate any help views.py def pmpage(request): user = recceiver.objects.get(id=request.user.id) all_message = pm.objects.filter(recepient=user).distinct() unread = pm.objects.filter(recepient=user, unread=True).order_by('sender').distinct() sent = pm.objects.filter(sender=request.user) context = { 'all_message' : all_message, 'unread' : unread, 'sent' : sent, } return render(request, 'message.html', context) models.py class recceiver(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.name) class pm(models.Model): sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) recepient = models.ForeignKey(recceiver, related_name='recceiver', on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) body = models.TextField() unread = models.BooleanField(default=False) def __str__(self): return f'{self.body}' thanks again -
Where are built-in methods of django model manager defined in source code?
By default, django model's default manager objects has below built-in methods: all(), filter(), exclude(), get(), create(), order_by() But I did not find where are those methods defined in Django source code ? -
Django - Date field support time zone?
I'm working with Django Date field and was wondering if it supports time zone. Doesn't seem like it does because when I attach a time zone to the date it gives an error. Is there a reason for this? Wouldn't something like 11:30pm PST at 12/20/2021 give like 12/21/2021 in UTC? -
How to call an API POST method only inside another API method in Django Rest Framework
I was going through DRF, I want to call one API function which have GET and POST method inside another API function which also have get and post method. whether both get and post method will be called or Is it any way that I can achieve it. I was googling I didn't get any proper approach If some one can demonstrate it would be helpful. what if I want to call POST method in another function? -
Exporting multi table from same databases using django in Swagger
I have two table dataset 1. first_name 2. last_name first_name table looks like f_name | state --------------- raj | UP ravi | MP rahul | JK last_name table looks like l_name | state --------------- sharma | UP singh | MP gupta | JK and django model.py looks like class first_name(models.Model): f_name = models.CharField(max_length=50) state = models.CharField(max_length=50) class last_name(models.Model): l_name = models.CharField(max_length=50) state = models.ForeignKey(first_name, on_delete=models.CASCADE, related_name="last_name", null=True, blank=True, db_column='state') so in django I made importexport.py file and wirte code for import and export of first_name and last_name data sepearatly using this code from import_export import resources from name_management.models import first_name, last_name class first_nameResource(resources.ModelResource): class Meta: model = first_name skip_unchanged = True report_skipped = False use_bulk = True force_init_instance = True skip_diff = True def import_row(self, row, instance_loader, **kwargs): row_result = self.Meta.model.objects.update_or_create(f_name=row[1], defaults={'state': row[2]}) class last_nameResource(resources.ModelResource): class Meta: model = last_name skip_unchanged = True report_skipped = False use_bulk = True force_init_instance = True skip_diff = True def import_row(self, row, instance_loader, **kwargs): row_result = self.Meta.model.objects.update_or_create(l_name=row[1], defaults={'state': row[2]}) and In django views.py file I have created get and post method for importing / Exporting data table class ImportExportViewSet(views.APIView): permission_classes = [permissions.AllowAny] http_method_names = ['get', 'post'] parser_classes = (FormParser, MultiPartParser) def get(self, request, *args, … -
Error while sending PDF through Django link
Fairly New to Django Here. I tried sending a CSV successfully using this code but I'm getting the following error sending a pdf file I generated using PDFpages from matplotlib UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 10: invalid start byte Here's the code def download_file(request): # fill these variables with real values fl_path = 'file.pdf' filename = 'report.pdf' fl = open(fl_path, 'r', encoding='utf-8') mime_type, _ = mimetypes.guess_type(fl_path) print(mime_type) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response Is there a way to know which is the correct encoding I need to send my file through? -
How to display N number of Backward relationship in Django templates?
{% for category in categories %} {% for product in categories.product_set.all %} <h1> {{ product.name }} </h1> {% endfor %} {% endfor %} I want to show 10 products instead of all in template -
How do I upload a txt flatpage into a django based website
What I want to do is, I have a file called abc.txt. I want to upload this into to my website so that it shows on the browser as mysite.com/.well-known/pki-validation/abc.txt. The file (page) contains some text. I want to do this from terminal by creating a flatpage. I have created views.py and url. Daniel -
Calling a function name inside a function in Django Rest Framework
I have tried to call the two method inside the function where I couldn't able to call those method. I have tried few approaches but not succeeded. Here, What I have tried "UserStartShift", "UserStopShift" are the API functions which have GET and POST method in it. These API are working fine individually, I wanted to return a different response using the conditional statement. views.py: @api_view(['GET']) def UserShiftDetailsView(request, userid): try: users = tblUserShiftDetails.objects.filter(UserId=userid) except tblUserShiftDetails.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if UserStartShift == True: cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] @UserId=%s',(userid,)) result_set = cursor.fetchall() for row in result_set: row = row[0] return Response({"IsStarted":True,"EstimatedShifEnd":(row + datetime.timedelta(hours=9)).strftime('%d-%m-%Y %H:%M %p'),"ReasonforAccess": "null"}) elif UserStopShift == True : cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_GetCurrentShiftDetails] @UserId=%s',(userid,)) result_set = cursor.fetchall() for row in result_set: row = row[0] return Response({"IsStarted":False,"EstimatedShifEnd":"null","ReasonforAccess": "null"}) -
post type is not working in knockout js with ajax call
knockout.js <script> $(document).on('click', '#submit', function(e) { var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description() }; $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData, contentType: "application/json; charset=utf-8", success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> In this ajax knockout js code post type is not working. When i click submit button form value is displaying in url but i have done post type in ajax Please help me to solve this Thanks in advance -
How to put and access a file with FFmpeg in Google Cloude Storages?
Hi I am a novice developer and deployed my first django project on Heroku. I want to compress it into ffmpeg and save it to Google Cloud Storage when the user uploads a video file from uploadForm in the Django project.And by extracting the duration from the saved video using ffprobe and storing it in the duration field of object. Save() of My forms.py code is as follows: def save(self, *args, **kwargs): def clean_video(self): raw_video = self.cleaned_data.get("video") timestamp = int(time()) raw_video_path = raw_video.temporary_file_path() print(raw_video_path) video_name = f"{raw_video}".split(".")[0] subprocess.run(f"ffmpeg -i {raw_video_path} -vcodec libx265 -crf 28 -acodec mp3 -y uploads/videoart_files/{video_name}_{timestamp}.mp4", shell=True) return f"videoart_files/{video_name}_{timestamp}.mp4" videoart = super().save(commit=False) videoart.video = clean_video(self) video_path = videoart.video.path get_duration = subprocess.check_output(['ffprobe', '-i', f'{video_path}', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ("p=0")]) duration = int(float(get_duration.decode('utf-8').replace("\n", ""))) videoart.duration = duration return videoart After all the validation of the other fields, I put the code to process the video inside the save method to compress the video at the end. Anyway, this code is not a problem in the local server it works very well. However, the server gets a NotImplementedError ("This backend dogn't support absolute paths.") error. Naturally, ffmpeg can receive input videos from temporary_file_path(), but it doesn't find a … -
Select first image of image foreign key in django template
I want to select first image of an object property set. I created a Property Model with a Foreign Key to an PropertyImages model. How do I access the first image of the property object_set.all in the template. I don;t want to do it in the view function since this should be in the base.html file. the code: {% for property in properties %} <div style="background-image: url('{{property.propertyimages_set.all|first.url}}'); background-size: 100% 100%; " ; class="tm-row-featured" > <div class="featured-content"> <p><span>Name: </span>{{property.property_name}}</p> <hr> <p><span>Type: </span>{{property.property_type}}</p> <p><span>Price: </span>&#8358;{{property.price}}</p> <p><span>Location: </span>{{property.property_state}}</p> <p><a href="{% url 'property_details' property.property_slug %}">More info >>></a></p> </div> </div> {% endfor %} -
how to fecth data from one to many database in django?
class Company(TimeStampedModel): name = models.CharField(max_length=200) hr_name = models.CharField(max_length=200) hr_email = models.CharField(max_length=200) user = models.ForeignKey( settings.AUTH_USER_MODEL, models.DO_NOTHING) hr_verified = models.BooleanField(default=False, blank=True) primary_phone = models.CharField(null=True, max_length=200) followed_by = models.CharField(max_length=200,default="Not assigned") comments = models.TextField(default="") def __str__(self): return self.name class FutsalUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField( ('staff status'), default=True, help_text=('Designates whether the user can log into this admin site.'), ) objects = FutsalUserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email these are models , i want to fecth the details in to one table