Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cmd not displaying anything when using runserver command
I have opened port 8080 on the windows defender firewall but am still stuck when I did start project everything was created fine, this is my first time using django so I imagine ive done something wrong with the command lines, you can see what ive done here: Nothing seems to do anything and when I try to connect to local host it says it cant be reached :( -
Updating django ManytoMany relationship with rest framwork modelserializer
Updating django ManytoMany relationship with rest framwork modelserializer I am using django and just getting started with API's through the rest framework. I am using the built in Model and viewserializer for a profile model. The profile model has "following" attripute which keeps track of the profiles followers as a manytomany relationship with other profiles. Through my API I am trying to add a profile when a the this queryset when the followbutton is pressed however the Patched request through the API instead replaces the whole following set instead of simply appending it. I basically want the API to use the "add" method for m2m in django. Any tips? ## models.py ## class Profile(models.Model): user = models.OneToOneField('User', on_delete=models.CASCADE) following = models.ManyToManyField('Profile', blank=True, null = True, symmetrical=False) def __str__(self): return str(self.user.username) serialisers.py `class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('id', 'user', 'following') ## views.py class ProfileView(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer ` router = routers.DefaultRouter() router.register('profiles', views.ProfileView) urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path('following', views.following, name = 'following'), path('profile/<str:username>', views.profile, name = 'profile'), #API path('api/', include(router.urls))` -
How to use django-filter in DRF
Here u can see my views with filter class ProductFilter(django_filters.FilterSet): min_price = django_filters.NumberFilter(name="price", lookup_type='gte') max_price = django_filters.NumberFilter(name="price", lookup_type='lte') class Meta: model = Ad fields = ['min_price', 'max_price'] class FindByTag(generics.ListAPIView): queryset = Ad.objects.all() serializer_class = AdDetailSerializer filter_class = ProductFilter Look down below for my urls for this view class urlpatterns = [ path('api/v1/tag/select?', FindByTag.as_view()) ] And finally my serializer class AdDetailSerializer(serializers.ModelSerializer): class Meta: model = Ad fields = '__all__' So, the main problem is that i send a GET request to http://localhost:8000/api/v1/tag/select?max_price=10000 and receive all records from my postgres db, filter doesn't work, can someone explain me why? Fell free to answer. -
Django settings.py statement executed twice
I have the following code in my settings.py file and when I startup my server, the print statement gets called twice. Why is that? settings.py if os.environ.get('DJANGO_DEVELOPMENT'): print('Development Mode') DEBUG = True ADMIN_ENABLED = True Console Development Mode Development Mode Performing system checks... System check identified no issues (0 silenced). July 16, 2020 - 20:34:23 Django version 3.0.8, using settings 'MyApp.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. -
Django annotate using field of the foreign key
I almost have it, only the last piece is missing: The model Achievement has a foreign key to Subskill, User and a CharField type. I want to annotate a queryset of Subskill with the tipe of the relative achievement, if any, otherwise leave it empty. Until now I have the following: def with_achievement_type(self, user): return ( self.prefetch_related('achievement_set') .annotate(achievement_type=Case( When(achievement__user=user, then=Value('YAY')), default=Value(''), output_field=CharField())) ) This puts 'YAY' if the Subskill has an achievement connected to the specified user, but how can I annotate with the the achievement__type instead? -
In Djagno app deployed at Heroku, image broken if DEBUG=False
I am using Django ImageField to upload an image and from views.py post it to a page. I deployed the site at Heroku, with DEBUG=True. Everything works well. But when I set DEBUG=False, the image gets broken. In the following image, you can see the image source and image is broken <img src="/media/images/bcc.jpg" ,width="500" height="400">. The image source remains the same when DEBUG=True and image get displayed. So during production, I have to set DEBUG=False but causing this broken the image. How to resolve this issue. -
URL changing when passed as GET parameter
I am trying to pass a URL from javascript to a django app, as a GET parameter, in the form of: http://djangoapp.com/http://newsite.com However, when I receive http://newsite.com in django it changes it to http:/newsite.com (missing slash). I have tried using encodeURIComponent('http://newsite.com') in javascript before sending but it is still the same result. -
Can Django's select_for_update deadlock when used on the same record twice?
I have some code that would be a lot simpler with nested calls to select_for_update(), but I'm afraid I'm setting myself up for a deadlock. Example: with transaction.atomic(): uu1 = UniUser.objects.select_for_update().get(pk=uupk) with transaction.atomic(): uu2 = UniUser.objects.select_for_update().get(pk=uupk) # why no deadlock here?? uu2.bio = 'i like pizza' uu2.save() uu1.bio = 'i like pie' uu1.save() I would have expected the second select_for_update() to deadlock since it's trying to lock an already locked record, but this code runs just fine and we end up with 'i like pie' in the bio. Ditto if I remove the inner transaction and just lock the same record twice in the same transaction. Why is there no deadlock here? Is this safe code? In case the answer is database specific, I'm using Postgres. -
How are Django Migrations Run in Tests
I have created a sequence in one of my migration files, but that sequence is never found when running tests From my understanding, all migrations inside INSTALLED_APPS are run even if the tests are done for specific apps only, but the migration was apparently never run. So How do I make sure the migrations are all run when doing tests? -
Django Model Field for a Secure String
In short: I want to store strings encrypted in the database and decrypt them when i need them. What is the best practice for this? Context: I am building an application that uses a 3rd party API that requires a login and password. I want to store the credentials that will be used for the 3rd party API in the database as their will be many different credentials. I was looking on the django documentation and on stackoverflow but i only find things that hash passwords. -
The browser does not render a template that contains both a detail view and a list view
I am building a Q&A website as my first django project for practice (bad choice for a first project), however I created a question model(PoliticsPost) and an answer model(Answer) and I linked the answer model with the question model using a foreign key and the answer instances with the question instances using the ID of the question being answered. The logic of the website is that the questions are displayed in a template (list view), and each question is a link to its description (detail view) and all the answers associated with it (list view). The issue is that, although I inserted both the question context name and the answer context name in the template, the browser only renders the questions detail view. (Sorry if this is confusing, it is because I am confused in the first place) Here is the code: views.py: class CreateAnswer(LoginRequiredMixin,CreateView): model = Answer fields = ['content'] success_url = reverse_lazy('Lisk home') question_id = 'qid' pk_url_kwarg = 'aid' def form_valid(self, form): try: question = PoliticsPost.objects.get(pk=self.kwargs[self.question_id]) except PoliticsPost.DoesNotExist: form.add_error(None, 'Invalid question') return self.form_invalid(form) form.instance.post = question form.instance.author = self.request.user return super().form_valid(form) class Answers(ListView): model = Answer context_object_name = 'answers' ordering = ['-date_posted'] urls.py(not root): path('politicspost/<int:pk>/',views.Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html'), name='politics_post_details'), path('politicspost/<int:qid>',views.Answers.as_view(template_name='lisk_templates/politics_post_details.html'),name ='answerslist') … -
Django, Heroku, DisallowedHost at / but host is in allowed hosts lists
I have a Django app deployed to Heroku but when I try to visit it I get disallowed, hosts error saying that the Heroku host URL is not in the allowed host but it actually is. The error Invalid HTTP_HOST header: 'scr-rivendell.herokuapp.com'. You may need to add 'scr-rivendell.herokuapp.com' to ALLOWED_HOSTS. settings: ALLOWED_HOSTS = ['localhost', '127.0.0.1:8000', 'https://scr-rivendell.herokuapp.com/'] I checked in the shell to make sure I'm right: >>> import django >>> django.conf.settings.ALLOWED_HOSTS ['localhost', '127.0.0.1:8000', 'https://scr-rivendell.herokuapp.com/'] -
Django Post detail url url not found
Django Post detail url domain.com/api/v1/1 not found but domain.com/api/v1 works given the following url patterns, note that ok with value of 1 exists, Project urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/vi', include('posts.urls')) ] Api urls from django.urls import path from .views import PostList, PostDetail urlpatterns = [ path('<int:pk>/', PostDetail.as_view()), path('', PostList.as_view()), ] -
In Django, which directory should static files be?
I have my static files in sub_app directory. I will name the folder sub_app where view.py, model.py are located. And when I run python manage.py findstatic it returns sub_app\static folder. I have another folder name as main_app, where settings.py file is located. These two folders and manage.py file is located in a root folder. I have no issue when DEBUG=True, but when I run DEBUG=False, I got following warning venv\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: root\static\ warnings.warn(u"No directory at: {}".format(root)) Here are static files settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Where should my static files? -
JavaScript not executed on clicking button in Django
I am new to web programming and currently working on Django. I have a html page with 3 buttons <p style = "color:black;"> <b> Your options: </b></p> <p style="padding-bottom: 40px;"><button>A</button></p> <p style="padding-bottom: 40px;"><button>B</button></p> <p style="padding-bottom: 40px;"><button>C</button></p> The script that needs to be executed after clicking on any one of this is as follows: <script> document.getElementById('submit_button').onclick = function(e) { e.preventDefault(); $('#submit_form').css('display', 'none'); $('#loading').css('display', 'block'); $.ajax({ beforeSend: function (xhr, settings) { xhr.setRequestHeader('X-CSRFToken', $('[name=csrfmiddlewaretoken]').val()); }, url: window.location.pathname, type: 'POST', processData: false, contentType: false, success: function () { window.location.reload(); } }); return false; }; </script> However, when I click on any one of the buttons, nothing happens. -
Can't pass two parameters in my URL to retrieve in my views with buttons
I am coding my first Django website (a fantasy sport website) and I am encountering a problem with the management of my requests. Basically what I want to do is allow two request.GET.get() methods on the same html page. Right now I have two different buttons that successfully send information through the URL that I can retrieve and filter in my views.py. The problem is that I can't get them both to work at the same time. My main page is http://127.0.0.1:8000/Main/ A user on my website will be able to manage multiple teams. This user will be able to navigate through their teams with the following HTML: <div onclick="chooseTeam()"><a href='?team_number={{team.number}}'>X</a></div> Which send the team number in the URL as such: http://127.0.0.1:8000/Main/?team_number=X This number is then recuperated in the views.py with: team_number = request.GET.get('team_number', 1) This first part works exactly as planned. The problem arise when a user who has already navigated to a specific team try to activate another button. For example, I have a filter button that allows the user to only see canadian players on the main page. This goes in the HTML as follows: <p><input id="CanadianPlayerFilter" type="checkbox" name="Canadian" <label for="CanadianPlayerFilter">Canadian</label></p> Similarly to my team navigation button, … -
Alguien sabe como puedo agregar una lista con ajax, estoy trabajando con django
Estoy tratando de almacenar unos datos de los cuales son unos productos, pero nose como hacerlo, me e cosultado y de la unica forma de hacerlo es con ajax y no mananejo muy bien ese lenguaje quien me puede ayudar? -
How to cacluate the time variable and comapre a time data with the current time by python django?
For example, I have a model in models.py which looks like this: class BlackList(models.Model): username = models.CharField(max_length=1000) flag1 = models.BooleanField(default=False) trytologintime = models.DateTimeField(auto_now_add=True, null=True) And in the views.py, what I try to do is something like this: ...... username = request.POST.get('username') # Get username input first password = request.POST.get('password') user = authenticate(request, username=username, password=password) black_list_user = BlackList.objects.get(username=username) # timenow = get time for now ( I do not know how to get it foe now ) passtime = timenow-black_list_user.trytologintime (Also do not know how to do the subtraction for time variable) if passtime > 24 hr (How to compare the time) black_list_user.flag1 = True black_list_user.save() ...... So, my main questions are: how to get the current time? how to do subtraction and compare two time variable? -
Unable to import Django.shortucts
I’m new to Django (I started about an hour ago) and I received an error under the views.py file that says ‘unable to import django.shortcuts. pylint(import-error).’ I made sure pylint was installed using pip install. How do I fix this? -
I can see custom user password hashes in Django Admin
I made my own custom user, extending AbstractBaseUser. In the past, this has worked perfectly, however, now, I can see the user's password hashed in admin: pgkdf2_sha256$150000$tv9jF8Iie9kR$Z8X3Kbn2fudQnIBr0fymNNnfFYMYttiQ2emTlG+wkYM= How can I change this back to the Django default for passwords? Thanks!! -
is username still required if I create customer django user model to use email for authorization
I am working on creating a custom user model for my django project to use email for authorization. Can I leave out the username field or is it still required? I have been searching but it is not clear. Thanks. -
How to convert this raw query to Django ORM?
I have three models. class Group(models.Model): name = models.CharField(max_length=64 class AccountPermission(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) field = models.CharField(max_length=256) text_value = models.CharField(max_length=256, null=True, blank=True) date_value = models.DateField(null=True, blank=True) class Data(models.Model): regions = models.ArrayField() companies = models.ArrayField() last_updated = models.DateField() I'm trying to take this sql statement SELECT * FROM Data d INNER JOIN account_permissions p0 ON p0.group_id = %s AND p0.field = 'regions' AND p0.text_value = ANY(d.regions) INNER JOIN account_permissions p1 ON p1.group_id = %s AND p1.field = 'companies' AND p1.text_value = ANY(d.companies) INNER JOIN account_permissions p2 ON p2.group_id = %s AND p2.field = 'last_updated' AND p2.date_value >= d.last_updated and convert to the equivalent Django ORM code. I've referred to Django's model expressions, however, I can't make sense of what I should be using/how to even begin. Thoughts? -
How to add JS to the Django model admin add / change form?
I wanted to hide some fields in the admin model add / change form so I added my custom JS script to the Media class of ModelAdmin via the get_form method of the MyModelAdmin class. def get_form(self, request, obj=None, **kwargs): if obj is None: self.Media.js = tuple(['admin/script1.js']) else: self.Media.js = tuple(['admin/script1.js', 'admin/script2.js']) self.form = MyModelForm return super(MyModelAdmin, self).get_form(request, obj, **kwargs) Though, this JS script is working it is also being loaded in the Admin's Change Object Table (list of model objects page) and not just the form. This is causing unwanted behavior in the Change Table. How should I stop the JS from being loaded into the change list / table? -
Model querys Django
i have this model with the following relation. from django.db import models from django.contrib.auth.models import User class UserModel(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.user) class BlogModel(models.Model): user = models.ForeignKey( UserModel, on_delete=models.SET_NULL, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=True) body = models.CharField(max_length=1000, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) + ", " + str(self.title) How do i query every blogpost a paticular user had made? Thanks in advance for the answer! -
Django: Aggregate through a model_set's model_set
These are my models: class Streamer(models.Model): name = models.CharField(max_length=50, null=True) class Account(models.Model): streamer = models.ForeignKey(Streamer, on_delete=models.CASCADE) name = models.CharField(verbose_name="Account Name", max_length=100, null=True) class Stream(models.Model): host = models.ForeignKey(Account, on_delete=models.CASCADE) score = models.PositiveIntegerField("Score", default=0) A Streamer can have multiple accounts queried through an account_set. An Account can have multiple streams associated to it through a stream_set. So how can I get all of the streams associated to all of the accounts associated to the Streamer? Hope that makes sense lol. It basically needs to be something like (not an accurate example): streamer = Streamer.objects.all()[0] # Get first streamer streamer.account_set.stream_set.count() for example, or something like this. Thanks in advance!