Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I can join two ManyToManyField number to Integer Field in Django
I want to get the numbers of values in Two ManyToMany Field and compain both to one Integer Field by function (def) 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) viewers_count = models.IntegerField('Here I want to get the number of both field') -
Is there a django messaging library that actually works?
I have tried now almost all django one to one messaging systems Pinax_messages Django_messages None seem to work. -
'User' object has no attribute 'password_2'
I'm getting this error when I'm trying to register an user. The thing is, password_2 is just a field to check if the password was well written by the user (it'll return an error if they don't match). Therefore, password_2 is not in the model because it does not need to be stored along with the actual password. So I get this error because I added the field to my serializer. How can I solve it? This is the model: class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) This is the serializer: class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) email = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) password = serializers.CharField( required=True, … -
How do I prevent template tags from loading when template is cached?
I have an HTML file that I'm caching with {% cache %} template tag. In order to render the template, I'm loading several template tags: {% load static l10n ... etc %}. I do not want these to load when the template is cached. Would moving this load statement inside {% cache %} tag prevent them from loading if template is in cache? Example: {% cache TTL PRODUCT product.id %} {% load static l10n %} ... html code ... {% endcache %} -
Django - Get count of child objects associated with the Parent object
I am trying to get the count of existing child objects associated with the Parent object. I have a Parent Model like: class ParentObj(models.Model): name = .CharField(verbose_name='Name', max_length=50) Now I have these Child models. class ChileObj1(models.ParentForm): parent = models.ForeignKey(Product) name = models.CharField(verbose_name='Name', max_length=50) class ChileObj2(models.ParentForm): parent = models.ForeignKey(Product) name = models.CharField(verbose_name='Name', max_length=50) class ChileObj3(models.ParentForm): parent = models.ForeignKey(Product) name = models.CharField(verbose_name='Name', max_length=50) Now it could be that there are only two child objects for the parent object, instead of 3. How can get a count of them using a query. TIA -
I accidentally, deleted table of a model in db.sqlite (manually). How can I recreate it?
I accidentally, deleted table of a model in db.sqlite. How can I recreate it? When I run command 'python manage.py makemigrations' it works but when I run'python manage.py migrate' it says 'No migrations to apply' -
How can i put the commas?
Hello im trying to insert a image with a JavaScript loading the static folder from Django and i cant put the commas for the imagen (needed where are ##): '<a href="#" class=""><img src="{% static ##images/img_1.jpg## %}" alt="Image" class="img-fluid coche-img"></a>' What can i do? -
Session lost and user logs out on external redirect from payment gateway in Django Oscar
I've integrated a 3rd party payment gateway in Django Oscar. On checkout user is redirect to Payment Gateway where user fills payment details and on successful payment, the payment gateway post back success response to my custom URL on my website. But when I receive the response, user becomes anonymous, session data is lost and user is logged out of the website on redirect to ThankYou page. Please guide me if someone has solved this issue before. Thanks. -
got page not found error with url in django
This is urls.py: urlpatterns = [ path('', views.first_page.as_view(), name='first_page'), path('all_ads/', views.all_ads.as_view(), name='all_ads'), re_path(r'^all_ads/(?P<pk>\d+)/$', views.all_ads.as_view(), name='all_ads_filtered'), re_path(r'^ads_detail/(?P<pk>\d+)/$', views.AdsDetailView.as_view(), name='ads_detail'), ] I have this link in template.html: <a href="/ads_detail/?source_token={{Catalogue.source_token}}"></a> that returns a link like this: /ads_detail/?source_token=AYFWWw1k But, I got page not found error. -
Uncaught TypeError Cannot read property 'call' of undefined Bootstrap 5 , Django
I am using bootstrap5 with my Django project {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Doc</title> <link rel="stylesheet" href="{% static "css/bs/bootstrap.min.css" %}"> <link rel="stylesheet" href="{% static "css/selectBox.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Oswald&display=swap" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% block css %} {% endblock %} </head> <body> {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> </body> <script src="{% static "js/index.js" %}"></script> {% block js %} {% endblock %} </html> First I downloaded the bootstrap 5 js and css files and used as static file <head> <link rel="stylesheet" href="{% static "css/bs/bootstrap.min.css" %}"> </head> <body> <script src={% static "js/bs/bootstrap.bundle.min.js" %}></script> </body> Bootstrap 5 css is working perfectly but javascript is not working, I am trying to make a dropdown button, the dropdown is not working. Whenever I click drop down this errors are showing up selector-engine.js:18 Uncaught TypeError: Cannot read property 'call' of undefined at Object.find (selector-engine.js:18) at carousel.js:608 at i (event-handler.js:101) find @ selector-engine.js:18 (anonymous) @ carousel.js:608 i @ event-handler.js:101 load (async) C @ event-handler.js:196 on @ event-handler.js:224 (anonymous) @ carousel.js:607 (anonymous) @ bootstrap.bundle.min.js:6 (anonymous) @ bootstrap.bundle.min.js:6 selector-engine.js:18 Uncaught TypeError: Cannot read property 'call' of … -
how to update some fields of an object if it exists? django
I've made a project for a store sometimes happen for example we have :product = mouse , quantity=100 , buying_price = 10$ , in another time we add the same kind of product(mouse) in this case we have to prevent from creating another object quantity = 120,buying_price=12$ , in this situation i expect to (100 * 10+120 * 12)/220 in order to get the buying average . i have to implement this : ((quantity * buying_price + new quantity * new buying_price)/quantity + new quantity) class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() buying_price = models.DecimalField(max_digits=30,decimal_places=3) views.py def createNewProduct(request): form = ItemForm() if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() return render(request,'temp/add_item.html',{'form':form}) database : mysql -
how to make syntax highlighting on a website for your own language on django?
I'm making a website in django and I need to implement syntax highlighting of the LibSl language( currently this language is not used anywhere, so I need to do it myself). Are there any libraries on Django that could do this? I use html templates Django enter image description here -
Can't embedded a django backend html in a angular front-end
As mentioned in the question, I am trying to embed an html form web page located in a django backend in a front-end (maked with angular, in another server), but when I acces to the front-end page (where the backend page is embedded) the following error appears: [Error] Blocked autofocusing on a form control in a cross-origin subframe. [Error] Blocked a frame with origin "https://...{backend address}..." from accessing a frame with origin "http://...{frontend address}...". The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match. (x8) [Error] Refused to display 'https://...{backend address}.../register_student' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. [Error] Failed to load resource: the server responded with a status of 403 () (register_student, line 0) So in order to solve the problem I modificate settings.py file by adding MIDDLEWARE = [ ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', ... ] SESSION_COOKIE_DOMAIN=".ynsat.com" X_FRAME_OPTIONS = 'SAMEORIGIN' And I also modificate views.py with the follow signal: @xframe_options_exempt def register_student(request): ... The thing is the frontend page shows the iframe correctly, but when it send the form the error shown above appears. Here is my code: views.py ... @xframe_options_exempt def register_student(request): if request.method == 'POST': form … -
django - testing send_mail function in a view
I'm trying to test a send_mail function which is placed in the following view (skip to the end to see the send_mail execution): @login_required def item_create(request, idType, idSubType=None): type = Type.objects.get(id=idType) form = item_Form(request.POST or None) form.fields['subType'].queryset = SubType.objects.filter(type=type).order_by('name') if idSubType: form.fields['subType'].initial = SubType.objects.get(id=idSubType) form.fields['company'].queryset = request.user.profile.companies context = { 'form': form, 'title': 'INSERIMENTO ' + type.name.upper(), # primo tab dei dati anagrafici 'tab_active_1': True, } form_specs = None if type.name == 'Mezzi' and idSubType: subType = SubType.objects.get(id=idSubType) specs_name = subType.subTypeGroup.name form_class = getattr(forms, specs_name + 'Form') form_specs = form_class(request.POST or None) context['form_specs'] = form_specs context['title_specs'] = 'Dati Specifici ' + subType.name if request.method == 'POST': if form.is_valid(): if form_specs: if form_specs.is_valid(): item = form.save() specs = form_specs.save(commit=False) specs.item = item specs.save() else: return render(request, 'equipment/item_detail.html', context) else: item = form.save() mail_context = { 'base_url': settings.GESTIONALE_URL, 'subType': item.subType, 'brand': item.brand, 'model': item.model_type, 'serial_number': item.serial_number, 'supplier': item.supplier.legal_name, 'item_abs_url': item.get_absolute_url(), } payload = render_to_string('equipment/mails/new_item_message.html', mail_context) carlo = User.objects.filter(username__icontains='carlo.cogni').first() monica = User.objects.filter(username__icontains='monica').first() send_mail('Avviso inserimento nuova attrezzatura', payload, settings.EMAIL_HOST_USER, (carlo.email, monica.email), html_message=payload) ######### messages.success(request, f'Dati aggiornati correttamente', fail_silently=True) return HttpResponseRedirect(item.get_absolute_url()) else: return render(request, 'equipment/item_detail.html', context) else: form.fields['is_purchased_new'].initial = True return render(request, 'equipment/item_detail.html', context) If the objects is created correctly, an email is automatically sent. … -
How to migrate database in Django inside Docker
I have a docker-compose project with two containers running NGINX and gunicorn with my django files. I also have a database outside of docker in AWS RDS. My question is similiar to this one. But, that question is related to a database that is within docker-compose. Mine is outside. So, if I were to open a bash terminal for my container and run py manage.py makemigrations the problem would be that the migration files in the django project, for example: /my-django-project/my-app/migrations/001-xxx.py would get out of sync with the database that stores which migrations has been applied. This will happen since my containers can shutdown and open a new container at any time. And the migration files would not be saved. My ideas are to either: Use a volume inside docker compose, but since the migrations folder are spread out over all django apps that could be hard to achieve. Handle migrations outside of docker, that would require some kind of "master" project where migration files would be stored. This does not seem like a good idea since then the whole project would be dependent on some locals file existing. I'm looking for suggestions on a good practice how I can … -
Django save to database
models: class An(models.Model): an_studiu = models.SmallIntegerField(primary_key=True) class Meta: managed = False db_table = 'an' def __unicode__(self): return "{0} {1} ".format( self, self.an_studiu) forms: class ContactForm(forms.Form): ans=forms.CharField(label='An Studiu') class AnForm(ModelForm): class Meta: model=An AnFormset=inlineformset_factory(An,fields=['an_studiu'],extra=1,can_delete=False) views: from django.shortcuts import render from django.http import HttpResponse from .forms import ContactForm,AnForm, AnFormset def contact(request): form=ContactForm() return render(request,'form.html',{ 'form':form }) def add_an(request): form=AnForm() an_formset=AnFormset(instance=An) if request.POST: form=AnForm(request.POST) if form.is_valid(): an_studiu=form.save() return redirect('/index/') return render_to_response('addan.html', { 'form': form, 'formset': an_formset }, context_instance=RequestContext(request)) addan.html: <form method="POST"> {% csrf_token %} <h5>An:</h5> {{ form.as_p }} <input type="submit" value="submit"> </form> I work with postgres. I took some code from other sites but it still won't save in my database. I did the database setup. I don't think I have a problem here. My real problem is that I am new and I looked in the documentation and it didn't worked for me. Please help. -
How to change example format value of datefield in drf yasg (swagger)
Hello im using drf yasg library to implement swagger in my django based app. I have changed the date format in settings.py file to look like this: REST_FRAMEWORK = { "DATE_INPUT_FORMATS": ["%d-%m-%Y"], } Now when I try to test my endpoint in the swagger then I get example of date field in wrong format: { "birth_date": "2021-04-27", } And when I try to execute the request I receive the error: { "birth_date": [ "Date has wrong format. Use one of these formats instead: DD-MM-YYYY." ] } What is expected to receive but it's annoying to change the example date each time I want to use it. Any tips how to achieve the same format in the swagger example? -
RTSP wrapped with Content-Type: image/jpeg in StreamingHttpResponse
Was trying to wrap rtsp stream in StreamingHttpResponse and same is working completely fine with WSGI server in django but i need to implement this with ASGI app. Below code for reference. In ASGI it continuously loading due to while True loop but with WSGI it works fine. I am not sure it is happening because of WSGI or ASGI. def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def livecam_feed(request): return StreamingHttpResponse(gen(LiveWebCam()), content_type='multipart/x-mixed-replace; boundary=frame') class LiveWebCam(object): def __init__(self): self.url = cv2.VideoCapture("<RTSP link here>") def __del__(self): cv2.destroyAllWindows() def get_frame(self): success,imgNp = self.url.read() resize = cv2.resize(imgNp, (640, 480), interpolation = cv2.INTER_LINEAR) ret, jpeg = cv2.imencode('.jpg', resize) return jpeg.tobytes() -
How to add div at the end in django admin panel
In django admin panel, I want to add a div tag at the end of the models change page. Below the form mentioned here -
On migrating in django project it shows and error
ERROR "ValueError: Field 'stock' expected a number but got 'UNAVAILABLE'." here I even removed the field 'stock ' from model but still getting error. It is not migrating..... What I do now? Please Help? -
Django writeable nested serializer and django-polymorphic
Suppose I have the following models: class DataQuery(models.Model): name = models.CharField(...) class Entity(PolymorphicModel): class TargetType(models.IntegerChoices): Human = 1, _('Human') Animal = 2, _('Animal') targetType = models.PositiveSmallIntegerField(choices=TargetType.choices, null=False) dataQuery = models.OneToOneField(DataQuery, on_delete=models.CASCADE, null=True, related_name="targetEntity") class HumanEntity(Entity): name = models.CharField(...) def save(self, *args, **kwargs): self.targetType = Entity.TargetType.Human return super().save(*args, **kwargs) class AnimalEntity(Entity): numPaws= models.PositiveSmallIntegerField(...) def save(self, *args, **kwargs): self.targetType = Entity.TargetType.Animal return super().save(*args, **kwargs) with the following serializers: class HumanSerializer(serializers.ModelSerializer): name = serializers.TextField(...) class Meta: model = HumanEntity fields = ('name', ) class AnimalSerializer(serializers.ModelSerializer): numPaws = serializers.IntegerField(...) class Meta: model = AnimalSerializer fields = ('numPaws', ) class EntityPolymorphicSerializer(WritableNestedModelSerializer, PolymorphicSerializer): model_serializer_mapping = { HumanEntity: HumanSerializer, AnimalEntity: AnimalSerializer, } class Meta: model = Entity fields = '__all__' class DataQuerySerializer(WritableNestedModelSerializer): id = serializers.ReadOnlyField() name = serializers.CharField(), targetEntity = EntityPolymorphicSerializer() class Meta: model = DataQuery fields = ('id', 'name', 'targetEntity' ) I have a model DataQuery that has a 1:1 mapping with either an AnimalEntity or a HumanEntity model. If I serialize a DataQuery that has been created with a HumanEntity, I get the following (correct) output: { id : 1 name : "testQuery" targetEntity : { resourcetype : "HumanEntity", name : "John Doe" } } A POST call to my endpoint also works, the DataQuery … -
Django and Angular custom user role based permissions
I am building a shopping webapp in Django and Angular where I would like a shop owner to create a new shop account and have the privilege's to create, update and delete products from a dashboard view in angular front end. That specific shop account then will only have access to any products they create. I would then like the customer account to only have permission to view all products from all shop accounts but not have access to the dashboard view or creating, updating or deleting products. What I have? At the minute have a basic app where any user can create, view, update and delete a product once they login with a token. I tried setting up custom user accounts and using permission classes and this does not work and I am unable to find an example to restricting access on the angular front end from the django back end. What I want? Customer to register as a standard user and only have view products permissions. Shop owner to be able to register a new shop account and have permission to create products and only have permission to update or delete those products. Only allow shop owners to … -
Django: How to accept keys with white space with drf serializer?
I want to have a serializer that accepts json where keys might have white space and upper letters to benefit from DRF's out of the box validation, error handling and messages. e.g. { "Full Name": "Kelly Smith", "Age": 31, "Likes chocolate": true } and then in python: >>> serializer = Serializer(data=json_data) >>> serializer.is_valid(raise_exceptions=True) True >>> serializer.validated_data {"Full Name": "Kelly Smith", "Age": 31, "Likes chocolate": True} I thought I could remap the keys to a python readable name to be compliant with python variable name restrictions (using something similar to this) but I am not sure what would be the best approach. Note: I already saw this ticket but it does the inverse (serializing-out) of what I need (serializing-out) -
Django doesn’t detect change in migrations
I have a Django app and i added my migrations folders to gitignore file and migrated for the first time then i added a field user model and migrated again. all of migration process happened again but in migration Django didn’t apply the change. what should i do to apply my changes to the database without having to push the migrations folder to the server -
Django cross-relational query for custom model properties
I wish to use Django's F to easily get cross-relational information. I had a working form of what I wanted before, but I felt it was ugly and so I transitioned to making custom properties for my models as so: @property def stage(self): """Returns the competition's stage status by date""" now = timezone.now() if self.end_date and self.pub_date and self.close_date and self.start_date: if self.start_date > now: return "Launched" elif self.start_date < now < self.end_date: return "Commenced" elif self.end_date < now < self.close_date: return "Scoring" else: return "Ended" return "Inactive" In the past, I used a huge When/Case block and annotated this in. I prefer 'property' style of doing things because their values don't mess up when aggregating. (Eg. Team counts get overcounted when I do sums etc. and so I have to do them separately) However, now I get errors when I try to access: (Team->CompetitionTeam->Competition) F('competitionteam__competition__stage') Is there a way to do this? The errors are: (When debugging and trying to annotate the above) django.core.exceptions.FieldError: Cannot resolve keyword 'stage' into field. Just running straight from my code, it doesn't cough an error immediately after annotating, but only when the QuerySet in question is accessed. django.core.exceptions.FieldError: Unsupported lookup 'stage' for AutoField …