Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import statements not being recognized in Django [closed]
I am using Django = 2.1 Python = 3.6 Pycharm Community Edition Import statements in one of my apps are not being recognized but the same import statements in other apps are working properly. Image of apps import staements not being recognized Image of import statements being recognized in other app of same project I have tried deleting .idea and I have also made sure that I have init.py in my apps and I have also deleted and reinstalled pycharm. -
Django monthly sums for a specific filter
I have the following models structure: Conto | Sottocategoria | Price | Quantity | Total* | Date of purchase Conto 1 | Product_a | 10 | 1 | 10 | 1/01/2020 Conto 1 | Product_a | 15 | 1 | 15 | 1/01/2020 Conto 2 | Product_b | 10 | 2 | 20 | 1/02/2020 I want to have the monthly sum for each "conto". Something like this: Conto | Gen | Feb | Mar | Apr | May | Jun | .... Conto 1 | 25 | 0 | 0 | 0 | 0 | 0 | .... Conto 2 | 0 | 20 | 0 | 0 | 0 | 0 | .... This one my models.py: class Tipologia(models.Model): nome= models.CharField('Categoria', max_length=30) class Sottocategoria(models.Model): tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE) name = models.CharField() class Conto(models.Model): nome=models.CharField() class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE, null=True) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) quantita=models.DecimalField() prezzo=models.DecimalField() data=models.DateField(default="GG/MM/YYYY") -
How to implement alive and readyness with django-health-check
We are using kuberntes and need two different endpoints one for health and one for alive. For some reasons we chosse https://github.com/KristianOellegaard/django-health-check. Its easy to implement a second view for alive which is loaded, but - this view is empty - I do not understand how I could configure the plugings which should be used for the view. class AliveCheck(MainView): # template_name = 'myapp/health_check_dashboard.html' # customize the used templates def __init__(self): self.plugins.clear() self.plugins.append(DiskUsage()) def get(self, request, *args, **kwargs): errors = super(MainView, self).run_check() return super(MainView, self).get(request, args, kwargs) Any ideas? -
Django - Correct Use of Mixins with CBVs
I just started to shift from function-based views to class-based views, as I realize more and more the benefits of the latter, especially regarding the modularity that you can achieve via mixins. However, as CBVs and Mixins are still quite new to me, I wanted to check, if I understand the basic concepts correctly: Example: class ReportingMixin1(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reportingmixin1_context'] = 'test1' return context class ReportingMixin2(object): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reportingmixin2_context'] = 'test2' return context class MyTemplateView(ReportingMixin1, ReportingMixin2, TemplateView): template_name = 'test4.html' My questions are the following: With function based views I would do context = {'reportingmixin1': 'test1} but I see that with class based views this is always done via context['reportingmixin1'] = 'test1 . Why is this the case? I assume one reason is that when combining multiple mixins in a TemplateView (as in the code in my example) but with context = {'reportingmixin1': 'test1} and context = {'reportingmixin2': 'test2} I would initiate or redefine the context dictionary in each mixin, so you would have only access to the context keys I defined in my mixin that is called last? What is context = super().get_context_data(**kwargs) doing exactly? I read that it is "calling … -
How to solve "Blocked:CSP" error Passit (Django)
I'm not sure if this is the right stack exchange but i think this one fits my question the most. I was searching for an Free Opensource web based password manager to manage passwords for me and our team and found Passit (passit.io). I wanted to test this tool so installed an ubuntu 18 server with docker, postgreSQL and nginx and followed the installation instructions to run passit docker: https://passit.io/install/ I configured Passit via the web based installation wizard and now i can see the passit web interface. When i try to create an account the application does not respond. When i check the Google dev-tools i see that the http://passit.axx/account/register request gets an blocked:CSP response. During an attempt to solve this issue, i found that i can "enable" the Django admin interface by logging in into the container and set the ENABLE_DJANGO_ADMIN setting in the passit>settings.py to True. I tried to login here with just some random credentials and got this error: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being … -
Django - how to change email field error measge
I have a django email field when email is entered wrongly it shows custom error message please include an @ in email address how can i change the error message class confirmmail(forms.Form): emailid = forms.EmailField(max_length=100,widget=forms.TextInput(attrs={'class': 'form-control user_name_textbox_style', 'placeholder':'Email Address', 'type':'email','required':'true','ng-model': 'email_from_forgotpassword'})) -
trying to createsuperuser on heroku but it throws me a typeError
i tried this command to createsuperuser using this command "heroku run python manage.py createsuperuser" but it always throws me this error Running python manage.py createsuperuser on ⬢ django-blog-web-app... up, run.4727 (Free)enter code here Username (leave blank to use 'u10279'): ###################### Email address: ####################### Password: Password (again): 'Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/base.py", line 793, in save_base post_save.send( File "/app/.heroku/python/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 173, in send return [ File "/app/.heroku/python/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 174, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/Users/signals.py", line 10, in create_profile Profile.objects.create(user=instance) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/models/query.py", line 433, in create obj.save(force_insert=True, using=self.db) TypeError: save() got … -
TemplateDoesNotExist error due to a comment
I'm in the process of making a website with Django and have yet to create order_snippet.html. When I add {% include "order_snippet.html" %} I expect a TemplateDoesNotExist error, but I put this in the payment.html and commented it out like this: <!-- {% include "order_snippet.html" %} --> yet I still have a TemplateDoesNotExist error. I thought comments weren't read by html? How come this raises an error? -
using python & django for new huge human resources system... which is better react js or angular?
using python & django for new huge human resources system... which is better react js or angular? we are developing new human resources system with huge data... we will use python as a back end... which is better to use as a front end reactjs or angular? we need fast & stable system... and which is better to serve single page request? class HelloMessage extends React.Component { render() { return ( <div> Hello {this.props.name} </div> ); } } ReactDOM.render( <HelloMessage name="Taylor" />, document.getElementById('hello-example') ); -
my pipenv doesnt create a pipfile and pipfile.lock in any of my projects folders anymore
It used to automatically create these files in the folder I was working in, in the command line. If I were to say install django... C:\Users\Admin\Desktop\Djangoproj>pipenv install django Installing django… Adding django to Pipfile's [packages]… Installation Succeeded Installing dependencies from Pipfile.lock (536933)… ================================ 9/9 - 00:00:02 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. This is what I get. I have an empty folder. I dont get the pipfile or pipfile.lock like I am supposed to. Has anyone encountered this before? Is there a solution to this? I have already uninstalled pipenv and reinstalled the package a few times already. Same thing goes for installing requests package. C:\Users\Admin\Desktop\Djangoproj>pipenv install requests Installing requests… Adding requests to Pipfile's [packages]… Installation Succeeded Installing dependencies from Pipfile.lock (536933)… ================================ 9/9 - 00:00:02 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. C:\Users\Admin\Desktop\Djangoproj>ls 'ls' is not recognized as an internal or external command, operable program or batch file. C:\Users\Admin\Desktop\Djangoproj> -
how to make icons <i class="fas fa-minus mr-2"></i> display in template
I am trying to add some icons to my project template. I think i am putting them in the right place but they are not displaying when i look at the template. I have even tried placing the icons in other places but it still doesn't display. here is the place where the icons are on the template <td> <i class="fas fa-minus mr-2"></i> {{ equipment_order_item.quantity }} <i class="fas fa-plus ml-2"></i> </td> -
Web Development Learning Guidance [closed]
Can anyone acqauint me with basic Web Development if I'm a complete beginner? And guide me as to how to learn it? I know C++ and Python but want to start to learn web dev. What courses do you suggest? (Prefarably Free) Please endow me with all the knowledge you have! -
How to apply ManyToManyField to non primary key field?
I have a model A which has name and server_permission attributes. I would like to use both of these fields in my model B, but so far with no luck. Could you please help me? class A(models.Model): name = models.CharField(primary_key=True, max_length=50, unique=True) server_permission = ArrayField(models.CharField(max_length=10, blank=True),size=8) class B(models.Model): zuya_server = models.ForeignKey(A, on_delete=models.CASCADE, default='None',related_name='zuya_server') account_permission = models.ManyToManyField(A,db_column="server_permission",related_name='account_permission') -
Displaying foreign key values
My models.py looks like that: class Order(models.Model): items = models.ManyToManyField(OrderItem) class OrderItem(models.Model): (item in the cart) item = models.ForeignKey(Item, on_delete=models.CASCADE) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand = models.ManyToManyField(Brand) size = models.ManyToManyField(Size, blank=True) class Accessory(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand_accessory = models.ManyToManyField(BrandAccessory) So currently the field item in my OrderItem model displays the title and quantity of the item in Item model: def __str__(self): return f"{self.quantity} of {self.item.title}" Item is connected with OneToOneField with Bike and Accessory. Is it possible to display the brand and size of the Bike if its added to OrderItem and brand_accessory if Accessory is added to the OrderItem? It would look like {quantity} {item.title} (if bike)> {bike.brand} {bike.size} (if accessory)> {accessory.brand_accessory} -
How to fix trouble with urls better django
I have a section residential interiors on the site, so the typical url looks like this https://caparolcenterspb.ru/decision/livingrooms/kitchen/provans/ (room and style) However different rooms may have the same styles and when searching for styles in views.py it may output several styles and an error views.py selected_room = Room.objects.get(slug=rmslg) style = Style.objects.get(slug=stslg) When you try to replace slug with different styles depending on the room(for example, provans_kitchen), an error occurs in the template(just put provans by default will not work) residentialInteriors.html {% for room in all_rooms %} <li class="menu__item menu__item_interiors"><a href="{% url 'decision:style' rmslg=room.slug stslg='provans' %}">{{ room.name }}</a></li> {% endfor %} I have 2 solution ideas(preferably 2): either change stslg in template by default to 'provans_' + str(room. slug), but this line does not work(especially not the fact that provans will be everywhere) either search for style in views.py not only for stslg, but also for rmslg, but for this in the style model, you need to create a room field inherited from the room model, which also does not work for me, since Room is declared further than Style models.py class Style(models.Model): name = models.CharField(max_length=30) full_name = models.CharField(max_length=50) slug = models.SlugField() img = models.ImageField(upload_to='img/') walls = models.TextField() floor = models.TextField() roof … -
Exception Value: Invalid HTTP_HOST header: 'products_web:8001'. The domain name provided is not valid according to RFC 1034/1035
Here docker creates containers :- products, orders, email, nginx and postgres. enter image description here I have to get product details from orders service, for that i used requests pipe link response = requests.get("http://products_web:8001/products/fetch/?prod_id=%s" % product).json() when i execute, getting response in html format defining error as Exception Value: Invalid HTTP_HOST header: 'products_web:8001'. The domain name provided is not valid according to RFC 1034/1035. following is the docker-compose.yaml version: '2' services: products_web: build: ./products command: bash -c "python3 ./products/manage.py makemigrations && python3 ./products/manage.py migrate && python3 ./products/manage.py runserver 0.0.0.0:8001" volumes: - .:/code ports: - "8001:8001" restart: always depends_on: - datab links: - datab emails_web: build: ./emails command: bash -c "python3 ./emails/manage.py makemigrations && python3 ./emails/manage.py migrate && python3 ./emails/manage.py runserver 0.0.0.0:8002" volumes: - .:/code ports: - "8002:8002" restart: always depends_on: - datab links: - datab orders_web: build: ./orders command: bash -c "python3 ./orders/manage.py makemigrations && python3 ./orders/manage.py migrate && python3 ./orders/manage.py runserver 0.0.0.0:8003" volumes: - .:/code ports: - "8003:8003" restart: always depends_on: - datab links: - datab stdin_open: true tty: true datab: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres nginx: image: nginx:latest build: ./web ports: - "8084:80" links: - products_web - orders_web - emails_web depends_on: - products_web - … -
Django. SQLite. How to improve query speed/code and sorting speed within a list
I wrote a piece of a very ineffective, but working code, which is running approx. 24 hours to complete the task. I have a list choices = ["qwert", ... "ABCDE", ...], length of the list is 2...1000. I am making changes in the SQLite table as follows: first bad code: def update_records_in_bigtable(uid_br_next, choices): for k in choices: q = BigTable.objects.all().filter(Q(field1__exact=k) | Q(field1__exac2=k) | Q(field3__exact=k) & Q(field3=0) ).update(uid_nr=uid_nr_next) second bad code: def add_records_to_crossreftable(choices, obj): for k in choices: try: x = CrossRefTable.objects.create(field1=k, uid_nr_foreign=obj) except: x = DuplicatesTable.objects.create(field1=k) third bad code: def get_next_list(k): choices=list(BigTable.objects.all().filter(Q(field1__exact=k) | Q(field2__exact=k) ).values_list('field1', 'field2', 'field3', ) ) choice=[] for ch in choices: ch=set(ch) # remove same members if "" in ch: ch.remove("") # remove empty members if "ABC" in ch: ch.remove("ABC") # remove special member choice=choice + list(ch) choice=set(choice) return list(choice) Please help to improve. Thank you -
How to access and set Environment Variables for Django in production (Nginx and Gunicorn)
I am trying to set Environment Variables for a Nginx And Gunicorn Served Django Project on Ubuntu. The variables are set for the Ubuntu user and i am able to see the value using printenv VAR_EMAIL. But when i use them django settings it is not working , using them as os.environ['VAR_EMAIL'],This doesn't get the value of the variable in production and server doesn't work. However this works on Development side. Please provide me some guidance on how to accomplish this. -
how to delete duplicate entries by same user in django?
actually after submitting a form if the page is reloaded again the form is again getting submitted . So i want to delete duplicate entries from my form database. Help will be appriciated . Thanks in advance . Keep coding ,Stay sweet ... -
Django test TransactionTestCase execute before sql request is done
I'm running a test to check if my bulk inserts work correctly. The process_products_data method formats the input data, create some sql requests as a string then connects to the db and execute them. When I run the test, it fails and succeed randomly. I displayed the data stored in db in the teardown method and I could observe that when the test fails, the db is not filled correctly, like if the process_products_data method didn't trigger or is in the middle of it's job. Any idea how to force the test to wait for the process_products_data method to be over? class TestCaseCreation(TransactionTestCase): fixtures = ['test_1'] products = [ { 'internal_code': '403273', '_type': 'dict', 'description': 'Abc', 'brand': 'my brand', 'creation_date': 1587543189737.0, 'name': 'my name' } ] maxDiff = None def setUp(self): shop = Shop.objects.get(pk=1) process_products_data(self.products, shop) def test_creation(self): self.assertEqual(...) self.assertEqual(...) -
TypeError at /recomm/ __init__() got an unexpected keyword argument 'movie'
I got an error while getting the movies from the function it shows mistakes movies got an unexpected keyword argument movie File "E:\FinalYearProject\movierecommendationsystem\myapps\views.py" in recomm 106. return HttpResponse('recommend.html', movie=movie, r=r, t='s') Exception Type: TypeError at /recomm/ Exception Value: __init__() got an unexpected keyword argument 'movie' Here I got error while getting the recommending movie def recomm(request): if request.method == 'GET': movie = request.GET['movie'] r = recommendation('movie') movie = movie.upper() if type(r) == type('string'): return HttpResponse('recommend.html', movie=movie, r=r, t='s') else: return HttpResponse('recommend.html', movie=movie, r=r, t='l') my form for getting movies <form action="{% url 'recomm' %}" method="GET"> -
Implement SSO on a Django App running in iAPC
I deployed my first Django app on the iAPC and so far it's running fine. Now I'm trying to implement SSO for it. I already created a Corproot Identity v2 Service instance and linked it to my app. So I see that the environment variable VCAP_SERVICES containing all needed credentials is available. My problem is how to integrate this information in Django. If I look at the provided Java example here I understand that I have to configure an OAuth2 client with the VCAP_CREDENTIALS and should receive some kind of client token when the callback url in my app is called. Using this client token it should be possible to access the detail information of the logged-in user. But it's still unclear for me how to code all this details in Django. I already installed the oic Python package and am trying to find a way to implement SSO using it. Any concrete help here would be very appreciated. Thanks, Alejandro -
How to do user authentication in Django using MySQL Database? [closed]
I am trying to create a website by using Django. For the database, I decided to use MySQL. I was able to connect my Django project with MySQL. Also to do Sign up, receive user information, and save it to the database. But when I moved on to Login part I stuck here. I did much research and tried many things nothing works. I did Login previously with SQLite3, and it was pretty easy. Now as I change the database I want to be able to login but have no idea how to do it with MySQL using Django. I attached the model.py and signup view to give more details. Is anyone able to show me Django code on how to login using data in my database?(which saved using phpmyadmin) -
Make navbar active on url and any url's following from it
I am trying to make my navbar element active if the user is on the current url and any url's leading from it. For example, I want the navbar to be active on: http://example.com/products AND http://example.com/products/discounted-items I was using this: {% if url_name == 'products' %}active{% endif %} and was very happy till I realised that once I progress from the 'products' page to 'products/discounted-items' it would cease being active. Is there a clean way to do this in django? Thank you very much. -
DRF local variable 'msg_data' referenced before assignment
This is my serializers.py class UserProfileSerializer(serializers.ModelSerializer): img_count = serializers.SerializerMethodField('get_img_count') post_count = serializers.SerializerMethodField('get_post_count') msg_count = serializers.SerializerMethodField('get_msg_count') class Meta: model = User fields = ('id', 'username', 'img_count', 'post_count', 'msg_count') def get_img_count(self, obj): try: img_data = ImgSerializer(Img.objects.filter(author=obj.id), many=True) except img_data.DoesNotExist: return 0 return img_data def get_post_count(self, obj): try: post_data = PostSerializer(Post.objects.filter(author=obj.id), many=True) except post_data.DoesNotExist: return 0 return post_data def get_msg_count(self, obj): try: msg_data = Smessage(Msg.objects.filter(author=obj.id), many=True) except msg_data.DoesNotExist: return 0 return msg_data This is my views.py class UserProfile(APIView): permission_classes = [AllowAny] def get(self, request): query = User.objects.all() serializer = UserProfileSerializer(query, many=True) return Response(serializer.data) This is the Error Snippet I want to get this { "id": 9, "username": "emil@gmail.com", "img_count:3, "post_count":5, "msg_count":50, } also getting error after using img_count.count().