Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Did you forget to register or load this tag in Django?
In the django project I am working on, when I add this line {% set alpha = SafeExec.objects.get(testcase=a_test) %} to my html, it is showing this error. How to get rid of it? This is my template code: {% for a_testcases in testcases %} <li><i>{{ a_testcases.0.program.name }}</i> <br/> {% for a_test in a_testcases %} {% set alpha = SafeExec.objects.get(testcase=a_test) %} 1{{ alpha.cpu_time }}1 {% endfor %} <input id="id{{ a_test.id }}" type="checkbox" name="testcases_cbx" value="{{ a_test.id }}" checked/> <label style="display: inline" for="id{{ a_test.id }}">{{ a_test.name }}</label> <br/> {% endfor %} </li> {% endfor %} This is screenshot of error: -
Output the count from two Models in the same view in Django
class Album(models.Model): title = models.CharField(max_length=100, blank=True, default='') price = models.FloatField() upload_time = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('upload_time',) class Status(models.Model): user_id = models.IntegerField() album_id = models.IntegerField() favorite = models.BooleanField(default=False) purchase = models.BooleanField(default=False) history = models.BooleanField(default=False) def __str__(self): return self.user_id in a ModelViewSet I wrote like this: class index(viewsets.ModelViewSet): serializer_class = AlbumSerializer queryset = Album.objects.all() As the image shown above, I need output the count of purchases of each Album, e.g. Album 1 has been purchased 4 times, Album 3 has been purchased 1 time. But right now, my index view only generate the fields in Album Model. What should I do to implement this, add the purchase number for each Album? Need your help... -
Django Inline Formsets
Good morning, I'am struggling against this for a long time and i cant find enough information to solve this. I have this two Models: class Perfil(models.Model): CORE = (('3', '3'),('6', '6')) user = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Username") timestamp = models.DateTimeField(auto_now_add=True) nome = models.CharField(verbose_name="Perfil", max_length=200, unique=True, null=True, blank=True ) num_bobines = models.PositiveIntegerField(verbose_name="Número de bobines") largura_bobinagem = models.DecimalField(verbose_name="Largura da bobinagem", max_digits=10, decimal_places=2) core = models.CharField(verbose_name="Core", max_length=1, choices=CORE) gramagem = models.DecimalField(verbose_name="Gramagem", max_digits=10, decimal_places=2) espessura = models.DecimalField(verbose_name="Espessura", max_digits=10, decimal_places=2) densidade_mp = models.DecimalField(verbose_name="Densidade da matéria prima", max_digits=10, decimal_places=2) velocidade = models.DecimalField(verbose_name="Velocidade", max_digits=10, decimal_places=2) producao = models.DecimalField(verbose_name="Produção", max_digits=10, decimal_places=2) class Meta: verbose_name_plural = "Perfis" ordering = ['-timestamp'] def __str__(self): return '%s' % (self.nome) class Largura(models.Model): perfil = models.ForeignKey(Perfil, on_delete=models.CASCADE, verbose_name="Largura") num_bobine = models.PositiveIntegerField(verbose_name="Bobine nº") largura = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) class Meta: verbose_name_plural = "Larguras" ordering = ['perfil'] def __str__(self): return '%s - Bobine nº: %s, %s mm' % (self.perfil, self.num_bobine, self.largura) When i create one "Perfil" it generates "Largura" based on "num_bobines": def perfil_larguras(sender, instance, **kwargs): for i in range(instance.num_bobines): lar = Largura.objects.create(perfil=instance, num_bobine=i+1) lar.save() post_save.connect(perfil_larguras, sender=Perfil) Now i am struggling with creating a inline formset to update the field "largura" for all instances with the same foreignkey. Can anyone help me with this? Ty -
Instamojo payment gateway webhook issue
I am integrating instamojo payment gateway with django application. The payment process is working properly, but webhook service is not working. I have mentioned webhook url in request and for that I have to disable CSRF verification. I am using csrf_exempt decorator but its not working. I am getting 403 error. I am using this webhook sample code - https://support.instamojo.com/hc/en-us/articles/208485745-Webhook-URL-in-PHP-Python -
overriding django.contrib.auth.views.login
I've seen lot of posts to do a custom login page and custom login views But I don't want to create all the custom view and login form for my simple purpose In my case, everything is set-up with the Django authentication Built-In system, I need one further thing, when I try to login I'd like to check an additional condition: I have a Profile model like this: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') actif = models.BooleanField(default=True) And I would like to check if user.profile.actif: I want to do this: def login(user, *args, **kwargs): if user.profile.actif: return super(?, self).login(*args, **kwargs) return ? Thank you -
Django User Model questions
I'm new to Django so I have some questions that might seem basic to you. I'm looking to create a platform that is open to both individuals and companies and I'm trying to design the user auth for an API that runs on DRF. I need to provide mobile platform access so I'm thinking of using OAuth via django-oauth-toolkit. Having difficulty understanding: Should I separate the login flow into a separate app? How do I know when I should spin up a separate app? Do I manage the profiles via the built in admin area? Is this secure for production environments? Should I separate individual profiles and company profiles into separate apps or just models extending the Base User? How do I allow the individual profiles to link their logins to social media accounts with django-allauth while storing extra information like birthday/name etc regardless of which mode of login? Thanks! -
Display the descriptive status of choices field
I created such a data model of UserProfile: class UserProfile(models.Model): STATUS = ( (1, 'male'), (0, 'lady'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.IntegerField(choices=STATUS, default=1) The template is expected to show the descriptive gender: <div class="row"> <div class="col-md-4 text-right"><span>Gender:</span></div> <div class="col-md-8 text-left"><span>{{ user_profile.gender }}</span></div> </div> However, it shows Gender: 1 rather than Gender:male How could enable the template to display the descriptive gender? -
Add Model Attribute to an instance if it doesn't have one
i've recently added a optional costs Model option to Estimate creation(finance). Now that, when i'm trying to edit statement, the statements created after the optional costs updation, updates successfully. but the previous statements that doesn't have the optional costs model attribute fails on updating. this is what i've tried if hasattr(instance,"optional_amount"): optional_estimate_amounts = optional_estimate_amounts_formset.save(commit=False) for f in optional_estimate_amounts: f.estimate = instance f.save() for obj in optional_estimate_amounts_formset.deleted_objects: obj.delete() else: for optional_estimate_amounts in optional_estimate_amounts_formset: optional_amount_description = optional_estimate_amounts[ 'optional_amount_description'] optional_amount = optional_estimate_amounts['optional_amount'] OptionalEstimateAmounts( estimate=data, optional_amount_description=optional_amount_description, optional_amount=optional_amount ).save() currently it throws type error. I'm wondering how to create a new optional amount model attribute to an existing estimate instance if it doesn't have one when trying to edit estimate? -
Django add new field on model if new object is created from another model
I have too model : class Exam(models.Model): name = models.CharField(max_length=100,default="test") user = models.ForeignKey(User) class UserScore(models.Model): user = models.OneToOneField(User,primary_key=True,on_delete=models.CASCADE) resultat = models.IntegerField(default=0) i'm new of Django, i want when i create a new exam create dynamically new field on my userscore model for all user, can you help me please Thks -
django map form field to another key
django form is, In [55]: class my(forms.Form): ...: abc_pqr = forms.CharField() Request data is {'abc-pqr': 'data'}. I want to map abc-pqr key to abc_pqr form field, how do I achieve this without changing request data ? -
django 2 - Nested query based off multiple models
I'm trying to wrap my head around how to achieve a nested/chained query based on my needs. There might be a better way to get the results I need so please let me know. Trying to get the authenticated user and get a list of friends, which I have working and I get a queryset object of friends. I would like to pass the queryset object of friends into another query that searches the Post model, matches the username found Friend.users to the Post.creator so I get back another queryset which will have all the Posts of all my friends which I can display in the template. class Friend(models.Model): users = models.ManyToManyField(User, blank=True) owner = models.ForeignKey(User, related_name='owner_friend', on_delete=models.CASCADE, null=True, blank=True) class Post(models.Model): creator = models.ForeignKey(User, on_delete=None, null=True) -
Invalid username/password error django rest framework custom user serializer
Custom User Model: class User(AbstractUser): ROLE_CHOICES = ( ('R', 'rider'), ('D', 'driver'), ) role = models.CharField(max_length=1, choices=ROLE_CHOICES) phone_number = models.CharField(max_length=10) cab = models.OneToOneField('Cab', on_delete=models.CASCADE, blank=True, null=True) Rider serializer: class RiderSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'phone_number', 'password') extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): username = validated_data.pop('username') password = validated_data.pop('password') instance = User(username, **validated_data) if password is not None: instance.set_password(password) instance.save() return instance Rider function based view method: @api_view(['GET', 'POST']) def rider_list(request): if request.method == 'GET': riders = User.objects.filter(role='R') serializer = RiderSerializer(riders, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = RiderSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(role='R') return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) rider endpoint: /riders/ I am able to create a user object but user authentication fails as password is getting stored as plain text in object. I have tried using User.objects.create_user(username, password=password, **validated_data) to set password as hashed value but it does not work I have also tried using make_password method to set hashed password but nothing seems to work. Please tell me what am i missing. How do i store the hashed password in password field of custom user object. -
module 'guestbook.views' has no attribute 'index'
i make a startapp "guestbook" inside my django project. here is the file list(guestbook) __init__.py admin.py apps.py migrations models.py template tests.py urls.py views.py guestbook/template guestbook guestbook/template/guestbook index.html i want to get the index render but i am facing error which is File "C:\Users\_monster\Desktop\skill\django_frontend\backend\f_django\guestbook\urls.py", line 7, in <module> path('', views.index, name='index') AttributeError: module 'guestbook.views' has no attribute 'index' here is my file setting main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ # main url, folder url path('admin/', admin.site.urls), path('hello/', include('hello.urls')), path('guestbook/', include('guestbook.urls')) ] guestbook/urls.py from django.urls import path # import everything from views from . import views urlpatterns = [ path('', views.index, name='index') ] guestbook/views.py from django.shortcuts import render # Create your views here. def index(request): return render(request, 'guestbook/index.html') so what is problem here ? the index.html are inside the folder -
Python simple API application without Djangp REST framework
I need to make a simple API using Python. There are many tutorials to make a REST API using Django REST framework, but I don't need REST service, I just need to be able to process POST requests. How can I do that? I'm new to Python. Thank you! -
How to convert csv into mock when csv file is specified as argument in unit test of Django command
There is a django command that gives the path of the csv file as an argument as follows. class Command(NoticeCommand): def add_arguments(self, parser): parser.add_argument( '--file', dest="file", type=str, required=True ) def handle(self, *args, **options): with open(options['file'], 'r') as f: reader = csv.reader(f) next(reader) for row in reader: ... I am thinking to make this csv file mock when doing unit test. However, I do not know which part and how to make mock. Also, the argument is required = True. How can I call UnitTest when csv is mocked? from mock import patch from django.core.management import call_command class ImportCsvTest(TestCase): @patch("common.management.commands.import_csv.????") def test_import_csv(self): call_command("import_lyric_artists", file=?????) -
Object of type 'bytes' is not JSON serializable
Using Django, I’d like to sync the files in the database with git repositories on my GitLab instance via python-gitlab. Here you can find my Python code: http://ix.io/1fII/python. I’m getting the following traceback: Traceback (most recent call last): File "/Users/keno/memeweb/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/keno/memeweb/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/Users/keno/memeweb/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/Users/keno/memeweb/memetree/views.py", line 42, in post Sync.sync() File "/Users/keno/memeweb/memetree/sync.py", line 54, in sync commit = project.commits.create(data) File "/Users/keno/memeweb/lib/python3.6/site-packages/gitlab/exceptions.py", line 242, in wrapped_f return f(*args, **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/gitlab/mixins.py", line 204, in create **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/gitlab/__init__.py", line 589, in http_post post_data=post_data, files=files, **kwargs) File "/Users/keno/memeweb/lib/python3.6/site-packages/gitlab/__init__.py", line 463, in http_request prepped = self.session.prepare_request(req) File "/Users/keno/memeweb/lib/python3.6/site-packages/requests/sessions.py", line 441, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "/Users/keno/memeweb/lib/python3.6/site-packages/requests/models.py", line 312, in prepare self.prepare_body(data, files, json) File "/Users/keno/memeweb/lib/python3.6/site-packages/requests/models.py", line 462, in prepare_body body = complexjson.dumps(json) File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", … -
kibana iframe: get user generated filters
I'm trying to get user's generated filters on kibana. I use the embedded iframe (shortened URL) of kibana dashboard. Web app is build using django web framework. Specifically I want to get filters created by the user: iframe HTML: <iframe id="kibana_iframe" src="http://localhost:5601/goto/688d0d4e4bdbf245c0f9b8e94e688f7c?embed=true" scrolling="yes" width="100%" height="1500" frameborder="0"></iframe> For this purpose I tried to get the innerHTML but I could not overcome this issue var iframe = document.getElementById('kibana_iframe'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; SecurityError: Permission denied to access property "document" on cross-origin object kibana and django are in the same host (localhost), I used these instruction but still getting the same security error. I know, this is not a proper approach but I have to make it work for internal use. Have you any idea how to bypass this error or any other proper way to get user generated filters from embeded kibana iframe? Thanks in advance! -
Django print models constant array in template
I have a constant array in my model: DELIVERY_TYPES = ( ('self', u'one'), ('paid', u'two'), ('free', u'3') ) in my django template I'am trying to render it: <span style="font-size: 20px;">{{ DELIVERY_TYPES[shop.delivery_type] }}</span> I get an error, how to print these values right? -
Cannot publish to azure
I have developed a Django app using visual studio community edition. I am unable to deploy it to Azure I am getting a temp file containing following text. 02-07-2018 15:07:22 System.AggregateException: One or more errors occurred. ---> System.Exception: Build failed. Check the Output window for more details. --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at Microsoft.VisualStudio.Web.Publish.PublishService.VsWebProjectPublish.<>c__DisplayClass41_0.b__2() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.VisualStudio.ApplicationCapabilities.Publish.ViewModel.ProfileSelectorViewModel.d__116.MoveNext() ---> (Inner Exception #0) System.Exception: Build failed. Check the Output window for more details.<--- =================== Thanks -
Page not found error happens-Can <str:id> be used?
Page not found error happens-Can be used? I wrote in urls.py from django.conf.urls import url from app import views urlpatterns = [ url('^data/<str:id>', views.data, name='data'), ] in views.py def data(id): ・ ・ ・ return None For example, when I access http://127.0.0.1:8000/data/AD04958 , Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/data/AD04958 error happens. I think I can write this url http://127.0.0.1:8000/data/AD04958 into '^data/' in urls.py,so I really cannot understand why this error happens. id is not save in Database,does it cause this error? What is wrong in my codes?How should I fix this? -
Access the objects of foreign key in Modelform in Django
How to access the objects of foreign key in Modelform. models.py class World(models.Model): country = models.CharField(max_length=200) Language = models.CharField(max_length=200) Population = models.IntegerField() class Traveller(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) Travelling_to = models.ForeignKey(World,on_delete=models.CASCADE) forms.py class countries_form(forms.ModelForm): class Meta(): model = Traveller fields = '__all__' view.py def index(request): form = countries_form() if request.method == 'POST': form = countries_form(request.POST) if form.is_valid(): saved_form = form.save(commit=True) return render(request,'receipt.html',{'upform':saved_form}) else: print("form is not valid") return render(request,'index.html',{'form':form}) index.html <label for="name">name : </label> {{ form.name }}<br> <label for="contact">Address : </label> {{ form.address }}<br> <label for="Travelling_to">Travelling_to : </label> {{ form.Travelling_to }}<br> # this will be a select tag,as its a foreign key # how can I access the language and Population of the selected country in form I am not able to access the language and population of selected country in this Modelform -
Moving my current Django app to another Digital Ocean droplet, with new custom user model
hope you're doing well. I have a web app that is deployed for about 6 months, it's like a data as service business, using stripe to handle billing. so I decided to change a lot of my back-end and front-end, 1- back-end : start using stripe subscriptions instead of handling reoccurring payments, make API, custom user model, adding API endpoints for business data. 2- front-end : started to use Vue JS (cdn) in some parts of my templates to make things more interactive. I even started a new django project from scratch, copied some unchanged parts from old project and started coding the new logic. there are 2 things concern me, 1- if I backup the old user table, would it be easy to import it to the new DB especially that I'm using a custom user model (deleted the username field and added some fields), my concern is how to make sure that passwords are not lost/changed. (is that something related to Django project SECRET_KEY) ? the other models can be moved easily using fixtures or by dumping and loading Json files with some logic to meet the new models structure. 2- is it easy to un-link the current … -
Adding the app name to a ContentType field in the Django admin change form
I have a Django admin site for email templates. These email templates have a ContentType ForeignKey field. This field is displayed in the admin change view. The Model: (Non relevant code not displayed) class EmailTemplate(models.Model): name = models.CharField(verbose_name=_('Name'), max_length=200, unique=True) content_type = models.ForeignKey(ContentType, verbose_name=_('Content Type')) The admin.py: (Non relevant code not displayed) class EmailTemplateAdmin(admin.ModelAdmin): form = EmailTemplateForm list_display = ('name',) fieldsets = ( (None, { 'classes': ('monospace',), 'fields': ('name','content_type',) }), ) I want to customize the field "content_type" now. Right now it just displays the ContentType, I want to add the corresponding "app_label" to it (We have many apps and sadly, some models exist in multiple apps (So the name is shown twice with no way of distinguishing it). This is quite a legacy codebase and renaming all the models to be unique between apps is not possible. In short: How do I change my content_types field to display like this: "[Content_type][Content_type.app_label] -
Django dev server running twice only on a specific machine
I experiencing a weird issue with Django dev server. I have my Django 1.11 running on python 3.5 on two different machines. The configuration on these two machines is supposed to be exactly the same (pyenv, virtualenv). When I run python manage runserveron machine1 everything works as expected but if I run the same command on machine2 then I can see from the console log that everything is running twice. At first I thought it was a PyCharm problem (I share the runConfigurations) but the same thing happens using plain terminal command. I've tried the well known reload problem, so I passed the param --noreload to runserver but nothing changed. I've tried to check if it was the missing favicon.ico problem: I've correctly created a favicon and added to my base html template but the problem remained. I've checked if any static files was missing but from my browser network panel I could not see any 404 when loading my templates. I see that this question has been asked multiple times but none of the answer seems to be related to my specific problem. What could possible cause this problem? -
django how to declare and increment a custom counter?
I need to increment the counter only after a true expression like: {% for cats in categories %} //reset counter {% for item in items %} {% if some_condition %} //increment counter {% endif %} {% endfor %} {% endfor %} how to make it with {{ forloop.counter }} as far as I know it is increasing in every step of the loop, how to make the increment conditional, just at the point where I need it?