Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to execute multiple conditions in 1 view in Django
I have 2 if else conditions within the 1 function based view. When the page renders it executes the first condition and return but do not execute the second condition. Please take a look on code. View: Def Dashboadr(request): '''Birthday Slider''' today = date.today() DoBworkers = CoWorker_Data.objects.filter(dob__day=today.day, dob__month=today.month).all() if DoBworkers.exists(): return render(request, 'dashboard/Dashboard.html', {'DoBworkers': DoBworkers}) else: messages.success(request, 'There is no birthday today.') return render(request, 'dashboard/Dashboard.html') '''Payment Slider''' today = date.today() three_days_before = today - timedelta(days=4) #start_date = end_date - timedelta() paymentNotification = CoWorker_Data.objects.filter(joiningDate__day__lt=three_days_before.day).all() if paymentNotification.exists(): c = context = ({ 'paymentNotification': paymentNotification }) return render(request, 'dashboard/Dashboard.html', c) else: messages.success(request, 'No record found.') return render(request, 'dashboard/Dashboard.html') return render(request, 'dashboard/Dashboard.html', c ) Ignore indentation.. -
Django Server: python manage.py runserver - Not Found: /url/
Hi I am a newbie when it comes to Django and am getting stuck on what seems a very basic issue. When I create a new Django project in the conda prompt and then start the django server, it always seems to try redirect to a url that doesn't exist. Steps taken in conda prompt: django-admin startproject mysite cd mysite python manage.py runserver This will start the server with the usual http://127.0.0.1:8000/ local site however when loading this up in my chrome browser it always redirects to http://127.0.0.1:8000/blog/ I see in the conda prompt that Not Found: /blog/ is shown screenshot ## I haven't changed any code in the project, so the urls.py haven't set a redirect in the url pattern or anything like that. How do I stop this redirect from happening? Note: if I do the following python manage.py runserver 7000 to change the port this redirect doesn't happen, but I am trying to solve for why its happening on 8000 Many thanks! -
Issue in django 1.7.2 version while doing makemigrations
when created new model and executing makemigrations in django 1.7.2 version django.core.exceptions.FieldError: Local field u'id' in class 'PhotoFeatureImage' clashes with field of similar name from base class 'PhotoFeature' -
How to add a select to filter table with JQuery dataTable
I am newbie and develop an app on Django I use for the first time the DataTable with bootstrap 4 and it works but I would like to add select with 3 options that enable user to filter table on a specific column I read options in documentation but did not found what I need is it possible to do it? thanks, -
my django query: how to improve the speed of list view
List page is paginated and displaying only 10 journal posts. Despite this, there are 95 queries being performed. It's affecting the page load speed. Instead of loading <1 second it's taking around 4-5 seconds. Here are my code, please check and let me know how to optimize. views.py class PostListView(LoginRequiredMixin,ListView): model = Post paginate_by = 10 def get_queryset(self): qs = super(PostListView, self).get_queryset().filter(Q( Q(language_id__in=self.request.user.native_language), ~Q(user_id__in=self.request.user.forbidden_user_list))).order_by('-created') return qs def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['list_type'] = 'all' models.py class Post(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=60) text = models.TextField() native_text = models.TextField(blank=True) created = models.DateTimeField(default=timezone.now, db_index=True) # updated = models.DateTimeField(auto_now=True) # is_corrected = models.BooleanField(default=False) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='posts_liked', blank=True) language = models.ForeignKey('account.Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.text def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) @property def get_correctors(self): from account.models import Profile as User result = list(set(User.objects.all().filter((Q(correctedrows__post_id=self.id) | Q(perfectrows__post_id=self.id) | Q(comment__post_id=self.id))))) return result -
How to validate username and password in dajngo rest framework?
Here I am trying to register users.But the validate_username is not working.With this function I am trying to make username between 6 and 15 characters long.The username is unique but my custom validation is not working. And also default AUTH_PASSWORD_VALIDATORS is also not working.It is returning message if only the two password fields doesn't match with this function def validate(self, data) but the numeric,common password validator is not working. How can I validate username and password in a right way ? class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name','last_name','username','email','password1','password2','profile'] def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def validate_username(self, value): data = self.get_initial() username = data.get("username") if len(username) < 6 and len(username) >15: raise ValidationError('Username must be between 6 and 15 characters long') return value def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], ) -
How can I override many to many field's intermediary model's object name
When I delete a data which contain a many-to-many field on django-admin, the below alert message pops up. Summary Owners: 1 Owner-salesman relationships: 2 Objects Owner: Chief Telecom (Own. fe311e..) Owner-salesman relationship: Owner_related_salesman object (7) Owner-salesman relationship: Owner_related_salesman object (8) I want to override the string "Owner_related_salesman object (7)" which I guess is in the intermediary model's definition. What should I do? Here's my code. class Owner(models.Model): # PK field id = models.AutoField( verbose_name='Serial Number', primary_key=True, ) # name fields name = models.CharField( verbose_name='Name', max_length=100, blank=True, # many to many fields related_salesman = models.ManyToManyField( verbose_name='Related Salesman', to='Salesman', blank=True, ) class Salesman(models.Model): # PK field id = models.AutoField( verbose_name='Serial Number', primary_key=True, ) # name fields name = models.CharField( verbose_name='Name', max_length=100, blank=True, # many to many fields related_owner = models.ManyToManyField( verbose_name='Related Owner', to='Owner', blank=True, through=Owner.related_salesman.through, ) By the way, I don't want to create a custom intermediary model because when I use it, I can't use the default many-to-many field widget (pic: https://i.stack.imgur.com/aqbhn.png) on django-admin, instead I could only use the inline which I think is bad to use. -
i want an upvote button that when clicked increment the value of a field(integer) in database
my html for button is <td> <a href="{% url 'minor:upvote' %}"> <button type="button" class="likes" style="text-align:center;border-radius:40px;width: 100px;height: 40px">upvote</button> </a> </td> url is.. path('',view=views.upv,name='upvote'), view is def upv(request,id): reporter = Logg.objects.get(id=id) reporter.upvote = reporter.upvote+1 reporter.save() return redirect('/') but the upvote field i.e an integer field with default value 0 is not getting incremented. -
Django timezone not working: doesn't change from UTC
I've checked now the time in ET/New York time and it's 04:39 AM using google search problem is I've set the timezone for new york on the backend and it's not set to this. In [1]: from django.conf import settings In [3]: import datetime In [4]: datetime.datetime.now() Out[4]: datetime.datetime(2019, 11, 21, 4, 38, 4, 124263) In [5]: from django.utils import timezone In [6]: timezone.now() Out[6]: datetime.datetime(2019, 11, 21, 9, 38, 25, 662909, tzinfo=<UTC>) In [7]: settings.TIME_ZONE Out[7]: 'America/New_York' In [8]: settings.USE_TZ Out[8]: True here you can see using django's timezone it's still using UTC timezone. Even though I've set it to NewYork on the backend. -
Django - from _sqlite3 import * - DLL load failed: Modul not found
I get this error when I try to run the local server on a windows machine. Im using the Anaconda 3 Python Distribution (64-bit). Dont know what happened, it worked before. Traceback: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\Myusername\appdata\local\continuum\anaconda3\Lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\users\Myusername\appdata\local\continuum\anaconda3\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\accounts\models.py", line 10, in <module> class UserProfile(models.Model): File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "D:\Users\BKU\Myusername\Desktop\DBAnalytics\dbdjango\env\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) … -
Using Context to pass a variable to a template
Having issues getting a variable to pass to the template, example below: def confirm(request, reference): c = {'return_reference': reference} msg_plain = render_to_string('mail.txt', c) msg_html = render_to_string('mail.html') send_mail( 'Return - Ready for Collection', msg_plain, 'some@sender.com', ['some@receiver.com'], html_message=msg_html, ) And my HTML template: <p>Return reference <strong>{{ return_reference }}</strong>.... Anyway, the result of this is always a blank / null in the return reference... Any assistance would be appreciated. -
Calculate a value from GraphQL and save it in Django models
I am trying to calculate a value from GraphQL. I am sending mutation to Django models but before save it I want to calculate this value with if statement (if the value is greater than 10 divide by 2, if is less than 10 multiply by 2). I don't know where to add this function. Here is my mutation in schema.py class CreatePrice(graphene.Mutation): price = graphene.Field(PriceType) class Arguments: price_data = PriceInput(required=True) @staticmethod def mutate(root, info, price_data): price = Price.objects.create(**price_data) return CreatePrice(price=price) class Mutation(graphene.ObjectType): create_product = CreateProduct.Field() create_price = CreatePrice.Field() schema = graphene.Schema(query = Query, mutation=Mutation) And here is my Django model. Base price is calculated value and function name has two options(*2 or /2 it depends of initial value). class Price(models.Model): base_price = models.CharField(max_length = 20) function_name = models.CharField(max_length = 20, choices = PROMO_FUNCTION) def __str__(self): return self.price_name P.S. Sorry for bad English. Thanks! -
Django routing with VueJS single page has unexpected behaviour when there is no trailing slash in the URL
I have a Django backend, VueJS frontend combination, where I serve a REST API via Django and a single page application with VueJS and vue-router. From this question I got the tip to use the following urls in my main urls.py: urlpatterns = [ re_path(r'^(?P<filename>(robots.txt)|(humans.txt))$', views.home_files, name='home-files'), path('api/', include('backend.urls')), path('auth/', include('auth.urls')), path('admin/', admin.site.urls), re_path(r'^.*$', views.vue), # VueJS frontend ] So I want URLs to behave like this: {baseDomain}/api/users/1/ -> go to backend.urls {baseDomain}/auth/login/ -> go to auth.urls {baseDomain}/admin/ -> go to admin page {baseDomain}/de/home -> vue-router takes over Now these URLs work perfectly fine, however I would expect that {baseDomain}/api/users/1 (without trailing slash) would still go to backend.urls, however what happens is that I land on the Vue page. Adding APPEND_SLASH = True in settings.py does not help either, since it only appends a slash if it didn't find a page to load. But since the regex for my frontend matches anything it always redirects to Vue. My attempt was to fix it by adding: re_path(r'.*(?<!/)$', views.redirect_with_slash) with the following code: def redirect_with_slash(request): '''Redirects a requested url with a slash at the end''' if request.path == '/': return render(request, 'frontend/index.html') return redirect(request.path + '/') But it isn't a very elegant … -
Field name `password1` is not valid for model `User`?
Here I am trying to register user with their profile model.But this code gave me following error django.core.exceptions.ImproperlyConfigured: Field name password1 is not valid for model User. What I am doing wrong here ? class Profile(models.Model): user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,related_name='profile') address = models.CharField(max_length=250,blank=True,null=True) contact = models.CharField(max_length=250,blank=True,null=True) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user','address','contact'] read_only_fields = ['user'] class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) class Meta: model = get_user_model() fields = ['first_name','last_name','username','email','password1','password2','profile'] def validate_username(self, value): data = self.get_initial() username = data.get("username") if len(username) < 6 and len(username) >15: raise ValidationError('Username must be between 6 and 15 characters long') return value views.py class CreateUser(generics.CreateAPIView): serializer_class = UserSerializer queryset = get_user_model().objects.all() -
Unable to add Forgot Password link in Django Admin suit?
In my admin site I have installed a Django suit and here I am trying to add forgot password link but can't add it Before installing the Django suit i added forgot password link and it was working perfectly but after installing suit it's not working now it's not working. do you have any idea ?? login.html: {% extends "admin/base_site.html" %} {% load i18n static %} {% block content %} <form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %} <div class="form-row"> {{ form.username.errors }} {{ form.username.label_tag }} {{ form.username }} </div> <div class="form-row"> {{ form.password.errors }} {{ form.password.label_tag }} {{ form.password }} <input type="hidden" name="next" value="{{ next }}"> </div> {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} <a href="{% url 'password_reset' %}">Forgot password?</a> <div class="submit-row"> <label>&nbsp;</label><input type="submit" value="{% trans 'Log in' %}"> </div> </form> </div> {% endblock %} -
python django create own command and add list as parameter
I want to use py manage.py own_command. I got the following code: from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'create user' def add_arguments(self, parser): parser.add_argument('--username', type=str, help='set username') parser.add_argument('--password', type=str, help='set password') parser.add_argument('--email', type=str, help='set password') parser.add_argument('--group', type=list, default=[], action='append', help='set group(s) like ["basic", "advanced"]') parser.add_argument('--permission', type=list, default=[], action='append', help='set permission(s) like ["delete", "write"]') >py manage.py create_app_user --username dustin --password hdf --email "" --group ["admin", "basic" ] creates usage: manage.py create_app_user [-h] [--username USERNAME] [--password PASSWORD] [--email EMAIL] [--group GROUP] [--permission PERMISSION] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] manage.py create_app_user: error: unrecognized arguments: basic ] I found solutions for django <= 1.7 BUT not for >=2.1 -
How to add header / footer on export on django import-export?
I'm using the django-import-export plugin in admin, and i would like to add a header/footer(images) when exporting data. Is there a way to get a handle on the excel or pdf object maybe when overriding export or before_export ? -
How to populate django form with selection from your models
I have a createsong CBV in django that allows me to create song objects to a model. My question is, in the form i created for the view, how do i make the album column to be auto populated with albums the user created only? See my views below '''Class CreateSong(CreateView): model = Song fields = [album,song_title] Def get_queryset(self): ab = Album.objects.filter(owner=self.request.user) Return Song.objects.filter(album=ab)''' -
Why does Django map the url to the wrong view function?
There are two different apps called index and management, and I try to display a pk + slug url in the first one, and in management the url has uid, but even though there are two different apps and different view functions, Django tries to map the url with pk + slug in management? Project urls.py urlpatterns = [ path('', include('index.urls')), # path('management/', include('management.urls')), ] Index urls.py urlpatterns = [ path('', views.front_index, name="front_index"), path('<str:slug>/<int:pk>', views.front_article_view, name='front_article_view'), ] Management urls.py urlpatterns = [ path('article/<str:uid>/', views.admin_article_view, name='admin_article_view'), ] The error is Reverse for 'front_article_view' with arguments '(UUID('fe179941-49cf-4ea2-a3da-e27363c20cfc'),)' not found. 1 pattern(s) tried: ['(?P[^/]+)/(?P[0-9]+)$'] that I get when clicking the link <a href="{% url 'admin_article_view' article.uid %}">{{ article.title }}</a> from a template in the management app. Thanks for your time and help! -
Are there any safety problems in Django?
Recently , I almost finished a project with Django, but my tutor told me that the project’s data need to be kept safe. It is the first time for me to develop it, so I wonder if there is someway to kept it safety? Or are there any potential issues? I will appreciate if you can tell me how to achieve it. By the way, I choose mysql for database. -
How can I implement a check box in django
I have a PC based gui app and I am trying to duplicate the same functionality in a browser based solution using django. On the PC I have a check box that enables extra functionality for the user. All that I need to do is return the value (True or False) when the box is checked and this will alter the logic in the views module. I have implemented the check box as: <form> <tr><input type="checkbox" name="use_stages" value="use_stages">Use stages</tr> </form> The check box appears in the browser but it will not allow me to check it. I have looked at django forms but that seems like overkill for such a simple requirement. Will I have to go down that route? I am not wedded to a check box. Maybe a button would do with the text toggling as the user clicks on it. Can anyone suggest how I should proceed from here? -
Trigger Background Task With POST request in Django
I want to trigger a background task (just trigger, not require to wait till finish), when user does the POST request. I know, I can do it with celery. But don't want to add the task in queue, as it has to be triggered immediately. This task can be long running, so after triggering I don't want to hold the POST call and just send response as request received. There might be a way using thread, but can I do it with asyncio or any other lib in python. Python 3.5 and Django 2.2 with DRF -
.gif is not responding in python
I get blank screen when i run this code. screen=turtle.Screen() print(screen.bgpic()) screen.setup(900, 650) screen.bgpic("map.gif") input() Posting the image below enter image description here -
Error at setup on Travis with django-pytest, docker
I got errors running pytest on Travis CI but have no idea how to fix it. When I run the command docker-compose run --rm api sh -c "pytest && flake8" on Docker in my local, all the tests pass. Could anyone give me a hint? I have some fixtures on conftest.py as well. A part of the error information api/tests/test_order_items.py EEEEE [ 45%] api/tests/test_orders.py EEEEEE [100%] ==================================== ERRORS ==================================== __________ ERROR at setup of TestOrderItemModel.test_list_order_items __________ self = <django.db.backends.utils.CursorWrapper object at 0x7efe0e94d3d0> sql = 'SELECT "orders_orderitem"."id", "orders_orderitem"."order_id", "orders_orderitem"."pizza_type", "orders_orderitem"."pizza_size", "orders_orderitem"."quantity" FROM "orders_orderitem" ORDER BY "orders_orderitem"."id" ASC' params = () ignored_wrapper_args = (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7efe0fbb4fd0>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7efe0e94d3d0>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) E psycopg2.errors.UndefinedColumn: column orders_orderitem.order_id does not exist E LINE 1: ...SOR WITH HOLD FOR SELECT "orders_orderitem"."id", "orders_or... .travis.yml language: python python: - "3.7" services: - docker before_script: pip install docker-compose script: - docker-compose run --rm api sh -c "pytest && flake8" Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] flake8 = "==3.7.9" autopep8 = "==1.4.4" pytest = "==5.2.1" pytest-django = "==3.6.0" [packages] django = "==2.2.7" … -
Django: How to get id from different model
I hope my title is enough to answer my question, I just want to get the id of model (StudentProfile) when I click the report from the model (studentDiscount), my error is from this line in my admin.py obj.Students_Enrollment_Records__Student_Users.pk I don't know if that is correct. @admin.register(studentDiscount) class studentDiscount(admin.ModelAdmin): list_display = ('Students_Enrollment_Records', 'Discount_Type','my_url_field') ordering = ('Students_Enrollment_Records',) search_fields = ('Students_Enrollment_Records',) def my_url_field(self, obj): return format_html("<a href='https://www.ucc.ph/enrollmentform/?StudentID={}'>Report", obj.Students_Enrollment_Records__Student_Users.pk) my_url_field.allow_tags = False my_url_field.short_description = 'Report' models.py class StudentProfile(models.Model): Image = models.ImageField(upload_to='images',null=True,blank=True) Username = models.CharField(max_length=500,null=True,blank=True) Password = models.CharField(max_length=500,null=True,blank=True) lrn = models.CharField(max_length=500,null=True) Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) class studentDiscount(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True)