Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UniqueConstraint doesn't apply
I'm on Django 2.2 and try to aplly a UniqueConstraint with conditions. But It seems that it's not applied, I still can add the entries breaking this constraint. My simplified model: class Size(models.Model): name = models.CharField(max_length=200, null=False) matching_equipments = models.ManyToManyField('Equipment', through=Equipment.sizes.through, blank=True,related_name='matching_sizes') is_active = models.BooleanField(default=True) class Meta: default_permissions = () ordering = ['id'] constraints = [ models.UniqueConstraint(fields=['name'], condition=Q(is_active=True), name='unique_sizename_active') ] The objective is to never have 2 sizes with the same name active at the same time. The migrations run well but nothing is applied on the database (mySQL) Any idea? -
Alternative to JNLP for Python
We have Django server as beck-end and React as front-end, we want to create page that interact with client and use its resources, for example its NIC to access devices on client LAN and for performing some actions on client, Something like JNLP agent in Java. Can it be done with Python? -
Linking items(to-do) to users and restricting items(to-do) to specific users
I'm trying to further expand this app from one user to multiple users. Whereby each individual user's todo-list will be displayed on the home(index) page when logged in. I was able to make progress by linking the users and the todo list in the models.py i.e.- Doer and Task respectively. But I can't display nor create individual items for each invdividual user. Would be grateful for your help and explanation too. Thanks Models from django.db import models from django.contrib.auth.models import User # Create your models here. class Doer(models.Model): user = models.OneToOneField(User,null = True, on_delete=models.CASCADE) nationality = models.CharField(max_length=120,blank=True) def __str__(self): return self.user class Task(models.Model): doer = models.ForeignKey(Doer, null = True, on_delete=models.CASCADE) title = models.CharField(max_length=300) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Views from django.shortcuts import render,redirect from.models import Task from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import TaskForm,UserRegisterForm,DoerForm def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) a_form = DoerForm(request.POST) if form.is_valid() and a_form.is_valid(): user = form.save() doer = a_form.save(commit = False) doer.user = user doer.save() messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() a_form = DoerForm() context = {"form" : form, "a_form": a_form} … -
Django+SharePlum and Rich Text Fields in SharePoint
Using Python with Django and accessing my SharePoint list via SharePlum. In SharePoint the description field is Rich Text. When I bring that into my template file using Django it is still showing tags. For example: <div class="ExternalClass5E185857E6A14259838D47F8D5A086FF">test</div> Is there any way to render this with no tags? -
Close Callout Message in Zurb Foundation after a period of time with jquery
I really don't understand the Foundation jquery. I create a message using Foundation and DJango. I just want the message to flash for a few seconds and the close. I would also like to close a "success" callout at a different spend than say an "alert.: this is the message in django & Foundation. <div class="grid-x > <div id='messages' class="cell large-12 large-offset-0 medium-12"> {% if messages %} {% for message in messages %} <div class="callout {% if message.tags %}{{ message.tags }}{% endif %}" data-closable> <button class="close-button" aria-label="Dismiss alert" type="button" data-close> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> {% endfor %} {% endif %} </div> </div> thank you, -
How to use own python modules without rewriting all paths in Django
I am making a website with django that uses my python codes. my directory is like this: \mysite \myApp \myCodes \common \deploy \src \mySite my codes in /myCodes/src have a lines at the beginning like: import sys sys.path.append('../deploy') sys.path.append('../common') some codes in /common and /deploy also have the same lines and they work fine but when I use my codes in from the view.py they can't find each other, I added \myCodes as an app in settings.py and when I manually change the import dir (import myCodes.common.myFunction) it is fine but it seams to be unnecessary to manually change all of the imports, is there away I can execute the codes as they are? P.s: I also use directory as input and open and write files in my functions that don't work (the are all in \myCodes directory) -
I'm trying to activate a virtual environment, using Windows 10 Powershell . but it's getting activated
PS C:\django_proj\venv> cd scripts PS C:\django_proj\venv\scripts> activate PS C:\django_proj\venv\scripts> -
Multiple one-to-one relations vs one-to-many django
I want to do something unusual. I will explain the issue: I got 2 models: Device and SensorColor They look like this: class SensorColor(models.Model): device = models.ForeignKey( "Device", on_delete=models.CASCADE, related_name="device_sensor" ) sensor = models.CharField(max_length=25, blank=False, null=True) status = models.CharField(max_length=25, blank=False, null=True) color = models.CharField(max_length=25, blank=False, null=True) class Device(models.Model): upper_sensor_color = models.ForeignKey( SensorColor, on_delete=SET_NULL, blank=True, null=True, related_name="upper_sensor_device", ) left_sensor_color = models.ForeignKey( SensorColor, on_delete=SET_NULL, blank=True, null=True, related_name="left_sensor_device", ) right_sensor_color = models.ForeignKey( SensorColor, on_delete=SET_NULL, blank=True, null=True, related_name="right_sensor_device", ) As you can see, every device has 3 sensors where I want to store a status and a color. Instead of doing a one-to-many relation (device has multiple sensors) I do multiple one-to-one relations. This is because I want to do the following: self.device.upper_sensor_color.color = Color.GREEN When a device sends data (every 10min) it needs to check if there is already a SensorColor for the Device, if not set it. I do this like this: def update_upper_sensor(self): # get last sensor status for device (mongodb) latest_status = self.device_sensor_db.get_latest_status( self.device.id, Sensor.UPPER ) if latest_status: if self.device.upper_sensor_color: self.device.upper_sensor_color.color = latest_status["color"] self.device.upper_sensor_color.status = latest_status["status"] else: upper_sensor = SensorColor( device_id=self.device.id, sensor=Sensor.UPPER, status=latest_status["status"], color=latest_status["color"], ) upper_sensor.save() self.device.upper_sensor_color = upper_sensor return Now, my question is: is this better (performance wise), then … -
Signaling mechanism for webRTC using simpleWebRTC js library and backend in django
I am trying to build video conferencing web application where multiple people can join the call and there will be video/audio/data transmission. I researched a lot for this. What i understand is we can achieve this using webRTC protocol. I started doing research for js libraries and i came to know for simpleWebRTC. I want to develop with backend as a django. I tried to run sample demo code from https://www.sitepoint.com/webrtc-video-chat-application-simplewebrtc/. but i am not able to establish connection with socket.io which is simplewebRTC signaling sandbox server. I tried with node express server as well, but still i got the same error:- net::ERR_FAILED. This error occured in simplewebrtc-with-adapter-js while making connection. What would be the correct technologies to achieve this type of functionality? Front-end webRTC libraries:- simplewebRTC/ EasyRTC/ Any else apis? Signaling mechanism:- What and how can we use to connect with webRTC? Backend:- Node js/Django? I still confused with the signaling protocols/STUN/TURN servers as we have to define the servers by our self. simpleWebRTC is not providing that which we can use in production. Any help would be much appreciated! -
How can i take reservation date's and number of days
I do car rental site as homework with django but i couldn't find how to get the reservation dates and the day difference between , help me please . -
Django form received wrong data from request.POST
I added a filter to my form, so that it only displays the options that belong to the user when request.GET, everything works fine at first, but next time it runs, something goes wrong. It shows the 'QueryDict' object has no attribute 'id' error, so by checking, I found that the user variable in the form received the data sent by request.POST. This should not happen, I guess? Here is my code Views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST,instance=request.user.profile) if profile_form.is_valid(): profile_form.save() messages.success(request,_('success!')) return redirect('character-manage') else: messages.error(request,_('something is wrong.')) else: profile_form = ProfileForm(instance=request.user.profile,m_user=request.user) return render(request,'corp/profile.html',{ 'profile_form':profile_form }) Forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('pcharacter',) def __init__(self,user=None,**kwargs): super(ProfileForm,self).__init__(**kwargs) if user: self.fields['pcharacter'].queryset = EveCharacter.objects.filter(bounduser=user) When I add print(user) under the __init__ function, refresh the form page and I will get a user object, but when I submit the form it will show something like this <QueryDict: {'csrfmiddlewaretoken': ['*****'], 'pcharacter': ['2']}>What went wrong? Any suggestions or guidance are appreciated. -
Can I delete the models.py file in django from my app and use another file as a model using another name?
I was thinking that if I need a model for a specific app in django project, can I use different .py file as a model after deleting models.py file? Let's suppose I want to use another_model.py instead of the models.py, is it possible? If possible then how? And if not possible then why? Can you elaborate please -
can't get the value of OneToOne relationship queries in django_graphql
The default Django model have been extended using OneToOne link with User model (some extra fields added to it). Here is my model: class Driver(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) father_name = models.CharField( max_length=20, blank=True, verbose_name="Father's Name" ) national_id = models.CharField( max_length=10, blank=True, verbose_name="National ID" ) phone_no = models.CharField( max_length=11, blank=True, verbose_name="Phone Number" ) and the following is my schema (if needed): class DriverType(DjangoObjectType): class Meta: model = Driver class Query(object): all_drivers = graphene.List(DriverType) def resolve_all_drivers(self, info, **kwargs): return Driver.objects.all() Problem Definition: The default User of django (django.contrib.auth.model) has some fields like first_name, last_name, email, etc. According to the OneToOne relationship between User and Driver models, it is expected to access that data. sample query: query { allDrivers{ id verified user { first_name } } } Error message: "Cannot query field \"user\" on type \"DriverType\".", -
Why do Django REST Framework Renderer and Parsers have to be instantiated and do not offer their key methods as static/class methods?
Like Djangos rest_framework.JSONRenderer it needs to be instantiated like json = JSONRenderer().render(serializer.data) in order to use the render method. What's the background, that render() is not offered as a static/class method? -
user_change_password() got an unexpected keyword argument 'extra_context'
Django 3.0.7 When I try to change password in admin site, I get TypeError at /admin/auth/user/1/password/ user_change_password() got an unexpected keyword argument 'extra_context' Namely I pressed "this form" link: More details Environment: Request Method: GET Request URL: http://localhost:8000/admin/auth/user/1/password/ Django Version: 3.0.7 Python Version: 3.8.0 Installed Applications: ['admin_aux', 'images.apps.ImagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'sidebars', 'general', 'categories', 'marketing', 'home', 'authors', 'taggit', 'cachalot', 'django_cleanup.apps.CleanupConfig', 'widgets', 'code_samples', 'hyper_links', 'polls', 'applications', 'videos', 'quotations', 'languages', 'people', 'arbitrary_htmls.apps.ArbitraryHtmlsConfig'] Installed Middleware: ['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'] Traceback (most recent call last): File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/michael/PycharmProjects/pcask/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/michael/PycharmProjects/pcask/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/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner return view(request, *args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) Exception Type: TypeError at /admin/auth/user/1/password/ Exception Value: user_change_password() got an unexpected keyword argument 'extra_context' Could you help me understand how to localize this problem and maybe you even can help me … -
Django form manytomany field not saving to database
I am new to Django and i am working on a website where user can submit a post. Django Form is not saving in database when i have manytomany field in model. I do not know if i can achieve this in Django, I want to attached other user names to the post so that when i submit the form the user name is selected automatically when i check on the post in admin. I will attach a screenshots for clarity. This image below is my form, as you can see 'My post' is the image_caption while 'andy' is another user name, i want 'andy' selected automatically in manytomany field when form is submitted. This is what i want when the form is submitted then i check in admin. The other user name (andy) is selected in manytomany field when the form is submitted. I did this manually Model: class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) image_caption = models.TextField(blank=True, null=True) tag_someone = models.ManyToManyField(User, related_name='tagged_users', blank=True) Forms: class PostForm(forms.ModelForm): class Meta: model = Post fields = ( 'image_caption', 'tag_someone', ) Views: def upload_view(request): ImageFormset = modelformset_factory(File, fields=('files',), extra=20) if request.method == "POST": form = PostForm(request.POST) formset = ImageFormset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): … -
DRF how to add FK user to group with limit?
How to add user to some Group but group must have limit of 5 users, if group has reached limit create new group. Ty for any help! Models: class Group(models.Model): name = models.CharField(max_length=256) class Membership(models.Model): name = models.ForeignKey(Group, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE, ) class Meta: verbose_name_plural = 'Membership' verbose_name = 'Memberships' unique_together = ('user', 'choice') def __str__(self): return '%s: %s' % (self.choice.question, self.choice) serializer: class MembershipSerializers(serializers.ModelSerializer): class Meta: model = Membership fields = '__all__' View class GroupViewSet(ModelViewSet): serializer_class = MembershipSerializers queryset = Membership.objects.all() http_method_names = ['get', 'post'] permission_classes = [IsAuthenticated] -
Filtering a django QuerySet by a previously ordered queryset
I am trying to order a queryset by distance from an input location. I am able to order the original queryset that contains the point fields, however when I use that queryset to filter a query on another model then it returns the queryset unordered. The code is as follows: Models: class EnglandSpine(models.Model): urn = models.CharField(db_column='URN', primary_key=True, max_length=10) schname = models.CharField(db_column='SCHNAME', max_length=150, blank=True, null=True) postcode = models.ForeignKey(Postcodes3, to_field='pc', on_delete=models.CASCADE, db_column='POSTCODE', max_length=10, blank=True, null=True) class Postcodes3(models.Model): gid = models.AutoField(primary_key=True) pc = models.CharField(max_length=10, blank=True, null=True, unique=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) the_geom = gis_models.PointField(blank=True, null=True) def __str__(self): return self.pc objects = GeoManager() class Meta: managed = True db_table = 'postcodes3' I am able to retrieve an ordered list of postcodes with the following view views.py class PCSearch(TemplateView, SingleTableView): template_name = 'schoolData/pcs.html' def get(self, request): form = PostSearch() return render(request, self.template_name, {'form':form}) def post(self, request): form = PostSearch(request.POST) if form.is_valid(): pcps = form.cleaned_data['Postcode'] pc = pcps.replace(' ','') d = form.cleaned_data['Distance'] ss = form.cleaned_data['schtype'] gs = form.cleaned_data['gentype'] adms = form.cleaned_data['seltype'] pcr = Postcodes3.objects.get(pc=pc) area = (pcr.the_geom, Distance(mi=d)) pcs = Postcodes3.objects.filter(the_geom__distance_lte=area).values('pc') pcss = pcs.annotate(distance=GeometryDistance("the_geom", pcr.the_geom)).order_by("distance") Finally I would pass the pcss variable through one more filter to get all the schools... results … -
How to run multiple sites from one instance of Django?
I am using Django as the back end and Nuxt as the front end, with Postgres as the database. I would like to have different tables/databases for each domain. The Django code and the Nuxt code will be the same for all sites. The way the app is set up, it requires different domains to have different databases or at least different tables. At the moment, I am thinking I need to create a separate installation of Django/Nuxt for each domain. But I am wondering if there is a better way? -
Django serializer ManyToMany and return name instead of id
My models: class Category(models.Model): name = models.Charfield().. code = models.Charfield()... class Movie(models.Model): name = models.Charfield().. categories = models.ManyToManyField(Category) My serializer class MovieSerializer(serializers.ModelSerialier): class Meta: model= Movie fields = ['name', 'categories', ] When i get a Movie by id it returns: [ {"name": "My Movie", "categories": [1, 2, 3], } ] I want my response to be : .... "categories": ["Fun", "Adventure", ...] -
How to display Historical table of django-simple-history in django admin site?
I have implemented Historical tracking of changes to objects in django using django-simple-history https://django-simple-history.readthedocs.io/en/2.10.0/index.html I have mentioned a field history in Model using which I can query an object's history. history = HistoricalRecords() There us also a table created in the database with name appname_historicalmodelname. I want to display this table appname_historicalmodelname in django admin where in we have list of records sorted by history_time. As I don't have a Model class for that History table, I'm unable to use admin.site.register(HistoricalModelName). Please help me display this table in django admin site. django: 1.11 python: 2.7 -
Maps java script API to Django project
I am creating a real estate web platform with Django and postgresql back-end. I have implemented maps API in my HTML template in order to show where the real estate is located. The code: <!--Map--> <div class="row mb-5"> <div class="col-md-12"> <style> #map{ height:250px; width: 100%; } </style> <div id="map"></div> <script> function initMap(){ var myLatLng = {lat:-33.90, lng:151.16}; var options = { zoom:10, center:myLatLng }; var map = new google.maps.Map(document.getElementById('map'),options); } </script> </div> </div> Markers will be added in the next step because I have to figure out how I can retrieve my LAT and LNG values from the database and display them inside the script. Does anyone have the answer? To explain that a bit further, I want to make something like <script> function initMap(){ var myLatLng = {lat:{{listing.geo_lat}}, {{listing.geo_lng}}}; var options = { zoom:10, center:myLatLng }; But I have tried that and it seems that either google api cant read the proper format of my values or listing.geo_lat is not properly working inside the script. -
Django: drop duplicated lines from Queryset after joining two models
I would like to create a table with [for loop] function from a Queryset in my html templates. There are two models as shown in the codes below. After joining two models with select_related, there will be duplicated lines, and I would like to find the line with the latest date. I have tried Order.objects.all().select_related('inspection'), but I couldn't find a way how I can remove the duplicated lines and aggregate the order num field by ', '.join function. Can you please help me to find a script that creates the [output_queryset] as shown below? Python 3.8 Django 3.0 models.py class Inspection(models.Model): RESULT_CHOICES = ( ('Passed', 'Passed'), ('Failed', 'Failed') ) inspection_id = models.CharField(max_length=30, primary_key=True) result = models.CharField(max_length=50, null=True, blank=True, choices=RESULT_CHOICES) class Order(models.Model): inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE) ordernum = models.CharField(max_length=50) departure_date = models.DateField(auto_now=False, null=True, blank=True) Example dataset inspection_list = [{'inspection_id': 'BN123', 'result': 'Passed'}] order_list = [ {'id': 1, 'inspection_id': 'BN123', 'ordernum': 'S1', 'departure_date': '2020-07-01'}, {'id': 2, 'inspection_id': 'BN123', 'ordernum': 'S2', 'departure_date': '2020-06-01'}, {'id': 3, 'inspection_id': 'BN123', 'ordernum': 'S3', 'departure_date': '2020-06-25'} ] output_queryset = [ {'inspection_id': 'BN123', 'departure_date': '2020-06-01', 'result': 'Passed', 'ordernum': 'S1, S2, S3'} ] -
Django: Two relationships between two models
I'm struggling with the creation of two models which have two relationships. My goal is that a person can own multiple objects, and always has a favorite object (which they own). So to be precise the constrains could be summed up like this: 1:n relationship Person - Object (a person [exclusively] owns multiple objects) n:1 relationship Person - Object (favorite object, every person has ONE favorite object) person.(favorite object).owner = person (a person must own their favorite object, that makes the n:1 relationship of the favorite object more like an "optional 1:1 from the object's perspective") class Person(models.Model): favorite_object = models.ForeignKey('Object') class Object(models.Model): owner = models.ForeignKey(Person) First of all, I get an error stating that I should add a related_name to help solve the reverse reference and I wonder what is the best thing to do here since the favorite relationship is optional from an object's perspective. Do I alter owner to be owner = models.ForeignKey(Person, related_name="+") to avoid the reverse reference in the first place? Secondly, how do I create objects in the first place? They depend on each other. I cannot create a user without having a favorite object and I cannot create an object without knowing its … -
how to filter value in django where 0<a<10
Guys i am filtering in django values from db.I want to filter for condition 0<a<10. i tried the following way: School.objects.filter(a__lt=10 , a__gt=0) but this option is not effictive and brings wrong results. Any idea how to make it efficient way ? Any help is appreciated