Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin site not loading CSS
Not sure what is going on, but my admin page on my Django site isn't loading any CSS. Not sure if it has to do with python manage.py collectstatic but ever since I served my static files using this, my admin page doesn't load with CSS and instead, it's plain HTML. This same issue is happening with a few projects of mine when using collectstatic. Any ideas? They'd be appreciated. Since I don't know what the issue is or where to start, I'm not sure what code to provide. If you want to see anything, let me know. -
Django runs transaction commit too late
def some_view(request): with transaction.atomic(): data = do_some_stuff(request) data2 = do_some_stuff2(request) async_task.delay(data, data2) return Response({'data': data, 'data2': data2}) Expectation: when with block is completed all database modifications are commited to database. Reality: while response is being prepared to be sent to browser (serialization) async task already started execution. Async task expects that all modification are already completed, but it is not. Only when browser receives response actual commit to database is done. I know about transaction.on_commit(func) hook, but question is about why once with transaction.atomic() is completed I can not be sure that data is actually updated in database? Take a note ATOMIC_REQUESTS=False It's about Django 1.11.20 and postgresql 10. I do not know if it works the same way with Django 2+ -
How to use ForeignKey or OneToOneField with Wagtail InlinePanel?
I have two models, Address and Subscription. I would like the Subscription model to have a ForeignKey or OneToOne relationship with an Address. class Address(models.Model): street_address = models.CharField( max_length=255, blank=True, default="", ) ... class Subscription(models.Model): subscriber_address = models.OneToOneField( Address, on_delete=models.SET_NULL, null=True, related_name='related_entity' ) panels = [ InlinePanel("subscriber_address"), ] I would also like for users to be able to edit the address fields when editing a Subscription instance via the Wagtail UI. However, when trying to create a Subscription with the above configuration, I get the following error: 'ForwardOneToOneDescriptor' object has no attribute 'rel' What is the proper way to render a ForeignKey or OneToOne relationship via the Wagtail InlinePanel? -
How to display base64 image in django admin?
I have legacy software that stores the institutions logo through django's BinaryField, I need to show this image on the django admin record editing page this my admin: class InstituicaoAdmin(admin.ModelAdmin): list_display = ['ds_instituicao', 'sigla'] search_fields = ['ds_instituicao'] formfield_overrides = { BinaryField: {'widget': BinaryFileInput()}, } readonly_fields = ["imagem_logo",] def imagem_logo(self, obj): base64Encoded = base64.b64encode(obj.logo) return mark_safe('<img src="data:;base64,base64Encoded">') This not work -
DJANGO PYTHON - SHOW IN A HTML TAMPLATE THE RESULT OF A SQL QUERY USING DJANGO
I want to show in a template, a query result using django and mssql. Query works fine: cursor.execute("SELECT DISP FROM INDTIMEN WHERE PAIS_SERV_PRODID = 'VEN_UY_POS' AND AΓO = 2019 AND MES = 10 AND INDIS != 0") lista=cursor.fetchall() the result of the query in de mssql is = 0.773 but when i write the variable lista in the html tamplate, the browser show [(Decimal('0.773'), )] how can I do to show only the result 0.773 -
Can values_list() return the name instead of id?
I have two models like so: class Budget(models.Model): name = models.CharField(max_length=255) class Transaction(models.Model): type = models.CharField( max_length=3, choices=[('inc', 'Income'), ('exp', 'Expense')], default='inc' ) amount = models.DecimalField(max_digits=12, decimal_places=2) description = models.TextField() added_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) date = models.DateTimeField() objects = TransactionQuerySet.as_manager() budget = models.ForeignKey(Budget, on_delete=models.CASCADE) ...and I have a custom Manager method on my TransactionQuerySet: class TransactionQuerySet(models.QuerySet): def categorize_budgets(self): return self.model.objects.values_list('budget').annotate(total=Sum('amount')) I want to categorize expenses by budget and sum them up, and when I do: >>> Transaction.objects.filter(added_by=user, type='exp').categorize_budgets() <TransactionQuerySet [(1, Decimal('4'))]> what it returns is, I suppose budget id). I want it to return budget name instead, is that possible? I have a workaround like this, but I'm wondering if the DB can do all the work in one go: def get_expenses(self): expenses = Transaction.objects.filter( added_by=self.request.user, type='exp' ).categorize_budgets() mappings = { Budget.objects.get(id=k).name: v for k, v in expenses } -
How Realize pure python app using frameworks?
I have pure python app(parser) using sqlite but without frameworks. I need realize this app with any of python frameworks and DB. As far as i know for example django use ORM, but i use sql queryes in my app. How can i implement or combine this? -
PyODBC Invalid Connection String Attribute (0)
I am using PyODBC on a Django server in order to connect to a Microsoft SQL Server that is on the same machine. Below is the current connection string I have: conn = pyodbc.connect("DRIVER={SQL Server};server=DESKTOP-VKNKLNT/MUSICCLOUD,1433;database=Customer;uid=--username--;pwd=--password--") But I get the error: django.db.utils.InterfaceError: ('28000', '[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user \'sa\'. (18456) (SQLDriverConnect); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "DESKTOP-VKNKLNT\MUSICCLOUD" requested by the login. The login failed. (4060); [28000] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user \'sa\'. (18456); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "DESKTOP-VKNKLNT\MUSICCLOUD" requested by the login. The login failed. (4060); [28000] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0)') I have checked to make sure my username, password, and database are right and I've tried just about every other solution I've seen. Any suggestions and help is appreciated. Thanks in advance. -
Why am I getting a TypeError while trying to access HttpRequest.POST['choice'] value? How do I solve this error?
I have been taking a django tutorial recently and I'm stuck. After submitting the form using post method, I tried getting the selected_choice model object by using the .get() method but I am getting a TypeError: cannot unpack non-iterable ModelBase object error. Here are the views from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from .models import Question, Choice def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(Question, pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', {'question': question, 'error_message': 'Please select a choice and vote'}) else: selected_choice.no_of_votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:result', args=(question.id,))) def result(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/result.html', {'question': question}) Here are the templates detail.html {% block content_main %} <h2>{{question.question_text}}</h2> {% if error_message %} <strong>{{error_message}}</strong><br><br> {% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" style="margin-left: 20px;"> <label for="choice{{forloop.counter}}" style="font-size: 20px;">{{choice.choice_text}}</label><br><br> {% endfor %} <br> <input type="submit" value="vote" style="margin-left: 30px; font-size: 20px;"> </form> {% endblock %} result.html {% block content_main %} <h2>{{question.question_text}}</h2> {% for choice in question.choice_set.all %} <ul> <li>{{choice.choice_text}} -- {{choice.no_of_votes}} vote{{choice.no_of_votes|plural}}</li> </ul> {% endfor %} <a href="{% url 'polls:detail' question.id %}}">Vote again?</a> {% β¦ -
How to handle 'dict' object has no attribute 'META'?
I'm trying to create a JSON response in a django project; but something goes wrong! applications_list = [] for project in projects_list: application_information = { ``` some keys and values ``` } applications_list.append(application_information) context = {'applications': applications_list} return render(request, self.template_name, context) But I got this error: 'dict' object has no attribute 'META' Should be mentioned that keys and values of application_information are serialized. I also tried json.dumps() but didn't work. I wonder what have been missed? -
how can I manage errors in login built in django?
I have a doubt about my code. I am trying to redirect erros if account is disable , and invalid cred ,but my code is doing if its invalid doesn't do nothing , but I want to send json data like invalid credentials however it doesnt going to anywhere from my conditions Views.py class LoginView(View): def get(self, request): return render(request, 'login.html', { 'form': AuthenticationForm }) def post(self, request): form = AuthenticationForm(request, data=request.POST) if form.is_valid(): user = authenticate( request, username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password') ) if user is not None: if user.is_active: login(request, user) return redirect('/') # home page else: return HttpResponse("A") # account disabled else: return HttpResponse("invalid_creds") urls.py urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('profile/', views.ProfileView.as_view(), name='profile'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), ] settings #LOGIN_REDIRECT_URL = '/account/profile' LOGOUT_REDIRECT_URL = '/' html <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div> <div class="form-group"><input class="form-control" name="username" placeholder="Email" /></div> <div class="form-group"><input class="form-control" type="password" name="password" placeholder="Password" /></div> <div class="form-group"><button class="btn btn-primary btn-block" type="submit">Log In</button></div><a href="#" class="forgot">Forgot your email or password?</a></form> -
Simple Web API with no views or models in Django Rest Framework
What I need is simple: a piece of code that will receive a GET request, process some data, and then generate a response. I'm completely new to python web development, so I've decided to use DRF for this purpose because it seemed like the most robust solution, but every example I found online consisted of CRUDs with models and views, and I figure what I need is something more simple (since the front-end is already created). Could anyone provide an example on how to do this on DRF? (or even some other viable solution, having in mind that it needs to be robust enough to take on multiple requests at the same time in production) -
django model inheritance: How does model creation work with custom manager?
Recently I've faced an issue with django, model inheritance and how the creation of model instances works. Suppose I have the following (basic) setup: class InviteBaseManager(models.Manager): def create(self): new_code= # create some kind of unique code, not really relevant here. return super().create(code=new_code) class InviteBase(models.Model): code = models.CharField(max_length=10, blank=False, null=False, unique=True) creationDate = models.DateTimeField(default=timezone.now()) objects = InviteBaseManager() class PartyInviteManager(models.Manager): def create(name): # method 1 newInvite= InviteBase.objects.create() print(newInvite.code) # is definitly set, lets assume "ABCD" # as expexted, the "InviteBase" table has one row with code "ABCD" and # default creationDate newPartyInvite = super().create(partyName=name, invite=newInvite) print(newPartyInvite.invite.code) # is EMPTY, prints nothing # In fact, when looking at the db, there is still only *one* row in the table "InviteBase", # with an *empty* code field and a default creationDate field. #method 2 newPartyInvite = super().create(partyName=name) # creates the InviteBase instance implicitly, again, newPartyInvite.invite.code is empty. class PartyInvite(InviteBase): #Isn't blank=False and null=False unecessary? A child should probably not exist with no parent? invite = models.OneToOneField(InviteBase, parent_link=True, on_delete=models.CASCADE, null=False, blank=False) partyName = models.CharField(...) objects = PartyInviteManager() So the question is: How can I pass an already existing instance of the base class inside the create method of my PartyInviteManager? Even when using method 1, β¦ -
Input Form some time return 2 variables list Django
I have simple model with simple form of mail class ExtraMailData(models.Model): client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) group = models.CharField(max_length=50) mail = models.EmailField(null=True) class Meta: # make sure we can have uniqe phone number to each client unique_together = ('mail', 'group',) class AddClientMailtData(AjaxFormMixin, forms.ModelForm): template_name = 'client/mail_form.html' class Meta: model = ExtraMailData fields = ('mail',) widgets = { 'mail': forms.EmailInput(attrs={'class':'form-control', 'placeholder': 'Mail'}), } FormsetAddExtraMailData = inlineformset_factory(Client, ExtraMailData,form=AddClientMailtData, extra=1, fields=('mail',), can_delete=True) Sometimes I get back the value splited to 2 value list , the first contains my data and the second empty: 'extraMail-0-mail': ['a@a.com', ''] ans sometimes it's return properly. my current fix is ugly, I check before is_valid() if I have len('extraMail-0-mail') > 2 and if so I replace it's value by 'extraMail-0-mail'[0]. I wonder why is it happening and what can I do to properly fix this? -
I do not accept to put a size to the answer in the parameter size_page - Django Rest Framework
I'm trying to put the size of the answer and it doesn't work for me. the page_size of the StandardResultsSetPagination class is working. libraries I use: - Django REST framework JWT - Django REST Framework JSON API (no parameters) See: https://ibb.co/SK65BKx (with parameters) See: https://ibb.co/g6t04D0 settings.py See: https://ibb.co/sKSZYty pagination.py See: https://ibb.co/64x6cQT -
Passing django view dictionary and variables to a iframe template in a template
I have two pages. 1) create_form.html , rendered with create_form view 2) formatter.html , rendered with formatter view I added formatter view in create_form.html with iframe. <iframe src = "/formatter" width = "768" height = "500" frameBorder="0"> </iframe> I pass a dictionary to create_form while rendering create_form.html. I can reach this dictionary in create_form view. But i need to pass this dictionary also to the formatter.html which is in an iframe in create_form.html -
Django don't accept saas files but accept css files
Please Help me. When I running my app in cmd My website dont work css (which have saas and css) Failed to load resource: the server responded with a status of 404 (Not Found) Settinngs.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Head.html {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Poppins:100,200,300,400,500,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/animate.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.theme.default.min.css' %}"> <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'css/aos.css' %}"> <link rel="stylesheet" href="{% static 'css/ionicons.min.css' %}"> <link rel="stylesheet" href="{% static 'css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'css/icomoon.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> script.html {% load static %} <script src="j{% static 's/jquery.min.js' %}"></script> <script src="{% static 'js/jquery-migrate-3.0.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.easing.1.3.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/jquery.stellar.min.js' %}"></script> <script src="{% static 'js/owl.carousel.min.js' %}"></script> <script src="{% static 'js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'js/aos.js' %}"></script> <script src="{% static 'js/jquery.animateNumber.min.js' %}"></script> <script src="{% static 'js/scrollax.min.js' %}"></script> <script src="{% static β¦ -
Login with both username and password in django 2.2.5
How can we login with username or password in Django site and Django Admin pages? I tried by creating custom user model and making email field as username field but I can don't want to login with either username or email. I want to use any of both any time to login. -
Do not refresh (redirect) page after facebook login
I am using social_django library for facebook login. I am using the following function for the login process which is called on login button click. I've also set the redirect in settings.py pointing the the url namespace 'app'. The login works fine, except the fact that my app page gets refreshed and all the content in goes away. Is there an option to automatically close the facebook tab after login, and not refresh my app page? I tried to open fb login in another tab, but still I will be redirected to my app page in that same tab. function FBLogin(){ window.open('{% url "social:begin" "facebook" %}'); } in settings.py LOGIN_REDIRECT_URL = 'app' -
Heroku - Redis - Django: web-app on Heroku doesn't send email notifications
I am developing a web-app using Django and using Redis for the email notifications. Everything works fine on my local environment, but deployed web-app on Heroku doesn't send any email. The add-on I have on Herokyu is "Heroku Redis" and the library on django is "pip install django-redis-cache" As the Heroky Dev Center documentation says https://devcenter.heroku.com/articles/heroku-redis#connecting-in-django , I set my setting.py file as: import os CACHES = { "default": { "BACKEND": "redis_cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), } } Now, the logs on Heroku for [heroku-redis] are: 2019-11-13T17:53:39+00:00 app[heroku-redis]: source=REDIS addon=redis-globular-96736 sample#active-connections=1 sample#load-avg-1m=0.115 sample#load-avg-5m=0.11 sample#load-avg-15m=0.125 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664216kB sample#memory-free=11900700kB sample#memory-cached=806096kB sample#memory-redis=313912bytes sample#hit-rate=1 sample#evicted-keys=0 2019-11-13T17:53:39+00:00 app[heroku-redis]: source=REDIS addon=redis-globular-96736 sample#active-connections=1 sample#load-avg-1m=0.21 sample#load-avg-5m=0.14 sample#load-avg-15m=0.135 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664216kB sample#memory-free=11900676kB sample#memory-cached=806552kB sample#memory-redis=313912bytes sample#hit-rate=1 sample#evicted-keys=0 2019-11-13T17:56:43+00:00 app[heroku-redis]: source=REDIS addon=redis-globular-96736 sample#active-connections=1 sample#load-avg-1m=0.145 sample#load-avg-5m=0.135 sample#load-avg-15m=0.135 sample#read-iops=0 sample#write-iops=0.0084034 sample#memory-total=15664216kB sample#memory-free=11899756kB sample#memory-cached=806472kB sample#memory-redis=313912bytes sample#hit-rate=1 sample#evicted-keys=0 2019-11-13T17:56:43+00:00 app[heroku-redis]: source=REDIS addon=redis-globular-96736 sample#active-connections=1 sample#load-avg-1m=0.22 sample#load-avg-5m=0.16 sample#load-avg-15m=0.145 sample#read-iops=0 sample#write-iops=0.19672 sample#memory-total=15664216kB sample#memory-free=11895764kB sample#memory-cached=806656kB sample#memory-redis=313912bytes sample#hit-rate=1 sample#evicted-keys=0 2019-11-13T18:00:05+00:00 app[heroku-redis]: source=REDIS addon=redis-globular-96736 sample#active-connections=1 sample#load-avg-1m=0.355 sample#load-avg-5m=0.22 sample#load-avg-15m=0.165 sample#read-iops=0 sample#write-iops=0.125 sample#memory-total=15664216kB sample#memory-free=11892588kB sample#memory-cached=806708kB sample#memory-redis=313912bytes sample#hit-rate=1 sample#evicted-keys=0 2019-11-13T18:00:05+00:00 app[heroku-redis]: source=REDIS addon=redis-globular-96736 sample#active-connections=1 sample#load-avg-1m=0.42 sample#load-avg-5m=0.26 sample#load-avg-15m=0.18 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664216kB sample#memory-free=11894496kB sample#memory-cached=806712kB sample#memory-redis=313912bytes sample#hit-rate=1 sample#evicted-keys=0 looks like every 3min is doing something but I cannot understand what it is saying or showing. On my local β¦ -
Django 2.2 img's not loading
I'm actually new to django and I found a problem when loading my images, I did the settings like the docs said and it saves my images to the right folder. Just the loading part does not work as I want it to. # the settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # the Model class Legend(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=300) creator = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) published = models.DateTimeField(null=True, blank=True) available = models.BooleanField(default=False) image = models.ImageField(upload_to='gallery', blank=True, null=True) # the template where i use the img field {% for instance in object_list %} <img style="width: 245px; height: 247px;" src="{{ instance.image.url }}" alt="legend image""> {% endfor %} the upload is working as expected. Saves all images to the media folder (which is on the applevel) so: media/gallery/name.jpg. running the server doesnt show the image but the source seems fine: http://127.0.0.1:8000/media/gallery/gto.jpg There seems to be a problem with serving files locally when debugging, but all i could find were for older django versions. Iam using django --version 2.2. I appreciaty any help -
Issue adding an app to django admin and displaying the models
I am new on django and I have a very basic project with the following structure [django_test βββ django_test β βββ settings.py β βββ templates β β βββ base.html β β βββ current_age.html β βββ urls.py β βββ views.py βββ my_app β βββ admin.py β βββ apps.py β βββ migrations β βββ models.py β βββ tests.py β βββ views.py βββ manage.py βββ requirements.txt][1] I have ran my project and I got something as the initial django admin screen But as you can see I have inside the project an app called my_app and inside the my_app's path I have a models file with some models as Model1, Model2, Model3 in other django projects I have seen than in other in the dashboard you have access to your models for to added, deleted, consulted and edited from there. Which addtional step am I missing ? -
django migration is not creating all the fields from defined model class into db
Hi i am trying to generate migration but all fields are not getting created into the db. Below is my code. from django.db import models class News(models.Model): author = models.CharField(max_length = 100), content = models.CharField(max_length= 100), description = models.TextField(default= "") def __str__(self): return self.author class Meta: db_table = "news" class SportNews(models.Model): author = models.CharField(max_length = 100), content = models.CharField(max_length = 100), description = models.TextField(default = "") def __str__(self): return self.author class Meta: db_table = "sports_news" -
How to serialize file for creating models which connected by foreignkey. Django Rest Framework
I have several files "ABC" and each has several parts with different data. Also, I have a parser that parse this file to dict in format: {part1: {"name":"test name", "dataKey1":"i have a model for this key", "dataKey2":{"a":123, "b":222}}, part2: {"name":"test name 2", "dataKey1":"not empty string", "dataKey2":{"a":080, "b":999}} } I have a model for some keys in nested dicts. I have a model for some keys in the files. I have a model for file. And I have a model for keeping list of all files. How serializer might be structured for handling many files(which I get with request) each of which will be parsed with my function and serialized to create models not only for each file but for each required nested dict??? -
How to just display one field from the form in Django
I want to display just one field from my form that I have created but I am getting 'Could not parse the remainder:' error Here is my forms.py file from django import forms from .models import * class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('prod_name', 'company', 'quantity', 'price', 'units', 'prod_type') Here is my html file {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST"> <br> {% csrf_token %} {% for field in form %} {% if field.name=='units' %} <div class ="form-form row"> <label for="id_{{field.name}}" class="col-2 col-form-label">{{field.label}}</label> <div class ="col-10"> {{field}} </div> </div> {% endif %} {% endfor %} <button type="submit" class="btn btn-primary" name="button">Update Sales</button> </form> </div> {% endblock %} I just want to display units in my webpage for this module that I am creating