Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How check if the Authenticated user is the same of the Post
I had some Models in my Blog, like a Profile(that receive a auth.User), and a Post(receive a author= Profile) That my code to check soo far, but dont work In that block should show element only if the logged user is the same of the post, for update and delete the post, but is showing for any logged user, how can I relate the View Code class Post(DetailView): model = models.Post template_name = 'post_detail.html' Template Code {%if user.is_authenticated and user.profile == post.author.profile %} ...... {%endif%} -
How do I annotate onto a select_related model?
I am selected a related object for each object in my queryset. How can I annotate a computed value for each one? Model: class School(models.Model): name = models.CharField(max_length=255) class Teacher(models.Model): name = models.CharField(max_length=255) school = models.ForeignKey(School) class Student(Entity): name = models.CharField(max_length=255) school = models.ForeignKey(School) I want to fetch all teachers and for each one their school, and the number of students in that school. This is what I tried: teachers = Teacher.objects.select_related('school').annotate(student_count=Count('school__student')) But I can see that this is wrong as the student count needs to be per school. I'd expect to be able to do something like this with my queryset afterwards: for teacher in teachers: print(teacher.name, teacher.school.name, teacher.school.student_count) -
Django Generic Relations - Object of Type ** is Not JSON Serializable
Still new to Django so bear with me. I am trying to follow Django example https://docs.djangoproject.com/en/2.2/ref/contrib/contenttypes/. I am trying to use tests.py to create notes for student 1. Here is tests.py: from django.test import TestCase from gsndb.models import * from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User # Create your tests here. student = Student.objects.get(id=4) text = "The student is content" user = User.objects.get(id=2) new_note = Note(text=text, content_object = student, user = user) new_note.save() I am wanting this to create a note for student 1. However when I run the test, I get this error: Object of type 'Student' is not JSON serializable Here is the traceback: Environment: Request Method: GET Request URL: http://localhost/gsndb/note/ Django Version: 2.1.7 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'user_app.apps.UserAppConfig', 'gsndb.apps.GsndbConfig'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 156. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 154. response = response.render() File "/usr/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/usr/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content 72. ret = renderer.render(self.data, accepted_media_type, context) File "/usr/lib/python3.6/site-packages/djangorestframework_camel_case2/render.py" in render 9. **kwargs) File "/usr/lib/python3.6/site-packages/rest_framework/renderers.py" in render 107. allow_nan=not self.strict, separators=separators … -
How to change the form instance dynamically from the data entered at the previous step
I would like from the data entered in the form to check if the person exists in the database if yes we skip the registration form to another form. Alas my code does not work. Someone can help me. FORMS = [ ("stage1-1", RegisterIdentification), ("stage1-2", RecRegister), ("stage2-1", BirthIdentification), ("stage2-2", RecBirth), ("stage3-1", FatherIdentification), ("stage3-2", RecFather), ("stage4-1", MotherIdentification), ("stage4-2", RecMother), ] TEMPLATES = { "stage1-1": "fr/public/births-wizard/stage1-1.html", "stage1-2": "fr/public/births-wizard/stage1-2.html", "stage2-1": "fr/public/births-wizard/stage2-1.html", "stage2-2": "fr/public/births-wizard/stage2-2.html", "stage3-1": "fr/public/births-wizard/stage3-1.html", "stage3-2": "fr/public/births-wizard/stage3-2.html", "stage4-1": "fr/public/births-wizard/stage4-1.html", "stage4-2": "fr/public/births-wizard/stage4-2.html", } -
Python - How to locally save a pdf file from file object? (django)
I am trying to upload a pdf file and just save it locally received from a FILE request. If it helps the file type returns the following: class 'django.core.files.uploadedfile.InMemoryUploadedFile' def file_upload(request): lesson_file = request.FILES['file'] # Save file to same directory lesson_file.save('file_name.pdf') #This is just an example of what I want to achieve -
include Create View Template in List View
i want to make my blog like facebook post the create post in the list of posts i'm trying to include the CreateView template in list view and give me that error (Parameter "form" should contain a valid Django Form.) also try to make the same method in comments, is this method work or there is anther way. This is the post_list.html. {% extends "posts/post_base.html" %} {% load bootstrap4 %} {% block post_content %} <div class="col-md-6"> {% for post in post_list %} {% include "posts/_post.html" %} {% inclide 'posts/_create_post.html %} {% endfor %} </div> {% endblock %} This is the _craete_post.html. {% load bootstrap4 %} <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" name="" value="comment"> </form> what i want to do is just include create template inside list template if this will not work i just want to make the user make a post inside the lists of posts like facebook and Thank's every one . -
How to update the model using inlineformset in django
Unable to save the data to the model foreign key(It is having OneToOne relationship ) using inlineformset factory Created inlineformset and then created view to capture the data from the formset (It is having OneToOne relationship ) models.py class Bed(models.Model): bed_no = models.CharField(primary_key=True,max_length=10, blank=True) room_no = models.ForeignKey('Room', on_delete=models.SET_NULL, null=True) ----- and so on class Guest(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) allotted_bed = models.OneToOneField(Bed,on_delete=models.SET_NULL, null = True) -------- and so on forms.py GuestFormSet = inlineformset_factory(Bed, Guest, fields='__all__',can_delete=False) views.py def guestinline(request, pk): allotted_bed = Bed.objects.get(bed_no=pk) if request.method == 'POST': formset = GuestFormSet(request.POST,request.FILES, instance = allotted_bed) if formset.is_valid(): formset.save() return HttpResponse('Sucess') else: print(formset.errors) else: formset=GuestFormSet(instance=allotted_bed) return render(request,'add_guest.html',{'formset':formset}) add_guest.html <body> <form> {{formset.as_p}} <button>Save</button> </form> </body> Expected Output: Success Actual Results: [04/May/2019 21:13:01] "GET /pgmanagement/add/6-B/?guest-TOTAL_FORMS=1&guest-INITIAL_FORMS=0&guest-MIN_NUM_FORMS=0&guest -MAX_NUM_FORMS=1&guest-0-first_name=Siddu&guest-0-last_name=Saida&guest-0-mobile=123456790&guest-0-parent_name=saida&gue st-0-dob=1992-02-06&guest-0-permenent_address=qwertyuiop%0D%0Alkjhgfdsa%0D%0A%3Blkjhgfds&guest-0-res_telephone=&guest-0- date_of_admission=2019-05-02&guest-0-email_id=siddu%40gmail.com&guest-0-emergency_contact=&guest-0-relation=&guest-0-hig her_degree=&guest-0-purpose_of_stay=&guest-0-office_address=&guest-0-office_telephone=&guest-0-id_proof_type=&guest-0-id _proof_no=&guest-0-id_proof=&guest-0-photo=&guest-0-local_address_proof=&guest-0-amount_paid=0&guest-0-sharing_type=0&gu est-0-allotted_bed=6-B&guest-0-id= HTTP/1.1" 200 4006 -
NoReverseMatch at /html-series/done/
I get this error, in sub-sub-category.html file. The namespace is fine, the url name seems to be fine as well, Please take a look, probably you can help me. That error above could be due to this line, where I reverse to that sub_sub_sub_cat url: {% for sub_cat in matching_series %} <h5>{{ sub_cat.tutorial_title }}</h5> <p>{{ sub_cat.snippet|safe }}</p> <a class='card-link' href="{% url 'tutorial:sub_sub_sub_cat' sub_cat.tutorial_slug %}"> read more</a> # here {% endfor %} I am not quite sure about sub_cat.tutorial_slug. Anyway this is the Tutorial model: class Tutorial(models.Model): tutorial_title = models.CharField(max_length=150) tutorial_content = models.TextField() tutorial_published = models.DateTimeField( "date Published", default=datetime.now()) tutorial_series = models.ForeignKey( TutorialSeries, default=1, on_delete=models.SET_DEFAULT) tutorial_slug = models.SlugField(default=1, blank=True) class Section(models.Model): section_title = models.CharField(max_length=150) section_content = models.TextField() section_published = models.DateTimeField( "date Published", default=datetime.now()) section_tutorial = models.ForeignKey( TutorialSeries, default=1, on_delete=models.SET_DEFAULT) section_slug = models.SlugField(default=1, blank=True) This is url app_name = 'tutorial' urlpatterns = [ path('', views.home_page, name='home'), path('tutorial/<int:id>/', views.tutorial_detail, name='tutorial_detail'), path('<single_slug>/', views.single_slug, name='single_slug'), path('<sub_sub_cat>/done/', views.sub_sub_cat, name='sub_sub_cat'), #here path('<sub_sub_sub_cat>/section/done/', views.sub_sub_sub_cat, name='sub_sub_sub_cat)'), ] and the last two urls respective views are here: def sub_sub_cat(request, sub_sub_cat): matching_series = Tutorial.objects.filter( tutorial_series__series_slug=sub_sub_cat) return render(request, 'tutorial/sub-sub-category.html', context={ "matching_series": matching_series, }) def sub_sub_sub_cat(request, sub_sub_sub_cat): matching_series = Section.objects.filter( section_tutorial__tutorial_slug=sub_sub_sub_cat) return render(request, 'tutorial/sub-sub-sub-cat.html', context={ "matching_series": matching_series, }) Thank you for time and … -
How to create dynamic charts with Django and Chart.js?
I'm creating a web page, and want to include a chart that shows the evolution of temperature during time. Temperature data are saved in a database every seconds. Django retrieve this data and pass it to the template. Django : def Dashboard(request): temp = Info.objects.using('wings').filter(localisation ='Wing_1').order_by('-time') time1 = [] temperature = [] for dataset in temp : time1.append(dataset.time.strftime("%Hh%M")) temperature.append(dataset.temp_wing) time1 = time1[:60] temperature = temperature[:60] time1.reverse() temperature.reverse() context = { 'time1': time1, 'temperature': temperature, } return render(request, 'Dashboard/dashboard.html',context) Template : <!DOCTYPE html> {% load static %} <canvas id="myChart" width="400" height="200"></canvas> <script src="{% static 'Dashboard/js/Chart.min.js' %}"></script> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: {{time1|safe}}, datasets: [ {label: 'Wing 1 temperature', data : {{temperature|safe}}, backgroundColor:['rgba(54, 162, 235, 0.2)'], borderColor: ['rgba(54, 162, 235, 1)'], borderWidth: 1} ]}, options: { scales: { yAxes: [{ ticks: { beginAtZero: false }}]} } }); ChartUpdate(function(){ myChart.data.datasets[0].data = {{temperature|safe}}; myChart.data.labels = {{time1|safe}}; myChart.update(); }, 5000); </script> The chart is properly rendered with the value of the database. But I had expected that the ChartUpdate function in the template will automatically update the graph with the value freshly saved in the database, but it doesn't seem to work... Is there … -
Django: Check in template if queryset is empty
I have found the solution for this but only by checking in views so far. I need to check in templates. My view: brands = Brand.objects.all() for brand in brands: brand.products = Product.objects.filter(brand=brand.id) And so in my template I want to show all my brands but not those which do not have any product. {% for brand in brands %} {% if brand.product is not None %} <!-- Displays brand --> {% endif %} {% endfor %} Something like that, but the code is not None doesn't work for empty querysets and it is still displaying brands with no objects in them. What can I do? -
I got this error when i'm tring to install libraries using requirements.txt file #Django
Can't install google-api-core virtualenv venv source venv/bin/activate pip install -r requirements.txt ERROR: google-api-core 1.10.0 has requirement requests<3.0.0dev,>=2.18.0, but you'll have requests 2.11.1 which is incompatible. Screenshot -
Storing the username of user who submitted form using foreignkey?
I'm building an inventory system using django as a framework. I have a modelform that a logged in user will submit to place an order. all of the fields I want to be filled work with the exception of the 'store' field, which corresponds to the individual who's placing the order. I dont want the user to submit the username which is why it's been excluded in the form, I'd like to override it with 'commit=false' and add it automatically. Fairly new to django so I'm unsure whether this is a problem. So far I've added a foreignkey from the 'store' field to the user table. However when the form is submitted the 'store' field remains null. I'd like the actual username from users to be placed in this field. models.py class Sysco(models.Model): milk = models.IntegerField(null = True) store = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null = True,) oder_date = models.DateTimeField(auto_now_add=True, blank=True, null = True,) def __str__(self): managed = True db_table = 'sysco' form.py class syscoform(forms.ModelForm): class Meta: model = Sysco exclude = ('store', 'order_date') views.py class SyscoOrder(TemplateView): template_name= "SyscoOrder.html" def get(self, request): form = syscoform(request.POST,) context = { 'form' : form, } return render(request, self.template_name, context) def post(self, request): form = syscoform(request.POST,) … -
Multilingual slug with django-translated-fields
I am trying to implement a multilingual Django website with help of django-translated-fields. The project I am working on is based on cookiecutter-django and Docker. The translation works fine for my model fields – except the slug filed. Actually translation of slug works as well but I am not able to take slug field for getting one single entry. Excerpt of voting model: class Voting(models.Model): slug = TranslatedField( models.SlugField( max_length=80, unique=True, verbose_name="Voting URL slug", blank=True ), { "de": {"blank": True}, "fr": {"blank": True}, "it": {"blank": True}, "rm": {"blank": True}, "en": {"blank": True}, }, ) Full voting model of project can be seen here. Excerpt of view: def voting(request, slug): voting = get_object_or_404(Voting, slug=slug) context = { 'voting': voting } return render(request, 'votes/single.html', context) Full view can be seen here Since Django translated fields creates slug_en, slug_de and so on I cannot find a solution for getting the slug in corresponding language. It should be obvious since documentation of Django-translated fields says: No model field is actually created. The TranslatedField instance is a descriptor which by default acts as a property for the current language's field. Unfortunately, don’t get it anyway. Any idea how I can change voting model for getting … -
Django: Get a single field from queryset in template
I have this in my view: def articles(request): brands = Brand.objects.all() for brand in brands: brand.products = Product.objects.filter(brand=brand.code) return render(request, "products.html", {'brands':brands}) And then in my template I'm trying to show all the products in groups separated by brand: <ul class="sidebar navbar-nav col-2"> {% for brand in brands %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" title="{{ brand.name }}" href="#" id="pagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span>{{ brand.name|lower|capfirst }}</span> </a> <div class="dropdown-menu" aria-labelledby="pagesDropdown"> {% for product in brand.products %} <a class="dropdown-item" data-toggle="tooltip" title="Testing" href="{{ product.code }}">{{ product.name }}</a> {% endfor %} </div> </li> {% endfor %} </ul> Problems are in href="{{ product.code }}" and >{{ product.name }}</a>. I don't know how to get the articles' code and name. I can acces to the whole product queryset though, but it's not useful for me. How can I achieve this? Thanks! -
Error while running python manage py migrate
I am new to django, I was running python manage.py migrate and got this error. (py1) G:\django\djangoproject1>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\management\commands\migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\mysql\validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\mysql\validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 254, in cursor return self._cursor() File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 229, in _cursor self.ensure_connection() File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Mahin\Envs\py1\lib\site-packages\django\db\backends\mysql\base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "C:\Users\Mahin\Envs\py1\lib\site-packages\MySQLdb__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\Mahin\Envs\py1\lib\site-packages\MySQLdb\connections.py", line 164, in init super(Connection, self).init(*args, **kwargs2) django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") -
Font awesome is not rendering from S3
I have deployed djnago app in aws elastic beanstalk and using s3 bucket for static files. Fontawesome is not rendering properly. It showing only square. Not sure this is font problem or css related problem. But this font showing properly in my local Linux machine without a problem. Below is my configurations cors configuration <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://example.com</AllowedOrigin> <AllowedOrigin>https://example.com</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> </CORSRule> </CORSConfiguration> Bucket policy { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::xxx-static/*" } ] } -
TypeError at /login/ 'bool' object is not callable
im setting up user authentication for an ecommerce site and when printing (request.user.is_authenticated()) i get the below error TypeError at /login/ 'bool' object is not callable from .forms import ContactForm, LoginForm def login_page(request): form = LoginForm(request.POST or None) print("User logged in") print(request.user.is_authenticated()) if form.is_valid(): print(form.cleaned_data) return render(request, "auth/login.html", {}) im expecting to receive a print from the console "user is logged in" -
Django TypedChoiceField choices insert values from the model
I have a Product model that has stock = models.PositiveIntegerField () is the number of goods in stock. When creating a product, I create a random quantity of goods. The product is added to the basket and there I can change the number of goods. I would like to display the number I entered when creating. forms.py class CartProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=[**here need product.stock form this product**], coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) How can I pass an argument to this form so that product.stock is displayed in choices parameter? show_cart.html This file shows us our shopping basket. {% for item in cart %} {% with product=item.product %} <tr> <td>{{ product.name }}</td> <td> <form action="{% url 'cart:cart_update' product.id %}" method="POST"> {% csrf_token %} {{ item.update_quantity_form.quantity }} <button>Обновить</button> </form> </td> <td><a href="{% url 'cart:cart_delete' product.id %}">Удалить</a></td> <td>{{ item.price }} руб.</td> </tr> {% endwith %} {% endfor %} It looks like you can see select forms are empty. Here is the method that gives us this page def cart_show(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/cart_show.html', {'cart': cart}) How can I enter the values of the quantity of goods in stock in the … -
How can I make actions with selected objects in Django
I'm new at Django and have some troubles with making actions with database objects, wich I need to select with checkboxes models.py class Scooter (models.Model): name = models.CharField(max_length=100, verbose_name='name') price = models.IntegerField(max_length=10, verbose_name='price') url = models.URLField(verbose_name='url') views.py class MainView(TemplateView): template_name = 'mainApp/index.html' def get(self, request): scooters = Scooter.objects.all().order_by('price') return (render(request, self.template_name, context={'scooters':scooters})) and my html template is: <table class="table table-sm table-borderless table-hover table-responsive-lg"> <caption>Перечень товаров</caption> <thead class="thead-dark"> <tr> <th scope="col"></th> <th scope="col">№</th> <th scope="col">Name</th> <th scope="col">Price</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> <form action="" method="post"> {% for elem in scooters %} <tr> <th> <input type="checkbox" id="{{ elem.num }}" name="scooter_select" value="/{{ elem.num }}"> <label for="scooter{{ elem.num }}"></label> </th> <th> {{ forloop.counter }} </th> <th scope="row"> <a href="{{ elem.url }}">{{ elem.name }}</a> </th> <td>{{ elem.price }}</td> <td> <a href="{{ elem.id }}/update" class="badge badge-warning" role="button" aria-pressed="true">Edit</a> </td> <td> <a href="{{ elem.id }}/delete" class="badge badge-danger" role="button" aria-pressed="true">Delete</a> </td> </tr> {% endfor %} </form> </tbody> </table> So I can't understand, how can I catch selected with checkbox objects? -
How to make sure only one BooleanField is true for a single model?
I have a django project in which I have a Videos model. On my index template page I only want to show a single video, the one that has isFeatured equal to true. Whenever I change another video's isFeatured property to true, it should make that property false for the former video. I've checked out other stackoverflow questions about this but all of them are dealing with a foreign key, while my model is simpler and I think there is an easier solution for this. This is how my model looks like: class Video(models.Model): url = models.URLField(max_length=200) isFeatured = models.BooleanField(default=False) def __str__(self): return self.url -
Why is multiprocessing breaking my django app?
Basically, I have a django app where each user can spawn a new thread or process with a request to the server. At first, I was using threading and the app ran without problems, but quickly I ran into performance issues with >8 threads running at the same time.The oneTimeStartAll() function is called once, when the server starts. When I switched to multiprocessing, I got the following Traceback: Note: the errors only pop up, when executing .start() for the process System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace System check identified 1 issue (0 silenced). May 04, 2019 - 13:59:13 Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): Traceback (most recent call last): Django version 2.1.7, using settings 'notifym.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. File "<string>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <module> File … -
Django runserver doesn't do anything after system check with no error
I have a blog written using django 1.9. Now I'm trying to move to django 2.2. When I run python manage.py runserver, the system check finds no error. But it exits without starting server. The output is as follows: (blog) borg@borg-TravelMate-P258-MG:~/githubRepo/Blog/Blog$ python manage.py runserver 0.0.0.0:8887 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). (blog) borg@borg-TravelMate-P258-MG:~/githubRepo/Blog/Blog$ Since there is no any exception printed, I have no idea how to solve it right now. -
Nginx Conf with Static Files under Django
I am setting an Nginx configuration with my Django project. In order to provide some static file without /static/ showing on the URL, I add some rewrite rules in Nginx configuration. Here is part of my Nginx configuration: location /static/ { location ~* \.(png|jpg|jpeg|gif|css|js)$ { access_log off; expires 30d; } alias /path/to/myproject/static/; } location ~ ^/favicon.ico$ { rewrite ^/favicon.ico$ /static/favicon.ico; } location /foo/ { rewrite ^/foo/(.*)$ /static/abc/$1; } location /bar/ { rewrite ^/bar/(.*)$ /static/bar/$1; } location / { fastcgi_pass myproject; include django_fastcgi_params; proxy_http_version 1.1; proxy_set_header Connection ""; } When I access https://myproject.com/foo, it will show 404 page of Django. I think it is because there is no matching location in Nginx (should end up with slash /) and no matching URL in Django's urls.py. When I access https://myproject.com/foo/, it will show index.html under myproject/static/foo/ folder, or it will be 403 Forbidden if there is no index.html. But I found that... When I access https://myproject.com/foo/abc, it will 301 Moved Permanently to https://myproject/static/foo/abc/ When I access https://myproject.com/foo/abc/, it will directly show https://myproject/foo/abc/, which are the files under myproject/static/abc/ Why these two URLs work differently? Is there any modification I should do? -
How to fix Django Oscar application.urls, when changed to custom path (/store) breaks login redirect link from checkout
Changing url(r'', include('application.urls')) to url(r'^store/', include('application.urls')) causes login redirect url to fail from checkout from cart as anonymous user. I have included LOGIN_REDIRECT_URL = '/pricing/accounts/' in settings.py. This fixes the direct login redirect url. However if an anonymous user tries to add product to cart, it is supposed to redirect to login page /store/accounts/login/?next=/pricing/checkout/ but it redirects to /accounts/login/?next=/pricing/checkout/. What is the workaround to fix this without breaking anything? -
To generate an form with django
I trying to generate an form with django and i don't have reaultats that i want. I'd like equivalence oh this code in django. Here is code html : <div id="formulaire"> <form method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control input-field bordure" placeholder="Matricule" type="text" minlength="6" maxlength="7" required name="matricule" id="matricule"> </div> <div class="form-group"> <input class="form-control input-field bordure" placeholder="Nom utilisateur" type="text" minlength="4" maxlength="20" required name="nom_user" id="nom_user"> </div> <div class="form-group"> <input class="form-control input-field bordure" placeholder="Nom" type="text" maxlength="25" required name="nom" id="nom"> </div> <div class="form-group"> <input class="form-control input-field bordure" placeholder="Prénom" type="text" maxlength="30" required name="prenom" id="prenom"> </div> <div class="form-group"> <input class="form-control input-field bordure" placeholder="Adresse électronique" type="email" required name="mail" id="mail"> </div> <div class="form-group"> <input class="form-control input-field bordure" placeholder="N°téléphone" type="tel" maxlength="30" required name="num_tel" id="num_tel"> </div> <div class="form-group"> <select class="form-control input-field" required name="filiere"> <option class="bordure">--Filière--</option> <option value="mathematique">Mathématiques</option> <option value="biochimie">Biochimie</option> <option value="chimie">Chimie</option> <option value="informatique">Informatiqe</option> <option value="boa">Biologie Animale</option> <option value="bov">Biologie Végétale</option> <option value="physique">Physique</option> </select> </div> <div class="form-group"> <select class="form-control input-field" required name="niveau"> <option class="bordure">--Niveau--</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> <div class="form-group"> <input class="form-control input-field bordure" placeholder="Mot de passe" type="password" required name="mdp" id="mdp"> </div> <div class="form-group"> <button class="btn btn-primary btn-block">S'inscrire</button> </div> </form> </div>