Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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(). -
raised ConnectionResetError when i use set_password in ajax requests
I want to send ajax request named 'client password change' here is javascript code function sendmailConfirm() { var result = confirm("client(client@google.com) password will changed"); if (result == false) { event.preventDefault(); alert('canceled.'); } else { $.ajax({ 'url': '/change/password', 'method': 'GET', 'data': { 'email':'password-change@pass.com', }, 'success':function(event){ alert('success!'); } }) } }; and view.py is class ChangePW(TemplateView): def get(self, request): if request.is_ajax(): user = User.objects.get(email='password-change@pass.com') password = random_password_generate() user.set_password(password) user.is_active = False user.save() return JsonResponse({'status': 'success'}) i do runserver and i clicked the button but it raised error ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 59753) Traceback (most recent call last): File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socketserver.py", line 717, in __init__ self.handle() File "/Users/hanminsoo/Desktop/issue/tving-ui/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/hanminsoo/Desktop/issue/tving-ui/venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Users/hanminsoo/.pyenv/versions/3.7.1/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- i cant understand when i remove user.set_password(password) it is working my django version is '3.0.4' and python version is '3.7.1' thank you :) -
Django, how to extract values list montly from DateField?
I have the following models: class Materiale(models.Model): sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) quantita=models.DecimalField(') prezzo=models.DecimalField() data=models.DateField(default="GG/MM/YYYY") I wanna calculate the value given by the following expressions PREZZO*QUANTIA in a monthly's view (in other words the total sum of PRZZO*QUANTITA of all items in a single month), but my code does not work: Monthly_views=Materiale.objects.filter(data__year='2020').values_list('month').annotate(totale_mensile=F(('quantita')*F('prezzo'))) -
How can I package a Django app with homebrew?
I'd like to package a Django + SQLite + JS-Frontend app with homebrew. Are there specifics to consider which are not obvious from the homebrew docs? -
DB level constraints to validate 1 field against another one in Django
Is it any way to use Django constraint in model (models.CheckConstraint class) in order to create a constraint to validate value of one field against another one? For example: class Season(models.Model): last_watched_episode = models.PositiveSmallIntegerField( null=True, ) number_of_episodes = models.PositiveSmallIntegerField( ) In this case I need to make a constraint that would raise an error in case value of the last_watched_episode field is greater then number_of_episodes field. 9 > 8 for example. Plus in case if last_watched_episode is Null(none) constrain should be omitted ( cant compare Null and int) I have model and serializer validators already but goal is to create DB level constraints. Way to create it with RAW SQL and custom migration is also possible but via DJANGO constraints would be preferable. Thank you. DB -postgres 12 -
celery .delay freezes for this task but runs for others
I am trying to send notifications using celery. @shared_task(name="send_notifs_to_devices_task") def send_notifs_to_devices_task(devices_ids, title, message, image=None, link=None): from pills_reminder.models import UserNotifications, UserDevice devices = UserDevice.objects.filter(id__in=devices_ids) for device in devices: UserNotifications.objects.create( uid=device.device_id, title=title, message=message, image=image, linksTo=link ) # TODO: to recieve image here device.send_notification(title=title, body=message, click_action=link) print('task to be done by celery') logger.info(f"successfully sent notifications to {len(devices)} devices") this works without .delay() >>> send_notifs_to_devices_task(devices, ... title=instance.title, ... message=instance.message, ... link=instance.link) {'multicast_ids': [4255826789468640174], 'success': 1, 'failure': 0, 'canonical_ids': 0, 'results': [{'message_id': 'https://updates.push.services.mozilla.com/m/gAAAAABepnOW1plHQRAB5kRMziPs47eXuzEFbJxR891Pps1Okyz_a-waK3jZ2IX3YehnDuuSut6WkVzEVoKODeOOkHFEf6teOyvVVatkjh3Du8UokRbLx8vC59_GbqeuS7wYxjtGGICXkrAK_xBaUjGbYaIII3nqXxGacLkcX2pWt2Ag6wGHmc3U3imzYx-3mde4zpncIVIb'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [7964723727637075692], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [7140533530146400686], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} task to be done by celery {'multicast_ids': [5226660064264463708], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None} but when i call this using .delay, it freezes. >>> send_notifs_to_devices_task.delay(devices, ... title=instance.title, ... message=instance.message, ... link=instance.link) Note, when i call another task such as add.delay(1,2), this works: >>> add.delay(1,2) <AsyncResult: 61b76768-73ef-4ca2-bbae-445ee528cafe> I don't have much knowledge of celery and i don't know what is wrong here? -
How to change lookup field in Model.viewset to other unique parameter in Django Rest Framework?
I am using Modelviewset in django rest framework. I want to change lookup field to email(unique) instead of id. I have tried adding lookup_field = 'email' inside my Schema viewset but it is not working. This is what i am getting { "detail": "Not found." } How do I resolve this. my Views.py: class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer lookup_field = 'email' my models.py: class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() email = models.EmailField(unique = True ) def __str__(self): return self.email my serializers.py: class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version', 'email') -
Maintaining order of querylist
I have a query that looks like this: top_posts= Ranking.objects.all().order_by("-score").values("post") It gets the top posts ordered by score and then this query is executed: Posts.objects.filter(id__in=top_posts) However, the order_by score is thrown away when I run this query. How do I maintain the order of the score?