Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django REST API best practice for views
I am trying to write a REST API with Django Rest Framework using the following models:- class Group(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() users = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Player) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="groups_owned", on_delete=models.PROTECT ) class Player(models.Model): group = models.ForeignKey(Group, related_name="players", on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="players", blank=True, null=True, on_delete=models.SET_NULL, ) slug = models.SlugField() class Game(models.Model): slug = models.IntegerField() group = models.ForeignKey(Group, related_name="games", on_delete=models.CASCADE) date = models.DateField() venue = models.ForeignKey(Venue, null=True, on_delete=models.PROTECT) The frontend that is going to consume this API is going to have pages like this:- * Group Details * Group Players * Group Games ... I know how to use a ModelViewSet to expose a view that can be used to return serialized data from a particular group but I'm not sure whether to create different actions to cover each separate page that's going to be required in the front end. I seem to have two options:- A single view (/api/groups//) which returns everything that any consumer might need - so the group name, owner etc. as well as all of the details of all of the games and players of that group. This seems more like the "proper" way to me. But it means that the … -
Pass value to uWSGI from Django application
How can I pass the request.user.username to the uWSGI logger from Django? I want to generate the below log: [pid: 1|app: 0|req: 2/38] **REQUEST.USER.USERNAME** Also, I'm using Nginx as the webserver. -
How to find the difference in multipolygon geometric area in geodjango?
I have two mulitpolygons (say a state and a district) and I want to find the difference in these two polygons and plot the difference in map as a vector layer in openlayer6. How can I calculate the difference using geodjango and return the geometry. Example code is : state = StateBoundary.objects.filter(id=1) dist = DistrictBoundary.objects.filter(id=10) I want something like this diff_area = state - dist I found the geodjango difference query here https://docs.djangoproject.com/en/3.2/ref/contrib/gis/functions/#django.contrib.gis.db.models.functions.Difference but dont get any example on how to do it using 'difference'. -
django app :shopping list with items taken from dropdown list and sum of items
I'm trying to develop new app in django. I'm really beginner. I have a little experience with django and python and very little, almost zero with java-script. Description of project: My first basic concept we can compare to shopping list. I want to create a dropdown list, which takes arguments(items) from database (model in django). this argument should be passed over to window below, where i can choose amount of items. _______________________________________________________________ | _________ | | item: |________| <:amount of item | | | |_____________________________________________________________| Next "item" and "amount of items" should be passed over to list below for example: item1 : amount of item1 item2 : amount of item2 item3 : amount of item3 item4 : amount of item4 sum of all amounts At the bottom o list i want to show sum of all items. I don't know where to start and I need help. Any ideas? -
DRF 3 - Making an Endpoint for Many to Many Table
I'm new to django rest framework and i am trying to understand how to make an endpoint to create and update a many to many relation table. models.py class OnlineClass(models.Model): ... teacher = models.ForeignKey(to=User, related_name='online_class', on_delete=models.CASCADE) students = models.ManyToManyField(to=User, through='Enrollment') ... class Enrollment(models.Model) online_class = models.ForeignKey(OnlineClass, on_delete=models.CASCADE) participant = models.ForeignKey(User, on_delete=models.CASCADE) For the user model i was extending it from the base user model from django. serializers.py class OnlineClassSerializer(serializers.ModelSerializer): participants = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),many=True) class Meta: model = OnlineClass fields = [ ... 'participants', ] extra_kwargs = {'participants': {'required': False,},} class EnrollmentClassSerializer(serializers.ModelSerializer): online_class = OnlineClassSerializer(many=True) participant = UserSerializer(many=True) class Meta: model = Enrollment fields = ['id','online_class','participant'] views.py class OnlineClassListAPIView(ListCreateAPIView): serializer_class = OnlineClassSerializer queryset = OnlineClass.objects.all() permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): return serializer.save(owner=self.request.user) def get_queryset(self): return self.queryset.all() class OnlineClassDetailsAPIView(RetrieveUpdateDestroyAPIView): serializer_class = OnlineClassSerializer permission_classes = (permissions.IsAuthenticated, IsOwner,) queryset = OnlineClass.objects.all() lookup_field = "id" def get_queryset(self): return self.queryset.all() Now what i would like to do is make an endpoint to add participants to the OnlineClass Table by adding data to the Enrollment Table, i have been looking other solutions but all i got was adding participants when the OnlineClass is created, but what i would like to do is adding the participants when the … -
Django Edit after Running like Webflow
I am working on a website which needs to be able to be edited after it is hosted. Thus it needs functionality where for example the text elements can be changed after it is hosted, just like this can be done with Webflow ?edit. Is there a way to do this besides giving all elements a variable name and editing them inside of the Django Admin dashboard? I have tried Django CMS but it only seems to work with websites build using Django CMS itself and not when I import existing templates. Is there anyone who has suggestions how this could be done? Thanks in advance -
Error running wsgi application: ModuleNotFoundError
I am trying to host my local web app on pythonanywhere. [Beginner to Django and web-development] I am facing the following error while launching the app: Error running WSGI application 2021-04-26 21:46:32,020: ModuleNotFoundError: No module named 'myapp' 2021-04-26 21:46:32,020: File "/var/www/username_pythonanywhere_com_wsgi.py", line 16, in <module> 2021-04-26 21:46:32,020: application = get_wsgi_application() 2021-04-26 21:46:32,020: 2021-04-26 21:46:32,020: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-04-26 21:46:32,020: django.setup(set_prefix=False) 2021-04-26 21:46:32,020: 2021-04-26 21:46:32,020: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2021-04-26 21:46:32,021: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-04-26 21:46:32,021: 2021-04-26 21:46:32,021: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-04-26 21:46:32,021: self._setup(name) 2021-04-26 21:46:32,021: 2021-04-26 21:46:32,021: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup 2021-04-26 21:46:32,021: self._wrapped = Settings(settings_module) 2021-04-26 21:46:32,021: 2021-04-26 21:46:32,021: File "/home/username/.virtualenvs/web-virtualenv/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-04-26 21:46:32,021: mod = importlib.import_module(self.SETTINGS_MODULE) File locations: The settings.py file is located at: /home/username/WebDev/Website/Django/MyApp/myapp/myapp I have modified '/var/www/username_pythonanywhere_com_wsgi.py' file as: """ WSGI config for myapp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os import sys sys.path.append("/home/username/WebDev/Website/Django/MyApp/myapp") os.environ('DJANGO_SETTINGS_MODULE', 'myapp.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I have looked at the similar question on stackoverflow but still cant figure out what is wrong at my end. Any pointers/help would be appreciated. -
Field 'doors' expected a number but got ''
Error: Traceback (most recent call last): The above exception (invalid literal for int() with base 10: '') was the direct cause of the following exception: File "/home/andres/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/andres/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./wallacar_app/views.py", line 124, in getDoors doors = Coche.objects.exclude(doors__isnull=True).exclude(doors__exact='').order_by('doors').values_list('doors').distinct() File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/query.py", line 949, in exclude return self._filter_or_exclude(True, args, kwargs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/query.py", line 966, in _filter_or_exclude_inplace self._query.add_q(~Q(*args, **kwargs)) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1396, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1418, in _add_q split_subq=split_subq, check_filterable=check_filterable, File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1350, in build_filter condition = self.build_lookup(lookups, col, value) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1196, in build_lookup lookup = lookup_class(lhs, rhs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/lookups.py", line 25, in __init__ self.rhs = self.get_prep_lookup() File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 117, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "/home/andres/.local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1827, in get_prep_value ) from e Exception Type: ValueError at /wallacar_app/ajax/doors/ Exception Value: Field 'doors' expected a number but got ''. models.py class Coche(models.Model): doors = models.ForeignKey('CocheDoors', on_delete=models.CASCADE) class CocheDoors(models.Model): doors = models.IntegerField(verbose_name="Puertas", primary_key=True, validators=[RegexValidator(regex='^[0-9]{1}$',message="Las puertas solo pueden tener una cifra")]) def __str__(self): return str(self.doors) views.py def getDoors(request): if request.method == "GET" and request.is_ajax(): doors = Coche.objects.exclude(doors__isnull=True).exclude(doors__exact='').order_by('doors').values_list('doors').distinct() doors … -
list all active Sessions when using django-user-sessions
I'm currently working on a django project and I'm using the django-user-sessions library. This library overrides the django contrib Sessions and offers possibilities for user session management. What I want to do is to list all active sessions, with the default django Session it would be something like this : Session.objects.filter(session__expire_date__gt=datetime.now()) The problem is I can't do it when I use django-user-sessions because we have to turn off the use of the default Sessions. All I could do with it is list a user's sessions user.session_set.filter(expire_date__gt=datetime.now()) Please, if you are familiare with this library can you guide me? Already checked the documentation but it doesn't tell how. -
How to get the values of dynamically input fields and process them in Django views
I have an input field that can be added dynamically in my template html file. Now, I want to get all those values to process them in the views. However, I am getting only the last value Any idea on how to grab all the values? Thank you and here is my code Html file <div class="form-group col-md-6"> <label>Required Skills</label> <div class="input_skills_wrap"> <div> <input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-primary add-more-skill" type="button"><i class="glyphicon glyphicon-plus"></i></button> </div> </div> </div> <script> $(document).ready(function(){ //EMPLOYMENT SKILLS $(".add-more-skill").click(function(e){ e.preventDefault(); $(".input_skills_wrap").append('<div><input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-danger remove-skill" type="button"> <i class="glyphicon glyphicon-minus"></i></button></div>'); }); $(".input_skills_wrap").on("click", ".remove-skill", function(e){ e.preventDefault(); $(this).parent('div').remove(); }); </script> views.py def post_internship(request): if request.method == 'POST': skills = request.POST['internship_skills[]'] print(skills) return render(request, 'post_internship.html') -
what is select_related attribute in dajngo generic class,can someone explain what this implies?
class PostDetail(SelectRelatedMixin,generic.DetailView): model=models.Post select_related=('user','group') This is the snippet and the instructor told its for associating user with post and the group with post. what exactly does this implies and how its get associated? -
image not getting uploaded in django via model form but getting added from the admin panel
So in my django project , I have a page where user can fill details about his profile via a form. The form is as follows : class VendorProfileForm(ModelForm): class Meta: model = Vendor fields = ['name', 'address', 'pincode', 'phone', 'email', 'image1', 'image2', 'image3', 'image4'] The model 'Vendor' to which the form is referring to is as follows : class Vendor(models.Model): name = models.CharField(max_length=255) email = models.EmailField(blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) phone = models.CharField(blank=True, null=True, max_length=20) address = models.CharField(blank=True, null=True, max_length=200) image1 = models.ImageField(upload_to='shop_images/', blank=True, null=True) image2 = models.ImageField(upload_to='shop_images/', blank=True, null=True) image3 = models.ImageField(upload_to='shop_images/', blank=True, null=True) image4 = models.ImageField(upload_to='shop_images/', blank=True, null=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) The view used is as follows: @login_required def vendor_profile_details(request): if request.method == 'POST': form = VendorProfileForm(request.POST) if form.is_valid(): vendor = form.save(commit=False) vendor.created_by = request.user vendor.save() return redirect('vendor_admin') else: form = VendorProfileForm() return render(request, 'vendor_profile_details.html', {'form': form}) And the template used for the frontend part 'vendor_profile_details.html' is as follows: {% extends 'base.html' %} {% block title %}Profile details | {% endblock %} {% block content %} <h1 class="title">Finish your profile</h1> <form method="post" action="." method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-dark is-uppercase" … -
How to use django-ckeditor in my template
I want to use RichTextField in my template.They can post own blog content who log in my site. So they can type in RichTextField. -
No reverse match error in Django getting error
enter image description here enter image description here enter image description here enter image description here enter image description here