Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
How to pass data from html to django view to use in URL?
I'm getting an error while working with django urls. I want to pass the value of Name input field after i hit the submit button. Let's say I've this html form- <form method='POST' action="{% url 'submittedform' slug=[firstname] %}"> {% csrf_token %} <div> <label for="name">Name</label> <input type="text" name="firstname" id="name"> </div> <div> <label for="email">Email</label> <input type="email" name="useremail" id="email"> </div> <div> <label for=phone>Phone</label> <input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}"> </div> <input type="submit" name="" id="btn" value="Submit"> </form> Here's my view that handling it- def submittedform(request, slug): if request.method == 'POST': # do something here return render(request,'myapp/welcome.html') return render(request,'myapp/welcome.html') and here's my view that's handling it- urlpatterns = [ path('index/',views.index ,name='index'), path('welcome/<slug:slug>/',views.submittedform, name='submittedform') ] I'm not using django forms. How can i get welcome/name working. -
Expand user model when fetching user data from Active Directory
I am using django_python3_ldap to connect to active directory. I can import users and sync them, making sure that the users that are already in the AD can log into the app without needing separate credentials. However, issue is that in addition to username, first_name, last_name and email, I want to import phone and office location from the AD. However, merely adding these fields causes the sync to break. I read from various tutorials that I should extend the Django user-model, but the import used by the library does not support extended one-to-one values. I am not confident in entirely replacing the django user model, so is there any good way to expand the user model to include these fields? -
Pycharm unresolved preference in Django project
I just created two projects by Django in virtual environment by python3 -m venv venv and pipenv, but they all report the unsolved reference warning in Pycharm. I have searched many methods on the internet, also changed the local interpreter, but all dont work. Current interpreter settings for my Pycharm in following images: The structure of project Also when I type from Django. in the Pycharm editor, it can not auto import modules. -
Web app framework advice for frontend page that works with backend MSSQL
I have a relic program at work with the backend that runs on Ms SQL, besides tables and views the programs business logic runs on stored procedures. These stored procs are executed by parsing xslt stylesheets that insert input fields and return results from tables which currently makes use of Internet Explorer's engine and runs as an executable desktop program. I would like to know from the community what framework I should consider using where I want to use the existing backend but control what appears on a modern browser, an example would be creating a new user. When the stored proc is called it is waiting for a username and password, I would like to control and force the user along a breadcrumb trail until they have completed the mandatory fields for the stored proc to update the table. I am comfortable with python and read up about using Flask, I have also dabbled in Angular. I would like to create these screens as quickly as possible and use Electron to publish it back as a desktop application. Typescript seems easier to understand than Javascript for me, or I am considering using Django and boxing myself into it. If … -
Django QuerySet return duplicate value on distinct, but does distinct on chaining count
I'm new to django, building a tiny project to get myself familiar with django, therefore still using default *qlite settings for storage. Here's the models defined, only with the fields related to this question: class Album(models.Model): id = models.CharField(max_length=32, primary_key=True) class Track(models.Model): name = models.CharField(max_length=128) album = models.ForeignKey(Album, on_delete=models.DO_NOTHING) Assume that I got: 2 albums: Album(id='a'), Album(id='b') 4 tracks: Track(name='a1', album='a'), Track(name='a2', album='a'), Track(name='b1', album='b'), Track(name='b1', album='b') When trying find out how many music albums are there in the selected music tracks, in this way. Track.objects.distinct('album').count() django complains that DISTINCT ON fields is not supported by this database backend. I thought this would be as easy as a sql statement like SELECT DISTINCT(album) FROM track; Then after some research, I found another way to achieve my goal, though something's kinda strange under the hood. Track.objects.values_list('album', flat=True).distinct().count() The query returns 2, the result I'm looking for, good. But without the count(), as below Track.objects.values_list('album', flat=True).distinct() The returned QuerySet contains 4 values, e.g. <QuerySet ['a', 'a', 'b', 'b']>. I'm curious about why this is happening, but didn't find any asked question similar to this, hope I could receive some help here, thanks. -
What does this error on Datepicker means? And how can it be resolved?
I am having this error after I click the update button from my modal. https://www.screencast.com/t/NOJr22Jyip Other data I submit is ok only this datepicker has an issue. <div class="row"> <div class="col-xl-12"> <div class="form-row"> <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="birthday">Birthday</label> <input type="text" class="form-control Dtpicker" id="birthday" name="birthday" value="{{employee.birthday}}" > </div> </div> </div> </div> </div> Views.py def save_employee_update(request): bday = request.POST['birthday'] employee = Employee.objects.get(employee_id=emp_id) employee.birthday = bday employee.save() # return render(request, 'index.html', {'form': form, 'successful_submit': True}) return render(request, 'index.html') JS for it. $(".Dtpicker").datetimepicker({ format: "YYYY-MM-DD", useCurrent: false, icons: { next: 'fa fa-angle-right', previous: 'fa fa-angle-left' } }) $(document).on("click", "#employee_update_btn", function () { if ($('#birthday').val() == ''){ return } }); After I click the update button the alert shows up but when I tried to print the value of birthday it does not contain anything. And That error show up. -
Failed to setup Postgresql in Django in namecheap
connection = Database.connect(**conn_params) File "/home/hatelsln/virtualenv/myunion/3.6/lib/python3.6/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "hatelsln_hatelsln", database "hatelsln_myunion", SSL off -
Django: Get one to many data
I am current working on a project in Django where i have to get the information of the routers and the commands data. **Query that I want to apply** Select * From dashboard_routerdata, dashboard_alarmactive Where dashboard_routerdata.id = dashboard_alarmactive.routerID_id The method Im used is time consuming. Can you suggest any thing to how to apply this query. -
User can update or delete data which created by others
class StoryViewSet(viewsets.ModelViewSet): serializer_class = StorySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) I have viewset with all CRUD functions. The problem is that user can edit or delete stories of another user, I found DjangoModelPermissionsOrAnonReadOnly in permissions, but I cannot even create. I am using author as foreign key in Storymodel. Also I am using rest_framework.authtoken. So, I think there is two options, create own permission or rewrite some permission. Which one is better? -
How to clean the json output of a @property variable in Django Rest Framework
The issues is, when I do a get request for this model, the JSON response is not clean making it difficult to work with in Retrofit. Here is an example JSON output: [ { "id": 1, "restName": "Buddy's", "banner": "http://127.0.0.1:8000/media/buddysImg.jpg", "zipcode": 48212, "restRating": { "rating__avg": 4.0 }, "website": "Buddys.com", "phone": 3138929001, "restPrice": 0.0 } ] And this is how I'd like it to look: [ { "id": 1, "restName": "Buddy's", "banner": "http://127.0.0.1:8000/media/buddysImg.jpg", "zipcode": 48212, "restRating": 4.0, "website": "Buddys.com", "phone": 3138929001, "restPrice": 0.0 } ] Here is my model : class Rest(models.Model): restName = models.CharField(max_length=50, null=False, default = " ") zipcode = models.PositiveIntegerField( null=False, default = 0) #restRating = models.FloatField( null=False, default = 0) banner = models.ImageField( null=True) website = models.CharField(max_length=50, null=False, default = " ") phone = models.PositiveIntegerField( null=False, default = 0) restPrice = models.FloatField( null=False, default = 0) @property def restRating(self): avg = Rating.objects.filter(restId=self.pk).aggregate(Avg('rating')) return avg def __str__(self): return self.restName And here is my serializer : class restSerializer(serializers.ModelSerializer): restRating = serializers.FloatField class Meta: model = Rest fields = ['id', 'restName', 'banner', 'zipcode', 'restRating', 'website', 'phone', 'restPrice'] Thank you for the help.