Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket Send and Receive Image with Base64 bandwith problem
I coded a web socket using Django channels and now want to add the possibility to send images over the chat (obviously it is a chat application). What I did for now: The user picks an image (frontend) The user sends it to the backend (HTTP POST) I use Django signals (it is a listener for the database) to detect if there is a new message with an image appended I send the image back over the websocket Following is the problem: It is slow (not too noticeable but quite slow) Sometimes it causes weird misbehavior So now I thought about sending the image as a base64 and then sending it back directly so I never have any HTTP which can be helpful, because it is a little bit faster. BUT: Base64 images are 20-30 percent bigger and I need to extract all the exif data in the frontend. Is there any possibility to send the images as a file over the websocket to the backend or if not is there a way to get around the quite greater size (20-30 percent), which is a problem because I cannot use too much bandwidth :/ How do other chat application solve … -
AttributeError at /service 'Orderbook' object has no attribute 'save'. , save is a function fm.save()
got an attribute error showing function as an error or the attribute . i had try to solve it but it is not working I had delete all the migrated files and again run python manage.py makemigrations and migrate command but still showing me same error code in admin.py # Register your models here. from django.contrib import admin from .models import * # Register your models here. @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display=('user_id','username','password','name','email_id','contact','address') @admin.register(Orders) class OrdersAdmin(admin.ModelAdmin): list_display=('oid','parcel_info','parcel_qty','parcel_weight','unit_mass','desti') code in views.py from django.shortcuts import redirect, render from django.contrib.auth import authenticate,login from user.forms import * from django.contrib import messages from user.models import * from user.models import Orders # Create your views here. def home(request): return render(request,'home.html') def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] userm=authenticate(user=username,passe=password) if userm is not None: login(request,userm) messages.success(request,"You have login successfully...") return redirect("home") else: messages.error(request,"Invalid Username or password...") return redirect("login") else: return render(request,'base.html') def register(request): if request.method=='POST': fm=Userregistration(request.POST) if fm.is_valid(): fm.save() else: fm=Userregistration() return render(request,'register.html',{'form':fm}) def Orderreg(request): if request.method=='POST': fm=Orderbook(request.POST) if fm.is_valid(): fm.save() fm=Orderbook() return redirect('service') else: fm=Orderbook() u=Orders.objects.all() return render(request,'service.html',{'form':fm,'us':u}) def contact(request): return render(request,'contact.html') def about(request): return render(request,'about.html') HTML code {% extends 'base.html' %} {% block body %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> … -
How to go from one page to another in django?
I am new in python programming and I created a project for learning. I have created three html pages when I click on the other page link it's show error page not found because url show previous page link with current page link (I don't know how to explain my problem) For Example I have two page index, home if I am on index page(url for index page is "http://127.0.0.1:8000/index/") and want to go to the home page when I click on home page link its show an error because the url for error page is "http://127.0.0.1:8000/index/home/" and I want home page url like this "http://127.0.0.1:8000/home/". Same thing happen when I want to go from home page to index page but when I write manually, page open correctly My code reference code for index.html and home.html links <a class="collapse-item" href="home">Home Page</a> <a class="collapse-item" href="index">Index Page</a> view.py from django.shortcuts import render from django.http import HttpResponse def index_view(request): return render(request, "index.html") def home_view(request): return render(request, "home.html") app/urls.py from django.urls import path from . import views urlpatterns= [ path('index/', views.index_view), path('home/', views.home_view), project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("app.urls")), ] -
Django - Display list of category belonging to each card
I have a Giftcard model, and Category model which holds all category, rate and term for each card. It has a foreign key back to Giftcard. I just want to be able to list category, rate and terms for each Giftcard. As the code is right now, it displays the displays same category, rate and terms for all Giftcard. model class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) name = models.ForeignKey(Giftcard, on_delete=models.CASCADE, related_name="specs") rate = models.IntegerField() terms = models.TextField() Here is my views def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) context = { 'giftcards': giftcards, } return render(request, 'dashboard/giftcard.html', context) Here is my template {% for giftcard in giftcards %} <!-- Card --> <div class="col-lg-4 gift__card col-6 p-0"> <a type="button" class="btn"> <img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}"> </a> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <input list="category" class="form-control" name="category" id="card_category" … -
how to make search box on the admin change list page make a search over phone_number field in User model
I want to do search over Users using their phone number, the search_list don't do that with fields of PhoneNumberField(): class User(AbstractUser, PermissionsMixin): phone_number = PhoneNumberField( unique=True) email = models.EmailField("Email address", unique=True, null=True, blank=True) first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) I tried to use this field in the admin: class UserAdmin(admin.ModelAdmin): add_form = CustomUserCreationForm form = UserChangeForm search_fields = [ "first_name", "last_name", "email", "phone_number", ] but it didn't work. -
drf - output serializer.data with custom data with APIView
i want to output in my API not only models, but some custom data, before any objects models.py class Example_model(models.Model): example_model_name = models.CharField(max_length=100) serializer.py class Some_Serializer(serializers.ModelSerializer): class Meta: model = Example_model exclude = ["id"] views.py class My_Api(APIView): def get(self, request): all_example_objects = Example_model.objects.all() serializer_class = Some_Serializer(all_example_objects, many=True) #my custom data which i want to include in this serializer before every thing (on top of it) custom_data = {'new_york':777} return Response(serializer_class.data) i want somehow to include custom_data variable in the output (on top of it) so it would looks like this { "custom_data":777, "api_output": [ { "example_model_name":"hello world" }, { "example_model_name":"i love you" }, { "example_model_name":"my name is giovanni giorgio" }, ] } -
Django ModelManager causes DjangoModelFactory to return None
I have a django.Model object which needs to do some parameter processing when it get's initialized. So inside of it I made a ModelManager as the documentation suggests. class ScheduledCourse(models.Model): """Represents a scheduled course that is/was bound to be held.""" class ScheduledCourseManager(models.Manager): def create(self, *args, **kwargs): if not (template := kwargs.get("template")): raise ValueError("Template can not be empty") # If user did not specifiy values for these parameters, use the ones in the template for key in ["title", "description", "price"]: if not kwargs.get(key): kwargs.update({key: getattr(template, key)}) super().create(*args, **kwargs) This works fine, I've tested it and I can create objects with the ScheduledCourse(...) call. When I tried however to make a factory for this object to use in my tests, then the factory returns None, without any error. class ScheduledCourseFactory(factory.django.DjangoModelFactory): class Meta: model = ScheduledCourse template = factory.SubFactory(CourseTemplateFactory) title = "Test title" description = "Test description" price = 1234.0 start_date = datetime.today() end_date = datetime.today() + timedelta(days=1) signup_deadline = datetime.today() - timedelta(days=1) venue = "Test Venue" status = ScheduledCourse.Status.DRAFT What is the cause for my factory returning none? -
Django foreign key display values in detail view
I have a main DB table Radni_nalozi (Work Orders) to which I am attaching Stavke (items) by a foreign key. When I go to see details about a specific Work Order I also want to display all the items that are connected to that Work Order by a foreign key. I tried many different approaches and it seems that I just can't figure it out on my own. I am attaching the code below. In an HTML template, I can only fetch details about specific work orders but not the items. -
Is there a way to annotate this django object computer property?
I have an django Model named Payment that I want to filter by a computed property. class Payment(Model): ...other fields terms = PositiveIntegerField(help_text='days') issued_date = DateField() then I have this property to calcutate the payment_date @property def payment(self): return self.issued_date + datetime.timedelta(days=self.terms) I tried to annotate it with something like this: Payment.objects.annotate(due_date=ExpressionWrapper(F('issued_date') + F('terms'), output_field=DateField())) but unfortunately it's not working. Any help on this is greatly appreciated. -
Nested serilailzer and difficulties with subfactories in a django unit test
I am getting a failing test because (I think) I can't add a subfactory field. The issue is caused by my test: _expected_restuarant_response. It is expecting a response that includes an employee field. The problem is that I can't add this subfactory field to RestaurantFactory because RestaurantFactory is located above EmployeeFactory in the factories.py file (EmployeeFactory is not invoked at that point in the file). I also can't put EmployeeFactory higher than RestaurantFactory because it refers to RestaurantFactory. Could somebody point me in the right direction? Thank you. A simplified version of my files: models.py: class Restaurant(models.Model): name = models.CharField(max_length=20) class Employee(models.Model): badge_id = models.CharField(max_length=20) restaurant = models.ForeignKey(Restaurant) serializers.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = [ 'badge_id'] class RestaurantSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=True, read_only=True) class Meta: model = Restaurant fields = [ 'name', 'employee'] factories.py: class RestaurantFactory(factory.django.DjangoModelFactory): name = factory.Faker('company') < ----------------------------------- do I need to add an Employee subfactory here? If so how? class EmployeeFactory(factory.django.DjangoModelFactory): badge_id = factory.Faker('id') restaurant = factory.SubFactory(RestaurantFactory) test.py: def _expected_restuarant_response(restaurant): return { restaurant.name, restaurant.employee_set.badge_id } assert response_json == [_expected_restaurant_response(RestaurantFactory())] -
Django Redirect by Name - NoReverseMatch - Error with URLResolver
My django project name is 'exercises' and the app name is 'practice'. This basic application allows a user can navigate to different pages with a button click. The reference to each page uses the following href: {% url 'practice:redirector' project.pk %} Where practice:redirector points to my app (practice) url path named redirector. It is parameterized with the primary key of the page which I am trying to redirect to. See below This url points to practice views. There, I have a view set up for each page that corresponds to the name that the page will display. I also have a re director view that uses the pk passed in the url to pull the relevant page from my database and use the name as the argument in the redirect() shortcut: I am expecting django to use the redirector view to redirect depending on the provided name. Using the debugger, I can see that the database is correctly queried and the correct name is passed to the redirect with each url: However, I get a NoReverseMatch error because django is using the project url file instead of my application url file to find the corresponding view. I need the resolver … -
Django TestCase: data not pass in ajax => status_code =400
I want to implent test of one of my Ajax view. I have read the doc but don't know why data are not pass to the form, and consequently form validation fail, explaining status_code 400. views.py class AjaxPatientCreate(SuccessMessageMixin, CreateView): model = Patient form_class = PatientForm def get(self, *args, **kwargs): form = self.form_class() return render(self.request, self.template_name, {"PatientForm": form}) def post(self, *args, **kwargs): if self.request.method == "POST" and self.request.is_ajax(): pat = self.request.POST.get('pat') # empty pat_sit = self.request.POST.get('pat_sit') # empty form = self.form_class(self.request.POST) if form.is_valid(): form.save() return JsonResponse({ "success":True, "total_patient": Patient.objects.filter(pat_sit__in = user_authorized_sites).count(), "datatable": render_to_string( 'ecrf/_datatable.html', { 'ajax_patients': Patient.objects.filter(pat_sit__in = user_authorized_sites), 'user_can_delete_patient' : self.request.user.has_perm('ecrf.can_delete_patient') } # data to pass to template ) }, status=200) else: return JsonResponse({"success":False}, status=400) test.py @override_settings(DEBUG=True) class AjaxPatientCreateViewTest(TestCase): def setUp(self): self.client = Client(HTTP_ACCEPT_LANGUAGE='fr') # define in context_processor self.login = self.client.login(username='admin', password='admin') def test_post(self): self.assertTrue(self.login) response = self.client.post( reverse('ecrf:ajax_patient_create'), data={'pat': 'TR001','pat_sit': 4,}, content_type='application/json', # django serialize data to JSON HTTP_X_REQUESTED_WITH='XMLHttpRequest' # ajax view ) print('response.status_code',response.status_code) -
Dynamic URL routing is not working in django web application
A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url. Dynamic value is getting populated in the URL, but it not performing action that needed. prop_listings.html HTML Page:- <div class="row text-secondary pb-2"> <div class="col-6"> <i class="fas fa-clock"></i> {{ listing.list_date | timesince }} </div> </div> <hr> <a href="{% url 'morelisting' listing.id %}" class="btn btn-primary btn-block">More Info</a> </div> </div> </div> URL.py in App Listings:- from django.urls import path from . import views urlpatterns = [ path('',views.PropListings,name="prop_listings"), path('<int:listing_id>', views.mlisting, name="morelisting"), ] Views.py :- def mlisting(request, listing_id): # listingDetl = get_object_or_404(Listing, pk=listing_id) listingDetl = Listing.objects.get(pk=listing_id) print(listingDetl.username, listingDetl.address,listingDetl.city) context = { 'listingDetails': listingDetl } return render(request,'listings/detail_listing.html', context) URL.py in MainProject:- urlpatterns = [ path('', include('static_pages.urls')), path('user_account/', include('user_account.urls')), path('listings/', include('listings.urls')), path('feedback/', include('feedback.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id <a href="{% url 'morelisting' listing.id %}" class="btn btn-primary btn-block">More Info</a> It's not working as expected on-click of above tag. But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected. Inspect … -
how I can insert latitude and long python Django
I want to insert latitude and long using python Django. I use code but does not work when click on the button it shows null in DB. models.py map_id = models.AutoField(primary_key=True) map_u_address = models.CharField(max_length=250, null=True) latitude = models.DecimalField(max_digits=11, decimal_places=7, null=False, blank=True) longitude = models.DecimalField(max_digits=11, decimal_places=7, null=False, blank=True)``` view.py ```def save_location(request): if request.method == 'POST': form = request.POST latitude = form.get('latitude') longitude = form.get('longitude') user_id = request.session['user_id'] insert_data = UserLocation.objects.create( latitude=latitude,longitude=longitude, ) if insert_data: json_data = {'msg': "Insert data successfully", 'state_val': 1} return JsonResponse(json_data) else: json_data = {'msg': "Data not saved", 'state_val': 2} return JsonResponse(json_data) else: return render(request, 'map_1.html')``` -
Django template filter inside a template tag
I use provider_login_url template tag that takes next parameter. I want next to be either a request.GET.next or some default value like /default-page. Obviously this does not work: <a ... href="{% provider_login_url ... next="{{ request.GET.next |default:"/default-page" }}" %}"> ... </a> Is it possible to do this inside the template? -
create a filter in django-datatables-view with relation value
I want to filter the value using relation in django-datatable-view. I have blog table related with author. I want to show only blog related to author. But how can I filter with in django-datatable-view. I got the author id. def filter_queryset(self, qs): search = self.request.GET.get('search[value]', None) if not self.request.user.groups.filter(name='Author'): print(self.request.user.id) if search: qs = qs.filter(title__icontains=search) | qs.filter(date__contains=search) return qs -
Custom middleware to check active session, sesison.id for logging out users with inactivity and dynamic typing-django
I am building a django application and am presently working on the login system. I want to implement following things:- Inactive users are redirected to a session out page after inactivity. If a user types in any url or pastes any url manually, he should be redirected to the session out page. I have done something called custom Interceptor in Grails and read a bit about django middleware. Could anyone guide in writing a custom middleware in django for the following purposes. Regards -
Connetc two serializers to output general data
I can't output general data from two tables models.py name = models.CharField(max_length=255, default='carousel_instance') widget_type = models.CharField(max_length=50, default='carousel', editable=False) class Image(models.Model): name = models.CharField(max_length=255, default='image_instance') image = models.ImageField(upload_to='images/') default = models.BooleanField(default=False) carousel = models.ForeignKey(CarouselWidget, on_delete=models.CASCADE) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image', 'carousel'] class CarouselWidgetSerializer(serializers.HyperlinkedModelSerializer): images = ImageSerializer(many=True, read_only=True) def create(self, validated_data): images_data = self.context['request'].FILES carousel = CarouselWidget.objects.create( widget_type=validated_data.get('widget_type', 'carousel') ) for image_data in images_data.getlist('file'): Image.objects.create(carousel=carousel, image=image_data) return carousel class Meta: model = CarouselWidget lookup_field = 'id' fields = ['id', 'name', 'widget_type', 'images'] views.py class CarouselWidgetList(generics.ListCreateAPIView): queryset = CarouselWidget.objects.all() serializer_class = CarouselWidgetSerializer When I need this { "id": 2, "name": "carousel_instance", "widget_type": "carousel", "images": ["/some_path/", "/some_path/"] } **How to link two serializers properly? Or what is the problem?" -
Django dynamic field in the admin panel one to many
There are related tables: equipment and orders. Can I fill in an array of equipment and its quantity in the admin panel when adding a new entity to the orders table? class Equipment(models.Model): name = models.CharField(max_length=63) def __str__(self): return self.name class Order(models.Model): # equipment = ArrayField(models.CharField(max_length=255)) -
api_view with filter request.user and created_by?
I want to display only the conferences created by the user connected with the get_myconferences function but I don't understand why it doesn't work? do you have any idea please knowing that I have no UserSerializer or class user I used user from the rest framework -
adding attribute on option (django)
could someone help me? I have the following models (simplified): class Glass(models.Model): code = models.CharField() price = models.CharField () class QuoteItem(models.Model): first_glass = models.ForeignKey(Glass,on_delete=models.CASCADE) I need to generate a first_glass select that incorporates the "price" attribute of Glass within each option, but I can't do it, the idea is that it looks like this (eg). <option value="4" price="2000">IN06</option> I tried to incorporate solutions from stackoverflow but I have not been able to add the attributes -
How can i perform join operation in Django?
The project is basically a resume builder wherein user will fill all details in the form and the system will generate a resume . The database structure is somewhat like this:- user table:- for authentication. resumeinfo :- here details like personal info ,education info are stored projectinfo table:- each resume created by user can have 0/1/or multiple projects experienceinfo table:- each resume have have 0/1 or multiple experience info 1 user can create multiple resume. Each resume has a resumeinfo and can have 0 or more projects and experiences. **here are the django models ** class User(models.Model): fname=models.CharField(max_length=20) lname = models.CharField(max_length=20) gender = models.CharField(max_length=20) def __str__(self): return self.fname class Resdata(models.Model): fname=models.CharField(max_length=20) lname = models.CharField(max_length=20) school = models.CharField(max_length=20) resumeno=models.CharField(max_length=20) creatorid=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.fname class Project(models.Model): ptitle=models.CharField(max_length=20) pdesc=models.CharField(max_length=20) resume=models.ForeignKey(Resdata,on_delete=models.CASCADE) def __str__(self): return self.ptitle class Exp(models.Model): etitle=models.CharField(max_length=20) edesc=models.CharField(max_length=20) resume=models.ForeignKey(Resdata,on_delete=models.CASCADE) def __str__(self): return self.etitle For example there are 2 users registered in user table jack bob jack creates 1 resume by entering all the details ,in this resume jack enters 3 project info and 2 experience info. Now jack creates 2nd resume by entering all the details ,in this resume jack enters only 1 project and has no experience I want to create … -
Django admin TabularInline and unique_together error 'dict' object has no attribute 'is_hidden'
my models: model.py class ModelA(Model): name = models.CharField('Name') class ModelB(Model): model_a = models.ForeignKey( ModelA, on_delete=models.SET_NULL, verbose_name='modelA', ) code = models.CharField('code') class Meta: unique_together = ('code', 'model_a',) In my admin.py: class ModelBInline(admin.TabularInline): model = ModelB fields = ('code', ) @admin.register(ModelA) class ModelAAdmin(admin.ModelAdmin): list_display = ( 'name', ) inlines = (ModelBInline,) If I change the code in TabularInline, and it is not unique, then I get an error: AttributeError at /admin/add/modelA/1/change/ 'dict' object has no attribute 'is_hidden' How to solve this problem? -
User Invitations based on invite links
my scenario is i have a teams model, team leads send out invite links to the team, url schema "domain/{team.id}/{team.name}/" i'm using dj_rest_auth for authentication, these invite links are sent to un-registered users. whne user clicks on url they are redirected to the signup view. now i need to add a user to the team(team id received in url) after they signup, i can't figure out how to pass the team id to user_sign_up post_save signal in allauth, django Sessionstore doesn't work as the key generated is different each time docs here, i'm new to django rest framework. i also looked at django globals, but that didn't help either. any help would be much much appreciated, app.views: from django.contrib.sessions.backends.db import SessionStore def inviteduser(request, pk, name): s = SessionStore() s['team-id'] = pk s.create() print(s.session_key) return redirect('http://localhost:8000/account/registration') accounts.signals: from allauth.account.signals import user_signed_up from django.dispatch import receiver from core.models import TeamMembers from django.contrib.sessions.backends.db import SessionStore @receiver(user_signed_up) def user_signed_up(request, user, **kwargs): s = SessionStore(session_key='gm0p279oeqvu385fy28btbyjzhak8a2j') # if request.session['team-id']: teamid = s['team-id'] # print(teamid) teammember = TeamMembers(member_id=user.id, team_id=teamid) teammember.save() i have a custom user model and a corresponding custom serializer. account.models: from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ … -
Anchor Tag href redirects to an untitled page
I want to use an <a/> tag which redirects to some page. But the problem is that when I click it, it doesn't open, and when I click on open in a new tab, it doesn't load properly. The url is correct but it won't load. You can see that the url is properly loaded, but the page wont load. But when I simply press enter in url, it loads somehow. Here's how I gave the href. <a href="{{HOST_BASE_URL}}art/search/art/all/"> It works if I manually add the value of {{HOSE_BASE_URL}} like this: <a href="http://localhost:8000/art/search/art/all/"> How do I resolve this?