Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.x accesing media files using JavaScript
i am writing a simple gallery where image onclick expands it. I am trying to implement it using JavaScript. Every image is been uploaded from django admin panel to specified media folder. Anyway, there is trouble accesing the image's src as JS have no understanding where are these images stored because django serve it on localhost:8080/media/ url. What should i do? Or are there any options after using manage.py collectstatic command? -
How to get queryset affected by filters in django admin
I am trying to get query set after applying all filters which selected by user (query set displayed in admin display list) at django 1.9 i am using super(MyAdminClassNAme, self).get_queryset(request) but it always return myModel.objects.all() when i need it with all filters applied automatically not manually -
Is it safe to use builtin django login system on production
I am developing a website which is expected to get more than 1000 visitors everyday and I am using built-in authentication system of django. I want to know - is it safe and secure enough? Also, what precautions should I take or what can I do to improve its security. Or should I use third party or other apps available out there? -
Django Limit subquery
I wrote the following code: away_fixtures = Fixture.objects.filter(Q(away=home) | Q(home=away)).order_by('-date')[:3] tips = tips.filter(prediction__fixture__in=away_fixtures) When executing the following error occurs (I use MariaDB 10.4, which does not support LIMIT in subqueries): django.db.utils.NotSupportedError: (1235, "This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") When executing the following code: away_fixtures = Fixture.objects.filter(Q(away=home) | Q(home=away)).order_by('-date') tips = tips.filter(prediction__fixture__in=away_fixtures) But this returns the 'tips' for all the 'away_fixtures' and I only want the for the last 3 fixtures (so limiting it to 3 fixtures). How can I achieve this without switching database engines? -
How to write pure unittest in Django?
so my question is, how to write pure unit tests with Django? For exmaple I have this model: class Topic(models.Model): title = models.CharField(max_length=255, validators=[MinLengthValidator(5)]) created_at = models.DateTimeField(auto_now_add=True) This serializer: class TopicSerializer(serializers.ModelSerializer): class Meta: model = Topic fields = ('id', 'title', 'created_at') and I wrote these tests: class TopicModelTest(TestCase): def test_create_topic(self): topic = Topic(title='Topic title') self.assertEqual(topic.title, 'Topic title') def test_too_short_title(self): topic = Topic(title='W'*4) with self.assertRaises(ValidationError): topic.save() topic.full_clean() class TopicSerializerTest(TestCase): def setUp(self) -> None: mocked = datetime.datetime(2020, 1, 1, 0, 0, 0, tzinfo=pytz.utc) self.topic_attr = {'title': 'What is the weather like?'} self.topic_serialized = {'id': 1, 'title': 'What is the weather like?', 'created_at': '2020-01-01T00:00:00Z'} with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked)): self.topic = Topic.objects.create(**self.topic_attr) self.serializer = TopicSerializer(instance=self.topic) def test_contains_expected_fields(self): data = self.serializer.data self.assertCountEqual(data.keys(), ['id', 'title', 'created_at']) def test_serialized_data(self): self.assertEqual(self.serializer.data, self.topic_serialized) Everything works, but this is not unit tests. This is integration tests, because database is used. So my question is, how can I write unit tests? I ask about this, because many companies want to write simple project with unit test (TDD) for junior, but I don't know how can I write isolated unit tests without DB -
Why does my django website look different when I deploy it on heroku as compared to localhost?
This is my website when I use it on localhost: This is the same website when I deploy it on heroku. I didn't change the css files at all. Still why are the positions and sizes getting changed? -
cant display images in emails in django after sending emails
in my project, I've added a newsletter feed. But when when the email is sent its doesnt not display the images from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string def send_multiple_email(name, receiver): subject = 'Welcome' sender = 'host' #passing in the context vairables text_template = render_to_string('newsletter/email-subscribe.txt',{"name": name}) html_template = render_to_string('newsletter/new.html',{"name": name}) message = EmailMultiAlternatives(subject,text_template,sender, [receiver]) message.attach_alternative(html_template, "text/html") message.send() -
Assert correct scrolling position with selenium in python
I am running a django app and in that scope I have a page with a navigation bar and when I click on my contact-tab this automatically scrolls down to my contact-section. I am trying to test this behaviour with selenium but I can't seem to figure out how I can test the actual position of the page. Or, in other words, I want to verify that the page actually scrolled down to the contact-section. Right now I am doing this: def test_verify_position( self, browser, live_server ): """""" browser.get(live_server.url) contact_section = browser.find_element_by_id("contact").click() assert ???? I think I somehow have to get the current scroll location-coordinates. I know I can get the location of an element using .location. But the relative position of an element is always the same no matter the scroll-position. I tried this to debug: def test_verify_position( self, browser, live_server ): """""" browser.get(live_server.url) e = browser.find_element_by_xpath( "/html/body/section[4]/div/div[1]/h2/strong") location = e.location print(location) browser.find_element_by_css_selector(".nav-contact").click() e = browser.find_element_by_xpath("/html/body/section[4]/div/div[1]/h2/strong") location = e.location print(location) This prints the same coordinates for before and after the scroll. I also searched the official doc https://www.selenium.dev/documentation/en/webdriver/web_element/ but couldn't find a better solution or any solution for that matter. Anyone knows how to do this? Help is very … -
Malfunction of django nginx server [closed]
I don't know why 3 game objects are created for every four minutes instead of one. It didn't happen on localserver. After hosting the website it creates 3 objects for every 4 minutes. This creates a very big problem. I can't figure out what is the problem. Here is the source code. Here is the website link. Please help me to solve this problem. -
How can I make a practical DD-MM form input?
I'm creating an application in Django and in the registration I'd like users to enter the day and month they were born, so that their birthday can be hailed on the site. I can't really think of a practical way to do this, I'm having trouble converting the jQuery datepicker to MM-DD format and the other method I have made (that works decently) is impractical and throws an error: Here's what I have done, which I want to change: <script> const daysInMonth = (month, year) => { return new Date(year, month, 0).getDate(); } $('#birthday_year').change(function(){ verifyDate(daysInMonth) $('#birthday_month').change(function(){ daysInMonth = daysInMonth($('#birthday_month').val(), $('#birthday_year').val()) verifyDate(daysInMonth); $('#birthday_day').change(function(){ verifyDate(daysInMonth); }) }) }) const verifyDate = () => { if($('#birthday_day').val() > daysInMonth){ $('#birthday_day').val('Select an option'); } } </script> I won't show the form code, but it takes 3 inputs - Year of birth; month of birth and day of birth. The actual issue is that I cannot efficiently moderate the day people enter, basically I can't check whether a day is in the month they enter. E.g. someone could enter febuary 31st as their birthday. I'm open to suggestions on a better way to do this, thanks in advance. -
csv file not being uploaded in django admin
In my Django admin i am uploading my csv with summary and issue key id column. I am able to upload my csv but whenever in row 2 if i add (",") it shows error "Failed to parse csv". but instead if i add any other special character under summary and test case id it works. can anyone help me? Forms.py def clean_csv_file(self): value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') try: data = pd.read_csv(value.file, encoding = 'ISO-8859-1', engine='python') data.columns= data.columns.str.strip().str.lower() data=data.rename(columns = {'test case id':'Test Case ID'}) def transform(df): my_new_string = re.sub('[^a-zA-Z0-9"''-_“” \n\.]', '', df) return my_new_string data['summary'] = data['summary'].apply(transform) except KeyError: raise forms.ValidationError( 'CSV file must have "summary" column and "Issue Key" column') except Exception as e: print('Error while parsing CSV file=> %s', e) raise forms.ValidationError('Failed to parse the CSV file') return data csv-1 (This doesn't work because of ") Test Case ID,summary "," TCMT-10,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user. TCMT-11,Verify that only View to “Duplicate test cases” under “Test_Suite_Optimizer” module on Dashboard of Client’s user. TCMT-12,Verify that Process CSV sub module is displayed under “Process CSV” module on Dashboard of Client’s user. TCMT-13,Verify that … -
how to set min date of jquery date picker depending on the models.DateField in django
class Post(models.Model): ref_no = models.CharField(max_length=6, null=True, blank=True, unique=True) select_section = models.CharField(max_length=20, choices=Sections) incident = models.TextField(max_length=500, help_text="Mention the incident in brief here.") severity = models.CharField(max_length=20, choices=Severity) date_posted = models.DateField(auto_now_add=True, auto_now=False, blank=True) confirm_closing = models.BooleanField(default=False, help_text="Please confirm to close the Ticket") comment = models.TextField(max_length=500, default="Issue resolved and this Ticket has been closed successfully!") date_closed = models.DateField(null=True, blank=False, auto_now_add=False, auto_now=False) username = models.ForeignKey(User, on_delete=models.CASCADE) This is my model Here i want my min_date for date_closed field should be greater than the date_posted field of my model....please let me know what to do.....thanks in advance -
Nested Serializer for Django to nest subfields
I have a viewset which retrieves a queryset (Region.objects.filter(id=region_id)), and I want to serialize the queryset to include a number of tables referenced by foreign key like so: Region >> Market >> Baskets >> Fruits Each fruit has a basket_id Each basket has a market_id Each market has a region_id I have a serializer: class RegionSerializer(serializers.ModelSerializer): markets = serializers.SerializerMethodField() class Meta: model = Region fields = '__all__' def get_markets(self, obj): return ==(list(obj.region_set.all().filter(region_id=obj.id).values())) So far this works great to retrieve the market list, but I want to nest it so I have a region, a list of individual markets on the region, a list of individual baskets on each market, and a list of individual fruits on each basket. I'm not entirely sure how to accomplish said subfields using the serializer. -
Django allauth use email instead username to identify user
I want to use only an email of a user to identify him/her. Now I thought I will just define User class like so: class User(AbstractUser, CreatedUpdatedAtMixin): email = models.EmailField(_('email address'), unique=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") But I also want to use django-allauth for sign up, login, email verification and so on. django-allauth adds EmailAddress table, which holds all emails for each user (there can be more than one email for user) and as a result I have emails duplicated (in User table and in EmailAddress table). How can I resolve this issue? I thought about deleting email from User but then user API is ugly (user.email_set.all()[0] :/). What's my best pick here? Just go along with duplication or should I implement allauth stuff myself, or hopefully there is some other option? -
Django get objects from url slug not working
I'm trying to make it so that I can show only briefs with the slug name as the category, however it does not work. At the minute I can only use it by showing all briefs using .objects.all() however this is not suitable for my desired use case. Do i need a slug field in the brief section too? Models.py class Category(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=50, unique=True) class Meta: verbose_name_plural = 'categories' verbose_name = 'category' def __str__(self): return self.name def get_absolute_url(self): return reverse('browse') class Brief(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) brandname = models.CharField(max_length=28) description = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True, blank=True) category = models.ForeignKey(Category, on_delete=CASCADE) def get_absolute_url(self): return reverse('homepage') Urls.py path('browse/categories/<slug:catslug>/', views.postsinthecategory, name = 'catslug' views.py def postsinthecategory(request, catslug): categories = Category.objects.all() brief = Brief.objects.all() if catslug: category = get_object_or_404(Category, slug = catslug) brief = Brief.objects.get(category=catslug) template = 'users/categoryposts.html' context = {'categories': categories, 'brief': brief, 'category': category} return render(request, template,context) -
Django filter for result from checkbox form
I'm begginer of django and i try to implement search engine to look for recipes that contains selected ingredients. I want to do form with all ingredients_type from my Model and user can select up to 3 of them (checkbox prefered). Then i want to filter recepe that contains them. I was looking for generic form but never get right result. Right now i have only a scratch and Im looking for any advice model.py class IngredientsType(models.Model): type = models.CharField(max_length=60, blank=True) def __str__(self): return self.type search.html {% for ingredients in ingredients_type %} <input type="checkbox" id="{{ingredients.type}}"> <label for="{{ingredients.type}}">{{ingredients.type}}</label> {% endfor %} <form method="POST" action="#"> <button type="submit" name="save" value="save">szukaj</button> </form> Do i have to create custom form or there is good way to use some of generic form? -
Django rest framework list of manytomany relational fields
I am trying to create an app that allows for me to upload my artwork and also have a carousel of a subset of those artworks. I want to have a Carousel object that I select images for it. from django.db import models from artwork.models import Artwork # Carousel Model references the artworks in a many to many field class Carousel(models.Model): carouseltitle = models.CharField(max_length=200,) artwork = models.ManyToManyField(Artwork) class Meta: verbose_name = 'Carousel' verbose_name_plural = 'Carousels' def __str__(self): return self.carouseltitle In my serializer, very simply creates what I want except for pulling Artwork fields: from rest_framework import serializers from .models import Carousel from artwork.models import Artwork class CarouselSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Carousel fields = ('id', 'carouseltitle', 'artwork') My view: from django.shortcuts import render from .models import Carousel from .serializers import CarouselSerializer from rest_framework import generics # Create your views here. class CarouselListCreate(generics.ListCreateAPIView): queryset = Carousel.objects.all() serializer_class = CarouselSerializer Creates this output: [ { "id": 7, "carouseltitle": "Home", "artwork": [ 2, 4, 6 ] } ] For the artwork list, I want to list field from the artwork such as the url to the image and the title, not just the PK. For the life of me everything … -
Will I have metatags for Google index in a reactjs application with using just Helmet?
First of all, apologies for my English. I have a reactjs application that requires to be crowded by Google. This application has multiple pages, so for a better indexing I tried to use Gatsby and I put everything in a Django server. I know that the interaction between the react app and the Django app could be better, but right now another guy is developing the backend part. I'm just wondering if I could provide him a single page app with a Helmet code for each "page" instead using Gatsby. So the Django template will point directly to the built index of my entire application and the part of indexing is made from my side with Helmet -
RelatedObjectDoesNotExist at /profile/
I have am trying to send the signal do that is the user create the account it automically create the profile for the user but I think i have messed things while creating signal.py it register the user but donot create the profile for the user views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import UpdateUserForms, ProfileUpdateForm from login.forms import UserRegisterForm from django.contrib import messages # Create your views here. @login_required def profile(request): if request.method == 'POST': u_form = UpdateUserForms(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account is updated!') return redirect('profile') else: u_form = UpdateUserForms(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'profile.html', context) def register(request): form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account Registeration Successful!!! for { username }') return redirect('home') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) signal.py so that it sends signal to create an userprofile automatically if user is register from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile #to create new profile @receiver (post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) #to update … -
Get specific list of data after filter in django
I tried to create a list of all the articles from a subscription with a URL. My Models are, class Subscription(models.Model): name = models.CharField(max_length=30) thumbnail = models.URLField() class Article(models.Model): subscription_name = models.ForeignKey(to=Subscription, on_delete=models.CASCADE) published = models.DateTimeField() title = models.CharField(max_length=300) Home Page View with all subscriptions: class HomeListView(ListView): model = Article template_name = "home.html" ordering = ['-published'] paginate_by = 20 context_object_name = 'allData' To make it more clear. Home page is shown with all articles from all subscriptions. If I click on a subscription, I wanna display all the articles by that subscription. How to implement the query for views.py for the problem? -
Python Django Channels - Is better to isolate the WebSocket Server?
So I have a Django application with React front-end through an API (django-restframework) and I would like to implement some websocket action (real time events) with Django Channels, is it better to create another server, just to websocket connections or integrate all in one application? I know it would change to ASGI, but don't know what it can causes or malfunction with HTTP connections after that. Thanks. -
Django-messages app - display message as a conversation
I'm beginning with Django and I had a glace at Django-messages app. I decided to follow the way they do. Thanks to parent_message and timestamp we could display a view conversation (sender & receiver). In my message_view.html I got the last message (which is in reality a message from a user) and I got the possibility to answer the message thanks to reply views. Does anyone has an idea about how display the whole conversation. I got in my template the first two steps: last message (message.id, which is in reality a message from a user) form to answer () the all conversation (parent_messages of message.id in order with timestamp) message/models.py class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1000) parent_message = models.ForeignKey('self', related_name='next_messages', null=True, blank=True, on_delete=models.SET_NULL) timestamp = models.DateTimeField(auto_now_add=True) read_at = models.DateTimeField(_("read at"), null=True, blank=True) replied_at = models.DateTimeField(_("replied at"), null=True, blank=True) #is_read = models.BooleanField(default=False) def new(self): if self.read_at is not None: return False return True def replied(self): if self.replied_at is not None: return True return False def __str__(self): return self.message class Meta: ordering = ('timestamp',) def inbox_count_for(user): return Message.objects.filter(receiver=user, read_at__isnull=True).count() message/views.py @login_required def view(request, message_id, form_class=ComposeForm, quote_helper=format_quote, subject_template=_(u"Re: %(subject)s"), template_name='message_view.html'): user = request.user … -
Django: ContentType matching query does not exist
I am creating a comment thread for my project and I faced above stated error. here is the traceback: Traceback (most recent call last): File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\GitHub\Portfolio\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\GitHub\Portfolio\comments\views.py", line 22, in comment_thread content_type = ContentType.objects.get(model=c_type) File "D:\GitHub\Portfolio\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\GitHub\Portfolio\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /comments/11/ Exception Value: ContentType matching query does not exist. And its associated code in views.py: def comment_thread(request, pk): obj = get_object_or_404(Comment, pk=pk) content_object = obj.content_object # post that the comment is on content_id = obj.content_object.id initial_data = { 'content_type': obj.content_type, 'object_id': obj.object_id } form = CommentForm(request.POST or None, initial = initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) object_id = form.cleaned_data.get('object_id') body = form.cleaned_data.get('body') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_queryset = Comment.objects.filter(id=parent_id) if parent_queryset.exists() and parent_queryset.count() == 1: parent_obj = parent_queryset.first() comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id, body=body, parent=parent_obj ) return HttpResponseRedirect(obj.get_absolute_url()) context = { 'comment': obj, 'form': form, } return render(request, 'comments/comment_thread.html', context) If I replace content_type = ContentType.objects.get(model=c_type) with content_type = ContentType.objects.get_for_model(Blog) it … -
How to replace celery task with azure service bus in a django application?
I am asked to use the azure service bus instead of celery in a Django application. Read the documentation provided but didn't get a clear picture of using service bus instead of a celery task. Any advice provided would be of great help. -
Loggin users in using Django AuthenticationForm
I am trying to use the AuthenticationForm class to log users into my Django application. Here is my login_view in views.py: def login_view(request): form = AuthenticationForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("users:index")) else: # form is invalid: return render(request, "users/login.html", {"message": "Invalid credentials."}) The above code does not work and always results in an "Invalid credentials" message. What am I doing wrong?