Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I seed a join table in Django not using fixtures?
I'm trying to seed a many-to-many join table in Django. To seed the rest of my database, I've been using fixtures. That process requires a model. But if I create a model and then a fixture for the join table, I'll end up with two tables in the database -- the one based on my model/fixture and the one django automatically creates. Is there a way to seed this Django-created join table? -
In Django REST framework's filtering, What "purchaser__username=username" mean
I'm studying to using Django Rest framework in my Project, but I'm confuse with this code serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Purchase.objects.all() username = self.request.query_params.get('username') if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset What does purchaser__username=username mean in this code ? It quite confusing me for time now. -
Querying an API, and displaying it's results from from form input - Django
I am not sure if I am going about this correctly, but I am not getting any errors it just reloads the page without displaying anything. The issue could be with me trying to format the api string and input the users input there? I also tried returning the variable as an HttpResponse, still made no difference. Sorry just getting back into python, and just starting with Django. Correct code should go something like this: 1.User inputs their name into the form 2. Page then displays the usersid. Code: views.py: from urllib import response from django.shortcuts import render from django.http import HttpResponse import requests from .forms import SearchUser import json # Create your views here. def home(response): # data = requests.get( # 'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-6c5d9a2c-3341-4b0c-a0a5-7eafe46e54cf') # userid = data.json()['puuid'] return render(response, "main/home.html", { 'form': SearchUser(), # include reference to your form 'userid': search, # 'mmr':NA, }) def search(response): if response.method == "POST": form = SearchUser(response.POST) if form.is_valid(): n = form.cleaned_data["name"] user = n(name=n) user.save() data = requests.get( "https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/f'{user}'/NA1?api_key=RGAPI-6c5d9a2c-3341-4b0c-a0a5-7eafe46e54cf") userid = data.json()['puuid'] return HttpResponse(userid) else: form = SearchUser() return render(response, "main/home.html", {"userid": userid}) forms.py: from django import forms class SearchUser(forms.Form): name = forms.CharField(label="Name", max_length=200) urls.py: from django.urls import path from . import views … -
Django filter model objects related to another model
I am trying to create a query set that matches a model objects, here's what i tried: a = Product.objects.first() # Select first product as a test b = a.compareproducts_set.all() # Filter only related product "a" in the query Now i only have first product "a" and it's filtered related query set "b", how to iterate the rest products along with their filtered query set from second model? So i can have two lists i can zip and loop them in template -
how to remove html elements after 30 min django
hello iam trying to make breaking news bar in my website , i used for that html ,css and django framework as follows : this is my html code : <div class="bereaking"> <div class="breaking_news"> <div class="news-ticker-title">عاجل</div> <div class="news"> <marquee direction="right" onmouseover="this.stop();" onmouseout="this.start();" class="marquee"> {% for breaking in breakings %} <a class="marquee-child" href=""><span>{{breaking.breaking_news}}</span></a> {% endfor %} </marquee> </div> </div> </div> this is my model.py: class breaking(models.Model): breaking_news = models.TextField(max_length=5000 , blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) i want to make timing for each news so iwant to add this bar when i add news from control panel and remove the bar after 30 min of the time how can i make that ? -
Is there a way to write a pytest test case to test the current api url?
I am attempting to set up a new GraphQL API for the first time, and am attempting to write a pytest test suite to cover the process. I am using Django 4.0. I want to set up a test that, when run, will look at the current server address (localhost or not), send a request to the GraphQL url at that address, and assert the result. I currently receive the following error "FAILED api/tests/test_api.py::test_get_all_notifications - requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=2448): Max retries exceeded with url: /graphql ..." Here is what I have so far: import requests import json from main.tests.fixtures import * def get_current_server_url(): # TODO: <---- THIS IS WHAT SHOULD CHANGE BASED ON CURRENT SERVER return "http://localhost:2448/graphql" def make_graphql_request(query: str) -> dict: url = get_current_server_url() request = requests.post(url, json={'query': query}) return json.loads(request.text) def test_get_all_notifications(db, notification) -> None: """Confirms that the GraphQL API returns a valid notification ID when requested.""" all_notifications_query = """{ allNotifications { id } }""" data = make_graphql_request(query=all_notifications_query)['data'] assert len(data['allNotifications']) == 1 There are several dependant fixtures being used in my notification fixture, but the notification fixture itself is as follows: @pytest.fixture() def notification(db, user__user_in_group__group, default_config) -> None: """Stages a new notification in the database.""" (sending_user, receiving_user, group) = … -
getting elements with a queryset based on a left join in django
I have two models: class A(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class B(models.Model): a_field = models.ForeignKey(null=True,blank=True,related_name='a',on_delete=models.SET_NULL) field2 = models.CharField(max_length=100) I want to get all of elements of model A which are not related to B. Here is the query I wrote but it doesn't work: B.objects.select_related("a_field").filter(a_field__isnull=True) How can I solve this problem? -
HTTPSConnectionPool - Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)
Consuming an API which was by http and passed to https returns the error: HTTPSConnectionPool(host='ip', port=por): Max retries exceeded with url: /b1s/v1/Deposits (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1131)'))) in the code I already tried adding this way: session = requests.Session() session.verify = False session.trust_env = False verify=ssl.CERT_NONE I also tried to install urllib3 Requirement already satisfied: urllib3==1.23 -
Can't join two tables on a foreign key field using django ORM?
class weapons(models.Model): weapon = models.CharField(max_length=11) country = models.IntegerField() flags = models.IntegerField(default=0) title = models.CharField(max_length=1000) class compare(models.Model): weapon = models.CharField(max_length=11) user_id = models.IntegerField() flags = models.IntegerField(default=0) WeaponNode = models.ForeignKey(weapons, on_delete=models.PROTECT) When I run this function: compare.objects.filter(user_id=1).values_list('weapon', 'WeaponNode__title') I expect this query raw: SELECT apps_compare.weapon, apps_weapons.title FROM apps_compare INNER JOIN apps_weapons ON (apps_compare.weapon = apps_weapons.weapon) WHERE apps_compare.user_id = 1 Result should be: But it returns this instead: SELECT "apps_compare"."weapon", "apps_weapons"."title" FROM "apps_compare" INNER JOIN "apps_weapons" ON ("apps_compare"."WeaponNode_id" = "apps_weapons"."id") WHERE "apps_compare"."user_id" = 1 apps_weapons.title returns null: In other examples I saw, they only used id with JOIN ON but I want to use a weapon value instead of id. How can I do accomplish with ORM? If it's not possible with ORM, then what are the other ways? -
Retrieving data from Mongodb and show it on front-end using django
I have a mongodb database named as world, which has two collection from before city, languages. I want to show the data of my collection on the web, how can i do it. currently i know to create collection in models.py and migrate it. like; first we have to edit databases[] in setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'world', } } in models.py i creted a class and migrated it using python manage.py migrate class Destination(models.Model): name= models.CharField(max_length=100) img=models.ImageField(upload_to='pics') desc=models.TextField() and i'm able to retrieve data from Destination by using below code in views.py from django.shortcuts import render from .models import Destination def index(request): dests=Destination.objects.all() return render(request,'index.html',{'dests':dests}) My question is my collection/class is already available in the database ( city, language) and i'm not creating it contrary to Destination which was defined by me. then how to show data of city collection of world database on the front-end. kindly looking for help. -
'Account' object has no attribute 'orderproduct' The downlad and preview is not shwoing
I want a situation, when the user purchases the product, and orderproduct created, he can download the image.. This is the product Model class Product(models.Model): # user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="product_manager") seller = models.ForeignKey(SellerAccount, on_delete=models.CASCADE) media = models.ImageField(blank=True, null=True, upload_to=download_media_location, storage = FileSystemStorage(location=(protected_uploads_loc))) title = models.CharField(max_length=250) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=100, default=15.99) sale_active = models.BooleanField(default=False) sales_price = models.DecimalField(decimal_places=2, max_digits=100, default=9.99, null=True, blank=True) image_size = models.CharField(max_length=20, null=True) # date_taken = models.DateTimeField(auto_now_add=True, auto_now=False) location = models.CharField(max_length=150, null=True) This is the orderproduct model class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) # download = models.ManyToManyField(Product, related_name="download_product") ordered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username This is the product download views class ProductDownloadView(MultiSlugMixin, DetailView): model = Product def get(self, request, *args, **kwargs): obj = self.get_object() # if obj in request.user.myproducts.products.all(): if obj in request.user.orderproduct.product_set.all(): filepath = Path.joinpath(settings.PROTECTED_UPLOADS, obj.media.path) print(filepath) guessed_type = guess_type(filepath)[0] wrapper = FileWrapper(open(filepath, "rb")) mimetype = "application/force-download" if guessed_type: mimetype = guessed_type response = HttpResponse(wrapper, content_type=mimetype) if not request.GET.get("preview"): response["Content-Disposition"] = "attachment; file=%s"%(obj.media.name) response['X-SendFile'] = str(obj.media.name) return response else: raise Http404 This is the html … -
Django - Annotate sum of duration in hour
I have a field Time with type DurationField and I want to sum the values and convert it into decimal hour Task.objects.all().annotate(total=Sum('Time')) For example if total = timedelta(seconds=5400) I want to get 1.5 hours -
Django отправка формы на почту
я пишу сайт на Django и у меня есть форма для отправки на почту заказчика. Форма: <form method="post"> {% csrf_token %} <p><input class="inp" id="id_subject" type="text" name="name" placeholder="Ваше имя" maxlength="100" required /></p> <p><input class="inp" type="email" name="sender" placeholder="E-mail" id="id_sender" required /></p> <p><input class="inp" name="message" id="id_message" placeholder="Сообщение" maxlength="100" required /></p> <input class="button" type="submit" value="Отправить" /> </form> views.py def get_contact(request): if request.method == 'GET': form = ContactForm() elif request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sabject = form.cleaned_data['name'] sender = form.cleaned_data['sender'] message = form.cleaned_data['message'] try: send_mail(sabject, message, sender, RECIPIENTS_EMAIL) except BadHeaderError: return HttpResponse('Ошибка в теме письма.') return HttpResponseRedirect('contact') else: return HttpResponse('Неверный запрос.') return render(request, 'main/contacts.html', {'form': form}) settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' RECIPIENTS_EMAIL = ['Моя почта'] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mailgun.org' EMAIL_HOST_USER = 'Логин' EMAIL_HOST_PASSWORD = 'Пароль' EMAIL_PORT = 587 EMAIL_USE_TLS = True На хосте при отправке формы выдет: SMTPServerDisconnected at /contact Использую mailgun как smtp сервер Что не так? -
Using GitHub with a ReactJS and Django Project
I am building a web app using ReactJS and Django. I will be working with someone else on the project and would like to push the project to GitHub. I have a main folder for the project which is then divided into backend and frontend. When I created the react app portion, it initialized a git repo. I know having nested repos is not recommended. What I would like to know is the best practice for pushing a project to GitHub using both React and Django. Thanks -
Django - How do I pass the 'partial' kwarg from a Serializer to its child serializer
When I submit a PATCH request, its sets a partial=True kwarg on the Viewset's serializer, in this case Book, however when Book has an embedded serializer (Chapter), it does not set partial=True on the Book nested serializer. Original code is this: BookSerializer(ModelSerializer): chapters = ChapterSerializer(many=True, read_only=False, required=False) I've tried something like this to pass partial down but its not working: BookSerializer(ModelSerializer): chapters = SerializerMethodField() def get_chapters(self,obj): return ChapterSerializer(many=True, read_only=False, required=False, partial=self.partial) The json request would be something like this: { "id" : 1, "title" : "New Book Title", "chapters" : [ { "id" : 1, "title" : New Chapter 1 Title }, { "id" : 7, "title" : New Chapter 7 Title }, ] } So during the request, those two Chapters need to have a partial_update, and take that into account when getting validated. -
Django-admin startproject creates broken manage.py file
I've tried this using virtualenv as well with no luck as well, I know there's a preference against "python -m venv .env" but that is very unlikely to be the issue. Django and virtual environments have worked fine in the past on this machine as well. The manage.py file created: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firebackend.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() steps to recreate: python -m venv .env source .env/bin/activate Appears to be working normal pip install django, django-rest-framework, etc Looking at everything and running the command again it appears to install fine. Tried this with Django 3 and 4 same results django-admin startproject backend . (with or without specifying the current directory, tested that out) And no matter what I do I get the manage.py file above. "Which python" and "which django-admin" point to the env result of 'python -c "import sys; print(sys.path)"' ['', '/usr/lib/python38.zip', '/usr/lib/python3.8', … -
Can the aggregate(Avg()) method in django slow down code execution?
This is how I calculate the average rating, that is, I use Avg (I'm trying to create an online store and I need to count the average rating of the product) average_rt = Review.objects.filter(product_connected=self.get_object()).aggregate(Avg('rating')) And it works, but I have a question: if I have, for example, a couple of thousand reviews, then when the page loads (my rating is counted in get_context_data), these calculations will not slow down the code? And if it slows down a lot, what solutions are there to fix it? I just don't quite understand how this method works -
How can I change the sites url depending on the anchor tags?
urls.py app_name='listing' urlpatterns = [ url(r'^listing/select/$',views.platformselect,name='listingselect'), url(r'^listing/',views.listingpage,name='listingpage'), ] views.py def platformselect(request): return render(request,'listing/platform_select.html') platform_selection.html <a href="{% url 'listing:listingpage' %}">amazon</a> <a href="{% url 'listing:listingpage' %}">ebay</a> <a href="{% url 'listing:listingpage' %}">google</a> Greetings. How can I change the urls according to the options. For example when I click the 'amazon' anchor tag I want it go to "mysite.com/listing/amazon". Same for the other options. How can I change the sites url depending on the anchor tags? -
PostgreSQL match operator @@ in Django for custom full text search ranking
I'm using a full text search in Django + PostgreSQL. So far the various configurations of SearchRank don't quite give the best ordering in my case. However, after some experimentation, what I want I think is a rank value that is 1/(number of words in field), if the field matches the search query 0 otherwise Which in raw SQL would be: (to_tsvector('english', title) @@ plainto_tsquery('english', 'my search query')) ::int::float / array_length(regexp_split_to_array(title, '\s+'), 1), How can I alias/annotate a queryset to have such a field in Django? The issue seems to be that the match operator @@ is abstracted away by Django - I can't seem to see any combination of functions at https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/ that allows me to to this. -
Rewriting User standard model when customizing User class
guys! I'm using standard User model from django.contrib.auth.models import User. And I want to customize User model, expecially to add a field with ForeignKey. For example: class User(models.Model): this_users_team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) If I wrote this code is the django will overwriting standard User model with my data in databases or will it cause the issues? One more time, I haven't not any class User in my code. But I'm using User in other models, for example: id_user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) -
TypeError: set() takes 2 positional arguments but 3 were given in Django rest framework
I have an update api in which I have to delete the images files first and then update with other new image files. But when I call the api, it gets above error. My models: class Gallery(TimeStampAbstractModel): picture = VersatileImageField( "Image", upload_to=upload_path, blank=True, ) updated_at = None class Meta: ordering = ["created_at"] class Articles(TimeStampAbstractModel): creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name="articles", ) title = models.CharField(max_length=255, blank=True) tags = TaggableManager() image_files = models.ManyToManyField(Gallery, related_name="articles") content = models.TextField(blank=True) video_content = models.URLField(max_length=255, blank=True) post_views = models.IntegerField(default=0) unique_visitors = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="article_views" ) launch_date = models.DateTimeField(null=True) description = models.CharField(max_length=200, blank=True, default=None, null=True) def __str__(self): return self.title My view: class ArticlesView(viewsets.ModelViewSet): queryset = Articles.objects.all() serializer_class = ArticleSerializer permission_classes = [IsAdminUser] def update(self, request, *args, **kwargs): instance = self.get_object() print(instance) files = request.FILES.getlist("image_files") if files: instance.image_files.all().delete() for file in files: image_content = Gallery.objects.create(picture=file) instance.image_files.add(image_content.id) partial = False if "PATCH" in request.method: partial = True serializer = self.get_serializer(instance, data=request.data,partial=partial) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response( { "message": "Article has been updated.", "updated_data": serializer.data, }, status=status.HTTP_200_OK, ) My serializer is : class ArticleSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField(required=False) image_files = GallerySerializer(many=True, read_only=True) user = serializers.StringRelatedField(source="creator") total_shares = serializers.FloatField(read_only=True) total_reacts = serializers.FloatField(read_only=True) bad_reacts = serializers.FloatField(read_only=True) good_reacts = … -
How to display container that is centered with content that is in the far left and far right of it
I would like to display the price of an object on my html website. This is what I would like it to look like: Dynamic The container is centered on the page with a max width of 400px The "price" string is on the far left while the actual price is on the right of the centered content This is what my html looks like: <div class="price-container"> <div class="price">price:</div> <div class="price-number">{{ event.price }}.00</div> </div> This is what my css looks like: .price-container{ font-family: Montserrat; text-transform: uppercase; color: white; font-weight: 700; font-size: 20px; width: 90%; max-width: 400px; } .price{ float: left; } .price-number{ float: right; } -
How to validate a login using a manually added field in a django admin users table
I want to link my login page to my django admin users table. So that users of the page can only access the check in page if their ID and pin is saved in the django admin field. The field already has manually added values and I want to connect these values to a login form. Please I am new to Django Create your views here. def login(request): if request.method == 'POST': from django.views.decorators.csrf import csrf_protect @csrf_protect def checkit(request): if request.method == "POST": r_number = request.POST.get("room") a_paid = request.POST.get("amount") o_name = request.POST.get("occuname") o_email = request.POST.get("occumail") o_occupation = request.POST.get("occu") n_of_n = request.POST.get("night") s_date = request.POST.get("start") e_date = request.POST.get("end") new_data = chech_in(room_number=r_number, amount_paid=a_paid, occupant_name=o_name, occupant_email=o_email, occupant_occupation=o_occupation, number_of_nights=n_of_n, start_date=s_date, end_date=e_date ) new_data.save() return redirect('check:checkit') return render(request, 'check/checkin.html') -
Django for loop in JavaScript syntax error
I am trying to use Django for loop in JavaScript but I am getting a syntax error <script> var config = { type: 'pie', data: { datasets: [{ data: [1780000, 1630000], backgroundColor: [ '#ff0000', '#0000ff', '#ff0080', '#73ffff', '#5c26ff', '#002db3', '#ffff26', '#4cff4c', '#ff00ff' ], label: 'Population' }], labels: [{% for label in labels %} {{ label }}, {% endfor %}] }, options: { responsive: true } }; </script> this part is what i a have a problem with to be exact {% for label in labels %} {{ label }}, {% endfor %} just typing {% for %} gives me a syntax error I looked at similar stack overflow questions and they just use the for loop normally without any problems so why am I getting a syntax error. I even tried it in an an empty Js file and still get a syntax error. Am I forgetting to import something ? It works just fine the HTML file Help is much appreciated I have been stuck for hours now :) -
How to get <a> tags value to django views?
In my django template I have some tags. They linked to my other pages. I want to know which anchor tag clicked in my views. How can I do that? <div class="amazon"> <a href="{% url 'listing:listingpage' %}"><img id="amazon" src="{% static 'images/amazon_logo.png' %}" alt=""></a> </div> <div class="facebook"> <a href="#"><img id="facebook"src="{% static 'images/facebook_logo.png' %}" alt=""></a> </div> <div class="youtube"> <a href="#"><img id="youtube" src="{% static 'images/youtube_logo.png' %}" alt=""></a> </div> <div class="google"> <a href="#"><img id="google" src="{% static 'images/google_logo.png' %}" alt=""></a> </div> <div class="instagram"> <a href="#"><img id="instagram" src="{% static 'images/instagram_logo.png' %}" alt=""></a> </div> views.py def platformselect(request): return render(request,'listing/platform_select.html')