Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix NoReverseMatch in django?
Here is the detail error: NoReverseMatch at /accounts/login/ Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['users/(?P<username> [^/]+)/$'] Request Method: POST Request URL: http://192.168.109.138:8000/accounts/login/ Django Version: 2.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['users/(?P<username> [^/]+)/$'] the part of views.py in users app: class UserUpdateView(LoginRequiredMixin, UpdateView): model = User fields = ["nickname", "job_title", "introduction", "picture", "location", "personal_url", "weibo", "zhihu", "github", "linkedin"] template_name = "users/user_form.html" def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self, queryset=None): return self.request.user I can not figure out how the reverse() function work and what are the useages of args and kwargs the users\urls.py: from django.urls import path from zhuri02.users import views app_name = "users" urlpatterns = [ path("update/", views.UserUpdateView.as_view(), name="update"), path("<username>/", views.UserDetailView.as_view(), name="detail"), ] the config\urls.py urlpatterns = [ path("users/", include("zhuri02.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm not sure how to figure this error,please do help,thanks in advance. -
Delete appointments with more than 30 minutes
I have this model and I am responsible for creating a function that eliminates those appointments with "CART" status that have more than 2 hours. APPOINTMENT_STATUS_CHOICES = ( ('ACTIVA','ACTIVA'), ('CERRADA','CERRADA'), ('CARRITO','CARRITO'), ('CANCELADA','CANCELADA') ) class CitaSucursal(models.Model): fecha_cita = models.DateField(null=True, blank=True) hora_inicio = models.TimeField(null=True, blank=True) hora_final = models.TimeField(null=True, blank=True) sala = models.CharField(max_length=45,null=True, blank=False, choices=SALA_ESTUDIO_CHOICES) id_sala = models.IntegerField(null=True, blank=True) prueba = models.CharField(max_length=100,null=True, blank=False) categoria = models.CharField(max_length=45,null=True, blank=False, choices=ESTUDIO_CHOICES) notas = models.CharField(max_length=200,null=True, blank=True) estatus = models.CharField(max_length=13,null=True, blank=False, choices=APPOINTMENT_STATUS_CHOICES) id_pago = models.CharField(max_length=45,null=True, blank=True) creacion = models.DateTimeField(auto_now_add=True) # When it was create ultimaActualizacion = models.DateTimeField(auto_now=True) # When i was update Paciente = models.ForeignKey(Paciente, null=True, blank=False, on_delete=models.CASCADE) Sucursal = models.ForeignKey(Sucursal, null=True, blank=False, on_delete=models.CASCADE) -
How to scrape data from website using web-scraping and store them in DJANGO models to display them later in HTML file
I am creating a University Forum using DJANGO Framework. In one of its modules, i have to scrape data from different university websites, (data contain fee structure and program offered, etc) and then store that data in DJANGO Models and then display it in HTML.. how it is possible.this is a website link "http://nu.edu.pk/Admissions/FeeStructure" thank you -
TimeoutError when trying to send email in django
enter image description here Hello i am getting TimeoutError while trying to send mail through django . the error shows as:A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond def mail_send_view(request, id): subject = 'Subject' message = 'message' send_mail(subject, message, 'kumar943954@gmail.com', ['aditya9090400@gmail.com'],fail_silently=False) return render(request, 'blog/sharebymail.html', {'form': form, 'post': post, 'sent': sent}) -
decode csv file in utf-8 (django + pandas)
My code generates a csv file, returns it to the browser. After downloading the file, all Russian words look like: РђР ± Р ° РєР ° РЅ ... encoding as if it doesn’t work. Tell me, please, how can I solve the problem? dataCsv = data.to_csv(sep=';', header='True', decimal=',', encoding='utf-8') response = HttpResponse(dataCsv, content_type="text/csv") response['Content-Disposition'] = 'attachment; filename=data.csv' return response -
How to connect to snowflake database from Django framework
I'm new to Django and I'm trying to display the result that comes from a Snowflake database. I know that Django has multiple built-in database backend engines like: django.db.backends.postgresql and django.db.backends.mysql among the other few it supports. Unfortunately, I couldn't find a proper way of configuring a database backend engine in the settings.py My guess was to go with sqlalchemy as that's what I usually use to connect to Snowflake outside of Django but for some reason, it's not working properly. I'd appreciate any guidance on that. -
Django has exception while "collectstatic" django.core.exceptions.SuspiciousFileOperation after adding STYLESHEETS in PIPELINE
As soon as I defined 'STYLESHEET' in my PIPELINE and did run python3 manage.py collectstatic, I got the django.core.exceptions.SuspiciousFileOperation: The joined path (/) is located outside of the base path component (/opt/luciapp/apps/web/lapp-web-site/src/apps/main/frontend/static) I'm sure it's nothing to do with my STATICFILES_DIRS or the STATIC_ROOT I'm an intermediate in Django Dev and surely a noob in front-end, Please help me with this. I've attached the snippets of the error log as well as the settings snippet (website) ➜ src git:(clean_for_production) ✗ python3 manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /opt/luciapp/apps/web/lapp-web-site/public This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/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.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/usr/local/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect for original_path, processed_path, processed in processor: File "/usr/local/lib/python3.7/site-packages/pipeline/storage.py", line 26, in post_process packager.pack_stylesheets(package) File "/usr/local/lib/python3.7/site-packages/pipeline/packager.py", line 100, in pack_stylesheets … -
How to exlude fields from forms?
A have model form with a few fields. In one template I want to use all of these fields in one template and exlude a certain field in another. Is it possible not to write new form and just exclude this field in views.py? -
Django ImageField upload works locally but not on production
MY MODELS FILE from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Profile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE) description = models.CharField(max_length=100,default='') city = models.CharField(max_length=100,default='') website = models.URLField(default='') phone = models.IntegerField(default=0) avatar = models.ImageField(upload_to='avatars/',blank=True,default='avatars/no.png') genre = models.IntegerField(choices=((1, ("Homme")), (2, ("Femme"))) ) def __str__(self): return self.user.username Locally when I fill the form, the image is saved in my file media/avatars/. But locally the image is not saved in this file and therefore it can not be displayed. -
Cannot install mysql / django on macOS 10.14.6
I'm getting an error while setting up django and MySQL in macOS. This is what I've tried so far python manage.py runserver 0:8000 ... django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? pip install mysqlclient Requirement already satisfied: mysqlclient in ./venv/lib/python3.7/site-packages (1.4.2.post1) WARNING: You are using pip version 19.3; however, version 19.3.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. pip install mysql-python Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip ERROR: Command errored out with exit status 1: command: /Users/Neil/Documents/GitHub/yas/venv/bin/python3.7 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/pip-egg-info cwd: /private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/q1/4yk86bss76s8zd27j30mnlr40000gn/T/pip-install-ciyk1caf/mysql-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 19.3; however, version 19.3.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. pip install mysqlclient Requirement already satisfied: mysqlclient in ./venv/lib/python3.7/site-packages (1.4.2.post1) WARNING: You are using pip … -
i can't save my form in database while iam saving getting error "'bool' object has no attribute '_committed'"
hii iam new to Django so iam working on my first blog which is articals blog so i am try to save articles from the template using Django forms but while saving getting error 'bool' object has no attribute '_committed' iam searching for a solution but didn't find out any solution. please help me. Models.py: class post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=20) discription=models.CharField(default=None ,max_length=100) text = models.TextField(max_length=2000) image=models.ImageField(upload_to="blog/",default=True,null=True,blank=True) created_date = models.DateTimeField(default=timezone.now()) published_date=models.DateTimeField(blank=True , null=True) def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title forms.py: from django import forms from .models import post class post_form(forms.ModelForm): class Meta: model=post fields=[ 'title','discription','text','image' ] views.py: def post_new(request,*args,**kwargs): if request.method == 'POST': form=post_form(request.POST,request.FILES) if form.is_valid(): form.save() form=post_form() else: form = post_form() context = { 'form': form } return render(request,'blog/post_new.html',context) -
How can I make a user data if I don't get the data from the JSON response?
I'm creating a app that get information from some users, like name, email, ID number, etc. I want to get a response from a POST but in some cases i don't get the email from the users, so I need to create a parameter with this empty data. In other words I'm making a parse of the parameters of the POST and checking if all the data is good and legit, if I don't get the email from the API i want to create a parameter or maybe a empty string at least. try: if not email: errors['email'] = _(u'This data is missing.') else: validate_email(email) if email != user_data['email']: if user_data['email'] in ["", None]: user_data['email'] = email # If the email is modified, its no longer verified and I check if the user is registered with another email. if 'email_verified' in user_data: user_data['email_verified'] = False users_same_mail = User.objects.filter(email=email) if users_same_mail.exists(): # I check if the email is twice registered # I give the user another email registered in the database errors['email'] = _( u'The email is already registered.') except ValidationError as e: errors['email'] = _( u'Bad email, please enter another one.')``` What can i write to create a empty string … -
Django UpdateView doesn't Saving form, not getting any visible errors
I have a Model, ServiceVisit, and I'm using a listview to show the query results and then I have a button loading the UpdateView in a popup window to edit but the form isn't saving. I have no styling applied and it's using form.as_p and I'm not getting any validation errors that I can see. I've tried to verify that all fields are listed and all fields have a value when the form is submitted. I've looked through the docs at Django of course and searched the problem here as well to no avail. Model class ServiceVisit(models.Model): #People involved(Client, Driver, CSR) ISVERIFIED = [('0', 'Unverified'), ('1','Verified')] ISTRUE = [('0', 'False'), ('1', 'True')] client_id = models.ForeignKey('Client', on_delete=None, null=True, blank=True) customer_service_rep = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='extension', on_delete=None, blank=True, null=True, limit_choices_to= Q( groups__name = 'Customer Service')) remove_csr_credit = models.BooleanField(default=False) driver = models.ForeignKey('Driver', on_delete=models.CASCADE, null=True, blank=True) vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE, null=True, blank=True) #Service Info service_date = models.DateField('Date Scheduled', null=True, blank=True) first_visit = models.CharField(default='True', max_length=1, choices=ISTRUE) projected_weight = models.IntegerField(null=True, blank=True) #Using Choices here over Booleans to speed up development verified = models.CharField(default='Unverified', max_length=1, choices=ISVERIFIED) def __str__(self): return f"{self.service_date} - {self.client_id}" View class ServiceVisitEdit(UpdateView): model = ServiceVisit fields = ['client_id', 'customer_service_rep', 'remove_csr_credit', 'driver', 'vehicle', 'service_date', 'projected_weight', 'verified'] def … -
Django: postgresql trigger
I am not really good when it comes in trigger trigger thing. I just want that if the admin update the StudentsEnrollmentRecord, it will trigger the SubjectSectionTeacher and it will save in StudentsEnrolledSubject. can you guys help me solve this problem? especially in PostgreSQL Trigger This is my trigger function on PostgreSQL, CREATE OR REPLACE FUNCTION public.enrollmentrecord() RETURNS trigger LANGUAGE 'plpgsql' VOLATILE NOT LEAKPROOF AS $BODY$BEGIN INSERT INTO StudentsEnrolledSubject (Students_Enrollment_Records,Subject_Section_Teacher) SELECT a.id AS Students_Enrollment_Records, b.ID AS Subject_Section_Teacher FROM StudentsEnrollmentRecords AS a INNER JOIN SubjectSectionTeacher AS b ON a.School_Year = b.School_Year AND a.Education_Levels = b.Education_Levels AND a.Courses = b.Courses AND a.Section = b.Sections Where a.EducationLevel=b.Education_Levels AND a.Course=b.Courses AND a.Section=b.Sections AND a.Student_Users=StudentsEnrolledSubject.Students_Enrollment_Records; END; $BODY$; ALTER FUNCTION public.enrollmentrecord() OWNER TO unidadb_admin; And this is my Django model.py class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Remarks … -
Is there a shortcut to insert {%%} in Pycharm?
i would like to be able to just type lets say "%%" into my files and get "{%%}" to be typed out? How do i accomplish this in Pycharm? -
search in mulit model using django
i want search from all my model in database , so i create this search functions for do this ... but always i got ' No results for this search ' how to fix this ? view.py: def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) pcprograms_database= PCprogram.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) androidapk_database= AndroidApks.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) androidgames_database= AndroidGames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) antiruvs_database= Antivirus.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) systems_database= OpratingSystems.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) pcgames_database= PCgames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html search form : <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}"> <input id="search_box" type="text" name="q" value="{{request.GET.q}}" placeholder=" Search For ... "/> <input id="search_button" type="submit" name="submit" value="Search"/> </form> html file : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for </small><b>{{ request.GET.q }}</b> : </h1> <br/><br/> {% for result in results %} <label id="label_main_app"> <img id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="170" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} {% else %} <h3> No results for this search </h3> {% endif %} {% endif %} any help … -
Django admin: inline model: how to acess current record id from has_delete_permission
Django admin.py class ProductAdmin(<SomeSuperAdmin>) # blah-blah... class ProductCommentAdmin(<SomeSuperAdmin>): # blah-blah... class ProductCommentInline(admin.TabularInline): model = ProductComment # blah-blah... def has_delete_permission(self, request, obj=None): #here I have obj.id which is id of Product, but not ProductComment #here I need to get somehow current ProductComment record data product_comment_record = <get_somehow_current_record_data > return product_comment_record.<some_bool_field> How do I access a current ProductComment record data from has_delete_permission method of an inline model? -
Use multiple databases in Django with only one table "django_migrations"
For a project in Django I have to use two databases: default and remote. I have created routers.py and everything works fine. There was a requirement to create a table on the remote database and I created migration, run it and the table django_migrations was created. I want to have only one table django_migrations, in the default database. The relevant part of routers.py is here: class MyRouter(object): # ... def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'my_app': return db == 'remote' return None I run the migration like this: python manage.py migrate my_app --database=remote Now when I do: python manage.py runserver I get the following warning: You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): my_app. Run 'python manage.py migrate' to apply them. The tables for my_app are created in the remote database, and in django_migrations inside the remote database the migrations are marked as applied. How to force Django to use only one table django_migrations, but still apply the migrations into different databases? -
Mistakes in custom pagination Django Rest Framework
I am using APIView in myproject and custom pagination also it is working but it shows same elements multiple time. Here I have tried so far. views.py class ProductByBrand(APIView): pagination_class = LimitOffsetPaginationUpperBond @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() return self._paginator def paginate_queryset(self, queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self, ctx): assert self.paginator is not None return self.paginator.get_paginated_response(ctx) def get(self, request, slug, brand, format='json'): pid = Category.objects.get(slug=slug) data = Category.objects.filter(parent_id=pid) data_categories = [] for category in data: data_categories += Category.objects.filter(parent_id=category.id) all_product = [] for data_category in data_categories: all_product += Product.objects.filter(category_id=data_category.id, brand=brand) print(all_product) ctx = [] for product in all_product: str = settings.MEDIA_URL + product.image.name ctx.append({ 'id': product.id, 'name': product.name, 'slug': product.slug, 'brand': product.brand_id, 'image': str, 'price': product.price, 'rating': product.rating, 'discount': product.discount }) queryset = Product.objects.all() page = self.paginate_queryset(queryset) if page is not None: return self.get_paginated_response(ctx) to be more precise I select brand in category section to filter the products related to that category. For example: I have two product as it can be seen from electronics category it has two products related to brand which id is 3. In this case I have … -
Django - Receiving error "too many values to unpack (expected 2)"
In my website, I have created a custom user from the AbstractUser class. When I check if a user with the same username or email exists, I get a value error returned to me. Here's my code: models.py: class Account(AbstractUser): pass def __str__(self): return self.username def __unicode__(self): return self.username views.py: try: user = Account.objects.get(username=request.POST['username']) return render(request, 'users/signup.html', {'error': 'Username has already been taken'}) except Account.DoesNotExist: try: user = Account.objects.get(request.POST['email']) return render(request, 'users/signup.html', {'error': 'Email is not available'}) except Account.DoesNotExist: user = Account.objects.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) auth.login(request, user) return redirect('home') Error returned: ValueError at /accounts/signup/ too many values to unpack (expected 2) Traceback: user = Account.objects.get(username=request.POST['username']) Does anybody have a solution? Thank you. -
saving in the database after return user?
here I use essentially Django cookie cutter, to be able to save with a custom shape sign I had to proceed in this way, it works, I'm not sure it's the right way to proceed but I only found this one. I also tested with def Signup() but no results But I realized that the user is not directly saved in the database for this test I put a timer between alt_user and alt_user.name . I noticed that User.object.get gives me the user and that I can modify the rest of the user's information. But when I look at my database, the user's backup is only done after the user returns. Is the user cached before the backup? The problem it poses and that after saving Alt_user.save() I send the id of the one if in a celery task for a longer calculation, thanks you in advance User = get_user_model() class CustomSignupForm(SignupForm): name = CharField( max_length=255) forename = CharField( max_length=255) street = CharField( max_length=255) street_number = IntegerField() city = CharField(max_length=255) country = CountryField().formfield() phone_number = IntegerField() date_of_birth = DateField() affiliate_link = IntegerField(required=False) class Meta: model = get_user_model() # use this function for swapping user model def save(self, request): # Ensure … -
Selenium Chromedriver Won't Start
I'm trying to test my code using selenium with chrome driver. But I always got this error message in my terminal. ====================================================================== ERROR: test_input_status (myweb.tests.StorySixFunctionalTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/fredypasaud/Documents/PPW/story_six/myweb/tests.py", line 58, in setUp self.selenium = webdriver.Chrome('./chromedriver',chrome_options = chrome_options) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__ desired_capabilities=desired_capabilities) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/fredypasaud/Documents/PPW/django01/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /snap/bin/chromium is no longer running, so ChromeDriver is assuming that Chrome has crashed.) And i put my chromedriver in the same directory as the manage.py of my project. And here's some code about from my test.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options class StorySixFunctionalTest(TestCase): def setUp(self): chrome_options = Options() self.selenium = webdriver.Chrome('./chromedriver',chrome_options = chrome_options) chrome_options.add_argument('--dns-prefetch-disable') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('disable-gpu') chrome_options.addArguments("--disable-extensions"); chrome_options.addArguments("--disable-dev-shm-usage"); super(StorySixFunctionalTest, self).setUp() def tearDown(self): self.selenium.quit() super(StorySixFunctionalTest, self).tearDown() def test_input_status(self): selenium = self.selenium selenium.get('http://127.0.0.1:8000/index/') status = selenium.find_element_by_id('id_status') submit = selenium.find_element_by_id('submit') status.send_keys("Coba Coba") submit.send_keys(Keys.RETURN) -
Return wrong URL in Django
When I click link to another page from 'localhost:8000/product_all/all', it's error: "Page Not Found" (Note: 'all' is parameter) It return url 'localhost:8000/product_all/all/index'. But it should be 'localhost:8000/index'. If I change page in another page that not be 'product_all/all', it's normally. (e.g. from 'index' to 'useraccount') my context menu_list = PagesMenu.objects.all() dropdown_list = DropdownMenu.objects.select_related('head_dropdown').all() context = { 'title': 'Ratchapol Optic', 'menu_list': menu_list, 'dropdown_list': dropdown_list, } in polls/views.py if type == 'all': product_list = Product.objects.all() else: product_list = Product.objects.filter(category=type) pd = { 'product_list': product_list, } pd.update(context) return render(request, 'polls/product_all.html', pd) in polls/urls.py path('product_all/<type>/', views.product_all, name='product_all'), path('', views.index, name='index'), -
Pass image from React to Django - The submitted data was not a file. Check the encoding type on the form
I'm trying to pass image via fetch and POST request to Django. Actually it works if I pass it via Postman, it appears in database, and then I can display it on my React page via GET request. Problem is that I can't pass anything to backend using my app. I already wrapped everything into FormData() but still i keep getting error that "The submitted data was not a file. Check the encoding type on the form". Any idea how to fix it? The problem is on backend or front-end part? First I grab image via react-dropzone, then cut it a bit with react-cropper and then try to pass it to django. React: sendData() { const form_data = new FormData() form_data.append('name', this.state.name) form_data.append('preview', this.state.preview.slice(5, this.state.preview.length)) form_data.append('thumb', this.state.thumb) this.state.thumbL && form_data.append('thumbL', this.state.thumbL) this.state.thumbL && form_data.append('thumbS', this.state.thumbS) // for (var pair of form_data.entries()) { // console.log(pair[0]+ ', ' + pair[1]); // } fetch("http://localhost:8000/logo/", { method: 'POST', headers: { 'Accept': 'application/json, text/pain, */*' }, body: form_data }) .then(res => res.json()) .then(resp => console.log(resp)) } onDrop = file => { const logo = file[0].name; const ext = logo.split(".").pop(); const extensions = ["bmp", "png", "jpg", "jpeg", "gif"]; if (extensions.indexOf(ext) === -1) { console.log("wrong format of … -
ModuleNotFoundError: No module named 'tinymce' for Django
So I get the following error: ModuleNotFoundError: No module named 'tinymce' when trying to deploy my Django app to Azure. It works perfectly when I test it locally, but breaks down on Azure. I've already done a pip freeze > requirements.txt and verified that django-tinymce is on that list, I've restarted my server and re-synced my GitHub project. TinyMce has been added to INSTALLED_APPS already. Here are a few code parts along with the error: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'cpu', 'django_cron', 'tinymce', ] #... TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } Error from Azure: …