Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to insert data to my DB when using another model's field in my form?
I have two different models: Trainer and User. I'm pulling in the trainer_price field from Trainer into my form in User. Please note that I'm also not using a foreign key. The problem I'm having is that the trainer_price is not getting inserted and the default value of 0 is there, which is not what I want. The way the User form works is they fill out their name, address, email and the trainer_price is automatically populated once they selected a trainer. It's also a read-only field. Here's what I've tried so far: user views.py def buyer(request): user_form = UserForm() trainer_listing = Trainer.objects.get(id=15).trainer_price context = {'user_form':user_form, 'trainer_listing':trainer_listing} if request.method == "POST": user_form = UserForm(request.POST) if user_form.is_valid(): user_form.save() return redirect("/success_page") return render(request, "user/user_form.html", context) forms.py class UserForm(forms.ModelForm): Fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'John Doe'})) Email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) Mobile = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '312-222-2222'})) Address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '1234 Main St'})) City = forms.CharField() State = forms.ChoiceField(choices=STATES) zipcode = forms.CharField() trainer_price = forms.DecimalField(label="Trainer Price", required=False, widget=forms.TextInput(attrs={'readonly':'readonly'})) class Meta: model = User fields = ['Fullname','Email', 'Mobile', 'Address', 'City', 'State', 'zipcode', 'trainer_price'] Any help in the right direction would be great! -
Not able to iterate through QuerySet results with Django
I'm new to Django and I'm experiencing issues with QuerySets. I am experimenting and trying to get to a field using the Bid.objects.filter method. It's constantly coming up with none if I use any filters (even when I type in an exact match like itemID = "Monkey517"). But if I do an "all" search, it comes up with tons of query sets that I don't know how to iterate through. I'm using examples I found online and I get the error that "'QuerySet' object has no attribute 'itemID'" or 'QuerySet' object has no attribute 'highestBidder' I'm not sure exactly how to get at each Query set that is inside a larger query set. It's all kind of confusing to me. Can anyone clear this up for me? Thanks! Below is my relevant code: views.py: def closeAuction(request): username = request.POST.get("username") itemID = request.POST.get("itemID") query = Bid.objects.all() for queries in query.iterator(): print(query.itemID) return render(request, "auctions/index.html") Models.py: class Bid(models.Model): itemID = models.CharField(max_length=64) newBid = models.IntegerField() highestBidder = models.CharField(max_length=64) post.html: {% if user.is_authenticated %} <form name="closeAuction" action="/closeAuction" method="post" > {% csrf_token %} <input autofocus class="form-control" type="hidden" name="username" value={{user.username}}> <input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}> <input class="btn btn-primary" type="submit" value="Close Auction"> {% endif %} </form> -
Easiest way to add {{ variable }} from different related model in one template
I got a question. I'm wondering what's the easiest way to add different {{ variable }} from different related model in one template. I'd like to add some information related to seller rating: def total_seller_ratings(self): return self.seller.rating_seller.count() def avg_seller_ratings(self): return self.seller.annotate(avg_ratesugar=Avg('rating_seller__ratesugar')).order_by('-avg_ratesugar') Create a template tag from Middleware? Or is any fastes solution to add another model on my view? I got a main view for my main page: #Channel MAIN PAGE @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class ChannelMainPage(generic.DetailView, FormMixin): model = Channel context_object_name = 'channel' template_name = 'channel_detail.html' form_class = ChannelChatForm def get_context_data(self, **kwargs): context = super(ChannelMainPage, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.channel = self.object form.instance.user = self.request.user form.save() return super(ChannelMainPage, self).form_valid(form) else: return super(ChannelMainPage, self).form_invalid(form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) def get_success_url(self): return reverse('channel:channel_detail',kwargs={"slug":self.object.slug}) models.py class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='channel/') date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField('Make it happen', default=False) class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) … -
how can I filter out the geometry field in the request using django-rest-framework-gis
I have this serializer: serializer.py from rest_framework import serializers from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import UsStatesG class UsStatesSerializer(GeoFeatureModelSerializer): class Meta: model = UsStatesG geo_field = "geom" id_field = False fields = ('st_fips', 'st_name', 'st_abbr') read_only_fields = ('st_fips', 'st_name', 'st_abbr') auto_bbox = True views.py from .models import UsStatesG from .serializer import UsStatesSerializer class StatesViewSet(viewsets.ModelViewSet): queryset = UsStatesG.objects.all() serializer_class = UsStatesSerializer I'm using the django-rest-framework-gis I want to dynamically decide if i want to include the geometry (geo_field) in the response or not. Sometimes I just want to get the names of the spatial units, (i.e. states names, abbreviations, zip codes etc.) without also including the geometry. It makes the request faster this way. Is there any property like i.e. returnGeometry: True | False How can I do this? thanks! -
PyCharm doesn't resolve Django apps but the project works
This is the project structure generated from having runt django-admin startproject school and python manage.py startapp quiz: In INSTALLED_APPS I've added: "quiz.apps.QuizConfig", In order for this project to execute correctly, in school/quiz/views.py I have to import e.g. models from quiz.models instead of the commonly seen school.quiz.models. Otherwise the project fails to run: As you can see above, PyCharm doesn't recognize quiz. It wants me to use school.quiz instead, but when I do that the project doesn't run: File "/.../Code/breather/school/school/urls.py", line 19, in <module> from quiz.views import QuestionView File "/.../Code/breather/school/quiz/views.py", line 6, in <module> from school.quiz.models import Question ModuleNotFoundError: No module named 'school.quiz' I'd really prefer to use school.quiz, but I can live with using quiz if needed. I just want PyCharm and runserver to reconcile on one way so that I can get on with my project. These are my Django settings in PyCharm: -
Google Cloud Django App Deployment - Permission Issues
I'm following this tutorial, yet I get stuck at the very end when I'm trying to deploy the app on the App Engine. I get the following error message: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [13] Flex operation projects/responder-289707/regions/europe-west6/operations/a0e5f3f4-29a7-49d8-98b5-4a52b7bf04ca error [INTERNAL]: An internal error occurred while processing task /app-engine-flex/insert_flex_deployment/flex_create_resources>2020-09-21T20:32:48.366Z12808.hy.0: Deployment Manager operation responder-289707/operation-1600720369987-5afd8c109adf5-6a4ad9a9-e71b9336 errors: [code: "RESOURCE_ERROR" location: "/deployments/aef-default-20200921t223056/resources/aef-default-20200921t223056" message: "{\"ResourceType\":\"compute.beta.regionAutoscaler\",\"ResourceErrorCode\":\"403\",\"ResourceErrorMessage\":{\"code\":403,\"message\":\"The caller does not have permission\",\"status\":\"PERMISSION_DENIED\",\"statusMessage\":\"Forbidden\",\"requestPath\":\"https://compute.googleapis.com/compute/beta/projects/responder-289707/regions/europe-west6/autoscalers\",\"httpMethod\":\"POST\"}}" I don't really understand why though. I'm have authenticated my gcloud, made sure my account has App Engine Admin/Deployment rights. Have everything in place. Any hints would be much appreciated. -
Querying Many To Many relationship by number of joins using Django
I have two models: ActorModel and FilmModel joined as follows: FilmModel(models.Model): actors = models.ManyToManyField(Actor, blank=True, related_name='film_actors') ActorModel(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.imdb_id I want to filter my ActorModel for any instance which has more than 5 joins with the FilmModel. I can do this as follows: actors = ActorModel.objects.all() more_than_five_films = [] for actor in actors: actor_film_list = FilmModel.objects.filter(actors__imdb_id=str(name)) if len(actor_film_list)>5: more_than_five_films.append(actor) However, using the above code uses lots of processing power. Is there a more efficient way of finding the actors with more than 5 joins? Could I do this at the filtering stage for example? -
WebSocket connection to 'ws://127.0.0.1:8000/ws/chat//' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
I am having this error message with Django channels please i need help. WebSocket connection to 'ws://127.0.0.1:8000/ws/chat//' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET. -
Save date on every form submission Django
Would it be possible to save the exact date when a specific user submits the form without updating existing data? So basically I'd have every date when a user submitted the form. I'd want to use these dates for a graph. When I submit the form now it updates the users data, such as weight, height, and goal. It works fine, but i want to be able to save submission days like "2020.09.12". And if the user submits the form again to change his data the date should containt "2020.09.12" + the new date. -
Django view: redirect user to template based on schema name (got from URL)
I am trying to redirect users to various apps based on their schema name. I have written this so far: def loginUser(request, url): schema_list1 = ['pierre'] schema_lsit2 = ['itoiz'] if request.method == 'POST': form = AuthenticationForm(data=request.POST) t = urlparse(url).netloc dbschema = '"' + t.split('.', 1)[0] + '"' if form.is_valid(): user = form.get_user() login(request, user) if dbschema in schema_list1: print('yes') redirect = '/upload.html' return HttpResponseRedirect(redirect) elif dbschema in schema_list2: print('yes') redirect = '/dash2.html' return HttpResponseRedirect(redirect) else: form = AuthenticationForm() context = { 'form': form, } return render(request, 'loginUser.html', context) my problem is that I get the error: TypeError at /loginUser loginUser() missing 1 required positional argument: 'url' Request Method: GET Request URL: https://itoiz.exostock.net/loginUser Django Version: 3.0.5 Exception Type: TypeError Exception Value: loginUser() missing 1 required positional argument: 'url' Exception Location: /home/ubuntu/exo/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 113 I am fairly new to django and I am confused about why do i get this error, especially because I used the exact same method somewhere else and it worked fine. I am wondering if someone can see what I am missing. By the way is there another way to get the user's url? -
POSTGRES: FATAL: role "postgres" does not exist
for my django project i wrote a docker-compose.yml, Dockerfile file and a build_dev.sh script after going through various reference and guides. after the build is complete i can access the hello world page by going to the url http://0.0.0.0/ Now I want to create the database i the running docker container docker exec -it django_docker_db_1 bash using this command i get access into the db container then i run the command su - postgres Now when i try to run createuser --createdb --password myproject it asks for a password. I entered the same password that i defined the script (in the guide it was written "When asked, enter the same password for the database as in the build_dev.sh script.") , but it throws me an error saying createuser: error: could not connect to database postgres: FATAL: role "postgres" does not exist. please help me with this! build_dev.sh #!/usr/bin/env bash DJANGO_SETTINGS_MODULE="myproject.settings.dev" \ DJANGO_SECRET_KEY="3!^3%bro*!)=1s_g49eqb5&q^4*-m^7p_)q7xkond_b6*lc&&6" \ DATABASE_NAME="myproject" \ DATABASE_USER="myproject" \ DATABASE_PASSWORD="testpassword" \ EMAIL_HOST="localhost" \ EMAIL_PORT="25" \ EMAIL_HOST_USER="" \ EMAIL_HOST_PASSWORD="" \ PIP_REQUIREMENTS="dev.txt" \ docker-compose up --detach --build docker-compose.yml version: "3.7" services: nginx: image: nginx:latest ports: - "80:80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/home/myproject/static - media_volume:/home/myproject/media depends_on: - gunicorn gunicorn: build: context: . args: PIP_REQUIREMENTS: "${PIP_REQUIREMENTS}" … -
How to best setup smtp using Gmail in DJANGO?
I have been using the SMTP module in python (DJANGO specifically) for quite a while now. However, even after turning on access to third party apps in my Google account, sometimes, Google automatically turns it off. This throws errors like Bad Credentials. Code in views.py after receiving email via a POST request upon form submission mail=('Sending email',"Hello ","A message",settings.EMAIL_HOST_USER,[request.POST['email']]) send_mass_mail((mail,),fail_silently=False,) Code in settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password_here' Though the code works fine sometimes, I am specifically looking for a foolproof way to send emails via my webapp. Thanks in advance -
"AnonymousUser must be a 'User' instance" in perfom_create() method
I'm migrating my web server from Gandi to AWS. I set up my server like the old one: AWS (EC2 & Route53) Server Ubuntu 20.04 Django Rest Framework WSGI Apache2 When I run my server with python manage.py runserver 0.0.0.0:8000 my website works fine. But when I deploy it with apache2 the POST requests don't work because the request's token doesn't work. It's as if the token is missing. Below an example to a POST request to create a poll in my backend: Url : http://mywebsite.fr/api/polls/ Header : Authorization : token mytokenwithmanynumbers Body: { "question": "My poll", "categorie": 1, "answers": [{ "text": "my answer" }] } In my backend I have the following code: urls.py: router.register('api/polls', PollViewSet, 'polls') api.py: class PollViewSet(viewsets.ModelViewSet): permission_classes = [IsOwnerOrReadOnly, ] serializer_class = PollSerializer def get_serializer_class(self): if self.action == 'create' and not self.request.user.is_anonymous: return PollSerializerCreate return PollSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) serializers.py: class PollSerializerCreate(serializers.ModelSerializer): answers = AnswerSerializer(many=True) class Meta: model = Poll fields = '__all__' def create(self, validated_data): answers = validated_data.get("answers", None) categorie = validated_data.get("categorie", None) user = validated_data.get("user", None) question = validated_data.get("question", None) if answers and categorie: poll = Poll.objects.create(question=question, user=user, categorie=categorie) for answer in answers: new_answer = Answer.objects.create(text=answer['text'], poll=poll) return poll raise FieldMissingToCreatePoll But … -
Django-form wizard: How to choose a specific form by name
I'm trying to choose a specific form by its name not its step. Is it possible to use a template tag like {{wizard.advancedForm}} to fetch the advancedForm in my form_list? class BetaRcollection(LoginRequiredMixin, SessionWizardView): form_list = ( ('mainForm', UploadAlbum), ('advancedForm', UploadAlbumAdvanced) ) file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'WizardTmp')) template_name = 'creator/release/collection.html' def done(self, form_list, form_dict, **kwargs): print(f'form_list: ${form_list}') print(f'form_dict: ${form_dict}') print('FORMS ARE VALID') # advancedForm.save() # save musicName = self.condition_dict.mainForm['musicName'] -
Load an image from aws s3 bucket to django application
I made a django app that stores notes of different semesters and branches and I want to display the profile image of the uploader of the post right next to their name in homepage of my website. I am using my staticfiles directly from the S3 bucket The notes that the users upload is stored in the notes/models.py whereas the user's profile and their profile image is stored in users/models.py What I want to do is in home.html (below) use something like, {% static post.uploader.profile.image.url %} but suddenly it does not work. Settings.py AWS_ACCESS_KEY_ID='XXXXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY='XXXXXXXXXXXXXXXXXXXXXXXXXXX' AWS_STORAGE_BUCKET_NAME='django-XXXXX' AWS_S3_REGION_NAME = "ap-south-1" AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None # s3 static settings AWS_LOCATION = 'staticfiles' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'django_project.storage_backends.PublicMediaStorage' # s3 private media settings PRIVATE_MEDIA_LOCATION = 'private' PRIVATE_FILE_STORAGE = 'django_project.storage_backends.PrivateMediaStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' notes/models.py class Notes_Model(models.Model): """Store notes of different branches and semesters.""" uploader = models.CharField(max_length=200) title = models.CharField(max_length=200) date_posted = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=2500) branch_choice = models.CharField(max_length=50, choices=branch_choices, default='cse') file_semester = models.IntegerField(choices=semester_choice) file = models.FileField() syllabus = models.TextField(max_length=200, default='No Syllabus Availibe Yet') def __str__(self): return self.title def get_absolute_url(self): return reverse("notes-detail", … -
Supervisor error - gunicorn: ERROR (spawn error)
I am getting the error gunicorn: ERROR (spawn error) when trying to deploy django application with gunicorn wsgi in the supervisor. My supervisor.conf GNU nano 4.8 supervisord.conf [unix_http_server] file=/tmp/supervisor.sock ; the path to the socket file [supervisord] logfile=server/supervisor/logs/supervisord.log ; main log file; default $CWD/supervisord.log logfile_maxbytes=5MB ; max main logfile bytes b4 rotation; default 50MB logfile_backups=10 ; # of main logfile backups; 0 means none, default 10 loglevel=info ; log level; default info; others: debug,warn,trace pidfile=/tmp/supervisord.pid ; supervisord pidfile; default supervisord.pid nodaemon=false ; start in foreground if true; default false minfds=1024 ; min. avail startup file descriptors; default 1024 minprocs=200 ; min. avail process descriptors;default 200 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket [program:gunicorn] command=/home/ubuntu/strategy_app/venv/bin/gunicorn strategy_server.wsgi:application -c /home/ubuntu/strategy_app/server/gunicorn/gunicorn.conf.py --chdir /home/ubuntu/strategy_app when I run the same above command outside of supervisor, it works /home/ubuntu/strategy_app/venv/bin/gunicorn strategy_server.wsgi:application -c /home/ubuntu/strategy_app/server/gunicorn/gunicorn.conf.py --chdir /home/ubuntu/strategy_app I also tried other options available in the official docs -
InterfaceError: Error binding parameter 3 - probably unsupported type
I have an error here with my Django backend: Environment: Request Method: POST Request URL: http://localhost:8000/MultipleChoiceQuestion/ Django Version: 2.2.11 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'db.apps.DbConfig', 'rest_framework', 'corsheaders', 'django_filters'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', '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: File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (unrecognized token: ":") was the direct cause of the following exception: File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in execute 99. return super().execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in execute 67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers 76. return executor(sql, params, many, context) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\utils.py" in __exit__ 89. raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) During handling of the above exception (unrecognized token: ":"), another exception occurred: File "C:\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\viewsets.py" in view 114. return self.dispatch(request, *args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\views.py" in dispatch 505. … -
Django: how do use * for Decimal and float?
I have below models, and it shown error: "unsupported operand type(s) for *: 'float' and 'Decimal'" for "self.item.price * 1.034". what should I do for fixed it?? models.py class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10, blank=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def get_total_price_credit(self): return round(self.quantity * self.item.price * 1.034) def get_final_price_credit(self): return self.get_total_price_credit() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) def get_total_credit(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price_credit() return total -
Getting error in django rest framework testing
Trying to test update in django rest framework but, it returns following error. How do test to edit update of gallery. self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 my models.py class GalleryImage(models.Model): image = models.ImageField(upload_to='gallery/') alt_text = models.CharField(max_length=300) created = models.DateTimeField(auto_now_add=True) class Gallery(models.Model): name = models.CharField(max_length=30) slug = AutoSlugField(populate_from='name', unique_with='id') images = models.ManyToManyField(GalleryImage) created = models.DateTimeField(auto_now_add=True) my factories.py class GalleryImageFactory(DjangoModelFactory): class Meta: model = GalleryImage image = factory.django.ImageField(color='blue') alt_text = 'alt_text' class GalleryFactory(DjangoModelFactory): class Meta: model = Gallery name = 'Image Gallery 1' @factory.post_generation def images(self, create, extracted, **kwargs): if not create: return if extracted: for image in extracted: self.images.add(image) my tests.py class UpdateDeleteGalleryTestCase(APITestCase): def setUp(self): image1 = GalleryImageFactory() image2 = GalleryImageFactory() self.gallery = GalleryFactory(images=(image1, image2)) def test_update(self): data = { 'name': 'edited gallery', 'images': [1] } url = reverse('delete:retrieve_update_delete_gallery', kwargs={'slug': self.gallery.slug}) response = self.client.put(url,data=data,format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) -
Django - Changing queryset order_by
Using Djanog I'm trying to implement some sorting in my table trigger by button but I have no clue how to deal with it as my query set is both filtered and paginated. Could you please give me a hint how to implement this? Should it be done in frontend, i.e. JavaScript or maybe handled by backend, changing qs.order_by('param') ? I would also appreciate any examples as I'm quite new to Django. Here's my code: --index.html <body> <main role="main" class="container"> <form method = "GET" action = "."> <div class="form-row"> <div class="form-group col-8"> <label for="filter_by_name">Search by name</label> <div class="input-group"> <input class="form-control py2 border-right-0 border" type="search" name="filter_by_name" placeholder="Name contains.."/> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> <div class="form-group col-md-4"> <label for="filter_by_shop">Search by shop</label> <select id="filter_by_shop" class="form-control" name="filter_by_shop"> <option selected>All shops</option> <option>first shop</option> <option>second shop</option> </select> </div> </div> <button type="submit" class="btn btn-primary">Search</button> </form> <table> {% for x in queryset %} <tr> <td>{{x.NAME}}</td> <td>{{x.PRICE}}</td> <td>{{x.SHOP}}</td> </tr> {% endfor %} </table> </main> </body> def MyView(request): qs = prices.objects.all().order_by('PRICE') filter_by_name = request.GET.get('filter_by_name') filter_by_shop = request.GET.get('filter_by_shop') if filter_by_name != '' and filter_by_name is not None: qs = qs.filter(NAME__icontains=filter_by_name) if filter_by_shop != '' and filter_by_shop is not None: qs = qs.filter(SHOP__icontains = filter_by_shop) … -
Django CSS not working when using block content
I'm trying to make a simple ordered list. Basically, I have a template that is a navigation bar that is at the top of every page in my web page. This is how the html/css looks on it. {% block content %} <style> * { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 10px; font-family: sans-serif; } a { text-decoration: none; color: #ea0a8e; font-size: 18px; } header { width: 100%; height: auto; background: #121212; background-size: cover; position: relative; overflow: hidden; } .container { max-width: 120rem; width: 90%; margin: 0 auto; } .menu-toggle { position: fixed; top: 2.5rem; right: 2.5rem; color: #eeeeee; font-size: 3rem; cursor: pointer; z-index: 1000; display: none; } nav { padding-top: 5rem; display: flex; justify-content: space-between; align-items: center; text-transform: uppercase; font-size: 1.6rem; } .logo { font-size: 3rem; font-weight: 300; transform: translateX(-100rem); animation: slideIn .5s forwards; color: #ea0a8e; } .logo span { color: white; } nav ul { display: flex; } nav ul li { list-style: none; transform: translateX(100rem); animation: slideIn .5s forwards; } nav ul li:nth-child(1) { animation-delay: 0s; } nav ul li:nth-child(2) { animation-delay: .5s; } nav ul li:nth-child(3) { animation-delay: 1s; } nav ul li:nth-child(4) { animation-delay: 1.5s; } nav ul li:nth-child(5) { animation-delay: … -
Filter and count QuerySet items with a variable
I am new to Django and am working on a very basic social media site as a practice project. Right now, I am trying to figure out how to filter a QuerySet based on a variable and counting how many items in the QuerySet match the filter. To demonstrate what I am trying to do, let's say I am looping through all the visible posts (like a Facebook post or something similar), and I am wanting to display the number of comments each post has. This is how I would go about that: {% post in all_posts %} <h1> There are currently {{ HOW DO I FILTER AND COUNT? }} comments on this post</h1> {% endfor %} This is what the relevant section of my views.py file looks like: def index(request): all_posts = Posts.objects.order_by('-date_published') all_comments = Comments.objects.order_by('-date_published') context = {'all_posts': all_posts, 'all_comments': all_comments } return render(request, 'social/index.html', context) The comments link to the posts through the post ID. So, I know this doesn't work, but ideally I would like to replace my HOW DO I FILTER AND COUNT? part of the template with something like: {{ all_comments.filter(postID=post.id).count }} Is there an easy way to do this in my views.py or … -
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label
I had an issue with getting some UTC as local time values from a database in my django app as I was doing it be 'hand' in my script, someone in that issue (located here) suggested I try running the script with django (reworking to use the django ORM) decent idea but then get this error which is coming from my models file here: from __future__ import unicode_literals from django.db import models from django.db.models import Q from django.contrib.auth.models import User # Create your models here. class OnSiteLog(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete=models.CASCADE) ... So the full error I get is: Traceback (most recent call last): File "report_mailer_django.py", line 13, in <module> from covidlog.models import OnSiteLog File "/mnt/h/programming/web/covid19/covidlog/models.py", line 7, in <module> from django.contrib.auth.models import User File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/local/lib/python3.6/dist-packages/django/contrib/contenttypes/models.py", line 133, in <module> class ContentType(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 111, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am not sure what is causing this, the file I am trying to fun should be loading django stuff just fine: import django import os from django.conf import … -
Look up nearest coordinates in database / GeoJson
I am working with a GeoJson file with thousands of rows of data, and given a coordinate pair (obtained through MapBox GL JS reverse geocoding) want to find the closest matching result in the dataset. My current approach is to convert the GeoJson into a Postgres DB to be modeled via Django/Python. The GeoJson contains linestring data therefore I loop through each linestring array and save the individual coordinate pairs as a new DB record along with the the linestring array itself. To query the DB I run the following SQL select query: SELECT id, linestring FROM GeoJsonDB ORDER BY ABS(geocoding_latitude-latitude) + ABS(geocoding_longitude-longitude) ASC LIMIT 1 where: geocoding_latitude and geocoding_longitude are generated by Mapbox latitude and longitude are the columns containing the requisite data in my DB id is the DB primary key linestring is an array of arrays containing the linestring coordinates to be drawn as a layer on the map This works but where the ‘nearest’ result is not really that near I will still pull a result which is not helpful (if too far away). So my questions are: (1) Is there a better way/more accurate way to work with the GeoJson data to accomplish this task … -
Is there a way to get a set of m2m from a queryset in Django
I am trying to find a way to get a set of m2m objects from a queryset. A simplified use case would be: I have an Event class with a M2M attendees(user) field. I have a user who is attending Event 1,4,6 I want to find all other users that are attending Events 1,4,6 It is simple enough to do, but it just seems like something that Django would be able to do out the box.