Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show All Data Using python manage.py shell (Django)
I have tried to migrate my database but am still having issues. I wanted to try and look at all my sites databases via Command Prompt. I want to try and see which columns do or don't exist in models. I did python manage.py shell but then could not work out the queries that would allow me to see all the information in both my sites databases. (project2_env) C:\Users\HP\django_project3>python manage.py shell (InteractiveConsole) >>> from blog.models import Post >>> from django.contrib.auth.models import User >>> User.objects.all() <QuerySet [<User: RossSymonds>, <User: RossTheExplorer>, <User: RossSymondsFacebook>, <User: testuser>]> >>> objects.all() -
Django guardian migration NodeNotFoundError after MIGRATION_MODULES defined for auth
I used django guardian in my project. For a reason, I added a new field to django group model with this code: if not hasattr(Group, 'project'): project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, related_name='groups') project.contribute_to_class(Group, 'project') So far, everything is ok. But I realized after makemigration command, django adds migration file to outside of my project directory. I want to make this file persistent. I found a solution with defining MIGRATION_MODULES in my settings.py: MIGRATION_MODULES = { 'auth': 'preferences.migrations' # preferences is an app of mine } But this time, django guardian module gives error after makemigration command. The errors are below: Traceback (most recent call last): File "./manage.py", line 16, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django_cassandra_engine/management/commands/makemigrations.py", line 22, in handle super(Command, self).handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 248, in build_graph self.graph.validate_consistency() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency … -
URL path is added twice when using proxy
Background: I was having a lot of issues with my internet connection so I had to buy an unlimited set of mobile data to be able to work. Unfortunately the internet provider do not allow me to share internet with other devices if the package you bought was an unlimited one. The only way to do it was using a proxy in my Android device to share internet, so with that, I am allowed to use it as hotspot and use internet in my laptop. Issue: I was trying to reach to a server api, and I could from my mobile phone (Android app I am building), but from Postman (in my laptop), I've been getting 404 errors. It is really weird since I can access to absolutely any other webpage/api but not this one specifically. That makes me think it could be something server misconfiguration related, but I am just an Android developer, so I have not idea of what could happen on the backend side. I noticed (as you can see in the image attached: https://imgur.com/a/jtHBA2I) that somehow the URL path is being added twice, the URL should be http://its-jitzone-dev.cloudapp.pe/, but instead, is being modified to http://its-jitzone-dev.cloudapp.pe/http:/its-jitzone-dev.cloudapp.pe. Question: … -
putting a different background image on a different page in a website
Hello so I am using django templating to make a website. So far only the home page has a background image and I want to place a different image on a separate page. Django templating has me use "extends base html". I keep trying to insert a different background page to replace the generic white background page on the search_results.html but the code doesn't work. I want my search_results.html have a different background from home.html. Appreciate the help! Code: I'll only include the ones on the head of each html to ensure not too much code about the body is put Base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title> {% block title %} My Site {% endblock title %} </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script> <![endif]--> <link href="{% static 'css/bootstrap/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/signinform.css' %}" rel="stylesheet"> <!-- Add your custom CSS to this file --> <link href="{% static 'css/custom.css' %}" rel="stylesheet"> {% block additional_styles %} <style> body {background-image: url(./static/images/golden_gate_bridge.jpg); } </style> {% endblock %} </head> Home.html (this one uses … -
How to write and make correct POST request for nested serializers in DRF?
I have two simple models, and serializers for Course and Department as below: (A course belongs to a department, that is many to one relationship from Course to Department) # models.py # Department Model class Department(models.Model): name = models.CharField(max_length=256) location = models.CharField(max_length=1024) # Course Model class Course(models.Model): code = models.CharField(max_length=15, unique=True) name = models.CharField(max_length=15, unique=True) department = models.ForeignKey(Department, on_delete=models.CASCADE, default=None, null=True, blank=True) ################################### # serializers.py # Department serializer class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ['id', 'name'] # Course serializer class CourseSerializer(serializers.ModelSerializer): department = DepartmentSerializer() class Meta: model = Course fields = '__all__' After adding some courses through SQL Queries, I made a GET request to the end point localhost:8000/courses/ which gives the expected result. [ { "id": 1, "code": "SS240", "name": "Sociology", "department": { "id": 1, "name": "Humanities" } }, { "id": 2, "code": "CS310", "name": "Data Structures and Algorithms", "department": { "id": 5, "name": "Computer Sciences" } } ] I want to make a POST request to the end point localhost:8000/courses/. Say, I have a department with name = Computer Sciences with id = 5. I want to add a course with code=CS330, name = Object Oriented Design, department = Computer Sciences. How should I write … -
Enter a list of values error in forms when ManyToManyField rendered with different type of input
I changed the widget of my ManyToManyField, tags, in my model to hidden... class PreachingForm(ModelForm): class Meta: model = Preaching fields = ['title', 'text', 'date', 'privacy', 'tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), 'tags': forms.HiddenInput(), #changed to hidden input } ... and in the html, I'm supplying the hidden input with comma separated values <input type="hidden" name="tags" value="Tag1,Tag2" id="id_tags"> The problem is I'm getting a form error saying Enter a list of values and I want to strip(',') the data I got from the hidden input so it might be fixed but I have no idea how to do it. -
Dropdown list with 'other' option which displays a text field
I'm trying to write a Django application with a form which includes a field 'how did you hear about us?' which will give a dropdown list (tv commercial, search engine, etc) including an 'other' option. Upon selecting the 'other' option a box will appear beneath and the user can enter a unique answer. I have attempted this but am stuck. Any help would be greatly appreciated. models.py class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) HEAR_ABOUT_US = ( ('option1', 'Option 1'), ('option2', 'Option 2'), ('other', 'other'), ) hear_about_us = models.CharField('How did you hear about us?', max_length=200, default=None, choices=HEAR_ABOUT_US) views.py def personal_information(request): if request.method == 'POST': form = PersonalInformationForm(request.POST, request.FILES, instance=request.user.personalinformation) if form.is_valid(): if form['hear_about_us'] == 'other': form_data = self.get_form_step_data(form) form.refer = form_data.get('other', '') form.save() return redirect('#') form.save() return redirect('#') else: form = PersonalInformationForm(instance=request.user.personalinformation) context = { 'form' : form } return render(request, 'enrolment/personal_information.html', context) personal_information.html {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Personal Information</legend> {{ form|crispy }} <div id='other' class='other'> <!-- WANT THE TEXT BOX TO APPEAR HERE / I THINK IT WOULD BE BETTER DONE WITHIN THE FORM AND NOT AS A SEPERATE SECTION UNDER IT --> </div> </fieldset> <div class="form-group"> <button class="btn … -
How to set a Foreign Key based on multiple column with django-import-export?
There's a model defining which combination of department/position needs what types of training. Another model shows employees with all related information. All the data comes from xlsx file via django-import-export. The problem is that I can't figure out how to set a foreign key in employees model based on the unique combination of department and position rows, so each employee gets the training field value accordingly. I've tried this solution but it didn't work (or maybe I did something wrong): https://github.com/django-import-export/django-import-export/issues/375 I'm new to programming and this is my first project. Hope some of you can help. Here is my model defining training for each combination of department/position: class TrainingMatrix(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE,blank=False, null=True) position = models.ForeignKey(Position, on_delete=models.CASCADE,blank=False, null=True) training = models.ManyToManyField(Training) Here is the Employee model: class Employee(models.Model): badge = models.CharField(max_length=15, primary_key=True, unique=True) name = models.CharField(max_length=200) department = models.ForeignKey(TrainingMatrix, on_delete=models.CASCADE, null=True, blank=True,related_name='department_name') position = models.ForeignKey(TrainingMatrix, on_delete=models.CASCADE, null=True, blank=True,related_name='position_title') training = models.ForeignKey(TrainingMatrix, on_delete=models.CASCADE, null=True) And the xlsx file's column titles I import: badge, name, position, department -
About modifucation of Whoosh score algorithm
I have 2 questions about whoosh, hope someone can help me. (1) How can I get the number of unique items in given documents, it seem that the funtion “doc_field_length” could only support the number of total tokens in given documents. (2) How can I get the number of a query , for example when a query is " banana apple animal" , the number should be 3. Since I would develop a new scoring method instead of the original one "BM25" My whoosh version 2.7.4, python 3.5.6 Thank you very much -
How to link to other user's profile in django?
What I have been trying is to click the post's author(user that created the post) I want it to redirect me to that user's profile,for example in instagram when you click the user that is on top of the post it redirects you to their profile. Everytime I do that instead of seeing the post's author profile I see the loged in user profile. I think there is something wrong in the views.py file or in the base.html. views.py def profile(request, pk=None): if pk: user = get_object_or_404(User, pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) def home(request): created_posts = Create.objects.all().order_by("-added_date") return render(request, 'base.html', {"created_posts": created_posts}) def create(request): if request.method == 'POST': created_date = timezone.now() header1 = request.POST['header'] content1 = request.POST['content'] user = request.user created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user) created_obj.save() print('create created') return redirect('home') else: print('create not created') return render(request, 'create.html') models.py class Create(models.Model): added_date = models.DateTimeField() title = models.CharField(max_length=200) content = models.CharField(max_length=200) user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' urls.py urlpatterns = [ path('', views.home, name='home'), path('profile', views.profile, name='profile'), path('profile/<int:pk>/', views.profile, name='profile_pk'), path('create', views.create, name='create'), ] profile.html (shows user's profile) … -
accessing product sub categories like ebay in django form
i am trying to replicate the category structure sites like Ebay use when posting a product. For example, if you want to post an Iphone for sale, you go to post an ad, choose a category from the drop down menu on the form('electronics & computers'), then choose a subcategory of "phones", then the last sub category of "iphone". To create this structure i am using django-categories. Creating a product in the admin page works file, the admin form allows me to choose from a drop down menu of every category, however i can't seem to replicate that same process on my own form, to give users the ability to choose from the many categories. If your not aware if django-categories it is a Modified Preorder Tree Traversal. Here is my advert model class Advert(models.Model): title = models.CharField(max_length=100, blank=False, null=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='media/', blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(blank=False, null=False) condition = models.CharField(max_length=10, choices=COND_CATEGORIES, blank=False, null=False) price = models.DecimalField(decimal_places=2, max_digits=14, blank=False, null=False) description = models.TextField(blank=False, null=False) date_posted = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) featured = models.BooleanField(default=False) search_vector = SearchVectorField(null=True, blank=True) Here is the category model class Category(CategoryBase): class Meta: … -
Do I need to setup Whitenoise if Deploying with django-heroku?
The Heroku documentation says: The django-heroku package automatically configures your Django application to work on Heroku. It is compatible with Django 2.0 applications. It provides many niceties, including the reading of DATABASE_URL, logging configuration, a Heroku CI–compatible TestRunner, and automatically configures ‘staticfiles’ to “just work”. However, I saw other sources where they recommend setting up whitenoise for handling static files. Do I need whitenois if I setup django-heroku? Thanks. -
How do i save to database Js to Django
views.py def game1(request): if request.method == 'POST': point = request.POST['puan'] username = request.user.username User.objects.filter(username= username ).update(point=point) messages.add_message(request,messages.SUCCESS,'Puan başarıyla güncellendi.') return render(request, 'pages/gamepage.html') else: messages.add_message(request,messages.WARNING,'Bir hata oluştu.') return render(request, 'game/game.html') game1.html if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) { alert("Oyun bitti.\nPuanınız: " + snake.maxCells +"\nPuanınız kaydediliyor..."); // location.reload(); } Good day everybody i need help with something How to print the snake.maxCells into the database after the alert -
how i can update a model's field from another model in django?
my models.py is : class clients(models.Model): client_id = models.IntegerField(unique=True, primary_key=True ) ' ' money = models.IntegerField(default = 0) class transfermoney(models.Model): first_client_id = models.IntegerField() second_client_id = models.IntegerField() amountofmoney = models.PositiveIntegerField() time = models.TimeField(auto_now=True) date = models.DateField(auto_now=True) my serializers.py is : class UserSerializer(serializers.ModelSerializer): class Meta: model = clients fields = ('__all__') class moneytransfer(serializers.ModelSerializer): class Meta: model = transfermoney fields = ('__all__') my views.py is : class transferingmoney(APIView): def post(self,request): serializer = moneytransfer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i'm using django rest framework , and what i want is ,everytime when i make a post request into "transfermoney" model , it take the "first_client_id" and search for it into the "client_id" in the "clients" model and add the "amountofmoney" from "transfermoney" model to the "money" field in "clients" model , and the same for the "second_client_id" please how can i do that ? -
Why is Django a 'less secure' app according to Google?
Why does Google consider a request from my Django app to send an email via SMTP (smtp.gmail.com) to be insecure? Reading their security standards is not very helpful: How more secure apps help protect your account When a third-party app meets our security standards, you can: See what level of account access you’re giving the app before you connect your Google Account Let the app access only a relevant part of your Google Account, like your email or calendar Connect your Google Account to the app without exposing your password Disconnect your Google Account from the app at any time This is a very common issue when emailing from Django. There are tutorials and stackoverflow question/answers (second answer) that 'solve' this by changing settings in your google account to allow less secure apps. I had this working and was OK with it until I read this from Control Access to Less Secure Sites: Because Google is beginning to shut off Google Account access to less secure apps, the enforcement option is no longer available. We recommend turning off less secure apps access now. You should start using alternatives to less secure apps. As Google gradually moves away from allowing less … -
Django not rendering CSS
I am new to programming and currently Django will not render my CSS. This is the html request GET http://127.0.0.1:8000/static/blog/main.css net::ERR_ABORTED 404 (Not Found) Here's my current set up and what I know to be required for using static files. I don't understand how my paths are wrong if they are? In settings.py...it is installed INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', along with URL defined STATIC_URL = '/static/' This is my directory for my css file /Users/jason/PycharmProjects/blog/mysite/blog/static/blog/main and this is my html header {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> -
How to filter for a ManytoManyField with through in Django?
Trying to filter through all protocol data sources with their specific datasources in Protocol. Tried to use this: ProtocolDataSource.objects.filter(protocol__data_sources=..., protocol__data_sources=...) but obviously this comes up with an error. The dots are the name of the data source. class DataSource(Base): name = models.CharField( max_length=200, unique=True, verbose_name='Data Source Name') url = models.URLField( max_length=255, unique=True, verbose_name='Data Source URL') desc_help = 'Please briefly describe this data source.' description = models.TextField( verbose_name='Data Source Description', help_text=desc_help) class ProtocolDataSource(Base): protocol = models.ForeignKey( Protocol, related_name='protocol_data_sources') data_source = models.ForeignKey( DataSource, verbose_name='Data Source') path = models.CharField( max_length=255, verbose_name='Path to record collection') class Protocol(BaseWithImmutableKey): name = models.CharField( max_length=200, unique=True, verbose_name='Protocol Name') data_sources = models.ManyToManyField( DataSource, through='ProtocolDataSource') users = models.ManyToManyField(User, through='ProtocolUser', blank=True) organizations = models.ManyToManyField(Organization, blank=True) -
Django Wagtail template - if statement not working
Hi hopefully this is a simple fix. I'm still fairly new to Django/Wagtail and would appreciate any help. My goal is to better format my form fields by filtering with the field.label_tag value. I know for a fact the value of field.label_tag is as expected, but still no luck after confirming the output in the template and trying a few variations on the if statement. {% for field in form.visible_fields %} <div class="control-group"> <div class="form-group floating-label-form-group controls"> <label>{{ field.label_tag }}</label> {% if field.label_tag|stringformat:"s" == "Email Address" %} <strong>field.label_tag</strong> {% endif %} {% if field.label_tag|stringformat:"s" == "Message" %} {% render_field field class+="form-control" placeholder+="Message" id+="message" %} {% endif %} <p class="help-block text-danger"></p> </div> </div> {% endfor %} -
Django model form saving
Creating an eCommerce website now I have a Address model form which has another model as a foreignkey element i.e Billing Model. So the issue here is the Address form does not save I tried printing out the input data to see if it actually is receiving anything but nothing Below is my address model class Address(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) address_type = models.CharField(max_length=120, choices=ADDRESS_TYPES) address_line_1 = models.CharField(max_length=120) address_line_2 = models.CharField(max_length=120, null=True, blank=True) country = models.CharField(max_length=120, default='South Africa') province = models.CharField(max_length=120) postal_code = models.CharField(max_length=120) def __str__(self): return str(self.billing_profile) Below is my address form from django import forms from .models import Address class AddressForm(forms.ModelForm): class Meta: model = Address fields = [ 'address_line_1', 'address_line_2', 'country', 'province', 'postal_code', ] Bellow is my my html to render page {% if not object.shipping_address %} <div class="row"> <div class="col-md-6 mx-auto col-10"> <p class='lead'>Shipping Adress</p><br> {% url 'checkout_address' as checkout_address %} {% include 'addressForm.html' with form=address_form next_url=request.build_absoulute_uri adress_type='shipping' action_url=checkout_address %} </div> </div> </div> {% else %} <h1>Checkout</h1> <p>Cart Total: {{ object.cart.total }}</p> <p>Shipping Total: {{ object.shipping_total}}</p> <p>Order Total: {{ object.total }}</p> -
Can I use chromedriver with selenium for webscraping within django?
I am trying to call chromedriver with selenium inside Django for webscraping, but am having trouble. I already have a python script than scrapes data with selenium and chromedriver, but want to integrate it into Django. Is this possible? How would this work? I would like to keep using chromedriver for my webscraping within Django and prefebally don't want to show the user the chromedriver window. Would the window being controlled open up on the user's end? Would the user of the Django website need to have chromedriver installed for it to work? Would appreciate any help and advise. -
Django, Ajax and jQuery - posting form without reloading page and printing "succes" message for user
I would like to kindly ask you for your help. I wanted to create simple voting system. I somehow succeeded. I have simple "UP" button that post form with simple +1 integer for scorevalue of post. It have a lot of problems right now but I will fight with them later. Right now I wanted to add this +1 score without refreshing page (like most modern websites). I did my googling and I came up with this: https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ I have to say that it is working quite well, even with my zero knowledge about js, jquery or ajax. My problem is, that javascript is adding this +1 but it also is giving me some errors that I cannot grasp: responseText: "TypeError at /viewquestion/6/voteup\n__init__() missing 1 required positional argument: 'data'\n\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/viewquestion/6/voteup\nDjango Version: 3.0.4\n I would like to either get rid of them or understand nature of them :P And my second or main problem is that. Voting is working, but score don't change because ofcourse, page is not reloading. And I also cannot print "Success voting" message for user because, well website is not refreshing. Giving user some simple message "Voting Success" would be enough for me. Best … -
How to develop two list views that lead to one detail view in django?
I want to create a website that has a section for events. So the mapping would be done as: Homepage > Events > Event name > Event date > Event details Basically, the same type of event was held multiple times a year, so event date is a list of dates on which the event was held. I don't know how to approach this problem. I mean, I want to display a list that further displays another list and then the event details are displayed. I don't have any clue on how to do that in django. -
Django, TypeError: unhashable type: 'dict', where is the error?
I'm new in django. I'm trying to run my code but give me the following error: TypeError: unhashable type: 'dict'. I'm checking all code but I don't understand where is the mistake. Moreover I don't sure about the correctness of my code. Could you give me the necessary supports? Here my models.py class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantita')*F('prezzo'), ) def get_monthly_totals(self): conto = dict((c.id, c) for c in Conto.objects.all()) return list( (conto, datetime.date(year, month, 1), totale) for conto_id, year, month, totale in ( self.values_list('conto__nome', 'data__year', 'data__month') .annotate(totale=Sum(F('quantita') * F('prezzo'))) .values_list('conto__nome', 'data__year', 'data__month', 'totale') )) class Conto(models.Model): nome=models.CharField('Nome Conto', max_length=30, blank=True, default="") def __str__(self): return self.nome class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE,) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE,) sottocategoria = models.ForeignKey(Sottocategoria, on_delete=models.CASCADE, null=True) um = models.CharField() quantita=models.DecimalField() prezzo=models.DecimalField() data=models.DateField('Data di acquisto', default="GG/MM/YYYY") objects=MaterialeManager() def __str__(self): return str(self.sottocategoria) and here my views.py: def conto_economico(request): defaults = list(0 for m in range(12)) elements = dict() for conto, data, totale in Materiale.objects.get_monthly_totals(): if conto not in elements: elements[conto] = list(defaults) index = data.month - 1 # jan is one, but on index 0 elements[conto][index] = totale context= {'elements': elements,} return render(request, 'conto_economico/conto_economico.html', context) -
Django urls NoReverseMatch - missing argument
I've a more or less working comment and edit comment system. However, when I configured everything so that the proper userreview_id is pulled to the url in my UpdateView, it broke the link going from index page to details (it is in details thatare displayed comments, access to comment form and to updateview form). Here is my code with Broken URL urlpatterns = [ # ex: /restaurants/ path('', views.index, name='index'), # ex: /restaurants/15 path('<int:restaurant_id>/', views.details, name='details'), path('/edit/review/<int:userreview_id>', views.EditReview.as_view(), name='edit-review'), ] Details view def details(request, restaurant_id): # calling restaurant ID and displaying it's data restaurant = get_object_or_404(Restaurant, pk=restaurant_id) # calling a review and displaying it's data user_review_list = UserReview.objects.filter(pk=restaurant_id) user_reviews = [] for user_review in user_review_list: if user_review.posted_by == request.user: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by, "edit": user_review.get_edit_url}) else: user_reviews.append({"user_review_grade": user_review.user_review_grade, "user_review_comment": user_review.user_review_comment, "posted_by": user_review.posted_by}) return render(request, 'restaurants/details.html', {'restaurant': restaurant, 'user_review_list': user_reviews,}) index template {% extends "base_generic.html" %} {% block content %} <h1>Restauracje Poznan</h1> <p> Search by name or city <form action="{% url 'restaurants:search_results' %}" method="get" class="form-inline"> <div class="form-group mx-sm-3 mb-2"> <input name="q" type="text" placeholder="Search..."> </div> <div> <input type="submit" class="btn btn-primary mb-2" value="Search"> </div> </form> </p> <h2>Restaurants and other gastronomy places:</h2> {% if restaurants_list %} <ul class="list-group"> {% for restaurant in … -
Real time updates in a Django template
I have a django webapp that displays stock data. How it works: I make requests to a stock data API and get data every 15 mins when the US stock market is open. This is a background periodic task using Celery. I have a database where I update this data as soon as I get it from the API. Then I send the updated data from the database to a view, where I can visualize it in a HTML table. Using jQuery I refresh the table every 5mins to give it a feel of "real time", although it is not. My goal is to get the HTML table updated (or item by item) as soon as the database gets updated too, making it 100% real time. The website will have registered users (up to 2500-5000 users) that will be visualizing this data at the same time. I have googled around and didn't find much info. There's django channels (websockets), but all the tutorials I've seen are focused on building real time chats. I'm not sure how efficient websockets are since I have zero experience with them. The website is hosted on Heroku Hobby for what its worth. My goal is …