Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link properly sphinx index.html file to a view
My sphinx documentation is generated properly with custom theme. The documentation file is called index.html which I use as template in a django view to render the documentation. Problem : I lost the the theme sphinx_rtd_theme and links between pages. Could you please help me? -
CKEditor doesn't load on Django admin site
I deployed my project on Heroku but when I login to the admin site on Django, CKEditor doesn't load. I'm using CKEditor in order to implement RichTextField in my models. This is the error GET https://portfolio-jpl.herokuapp.com/static/ckeditor/ckeditor-init.js net::ERR_ABORTED 404 (Not Found) GET https://portfolio-jpl.herokuapp.com/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) Settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'general', ] MIDDLEWARE = [ '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Other settings STATIC_URL_DEFAULT_IMAGE = '/static/base/img/default.png' STATIC_URL_PROFILE_IMAGE = '/static/base/img/personal/' STATIC_URL_IMG = '/static/base/img/portfolio/' I'm a little confused due to I don't have CKEditor folder in the static directory. -
Change field using setter in Admin panel
I have following structure: (Models) class Lessons(models.Model): status_choice = [ ("COMING", _("Coming soon..")), ("PROGRESS", _("In progress")), ("DONE", _("Done")), ("CANCELED", _("Canceled")) ] _status = models.CharField(max_length=15, choices=status_choice, default=COMING_SOON) @property def status(self): return self._status @status.setter def status(self, value): #some validation self.save() And admin.py: @admin.register(Lessons) class AdminLessons(admin.ModelAdmin): list_display = ("class_name", "get_full_status", "time_start", "time_end") @admin.display(description="Status") def get_full_status(self, obj): return [item[1] for item in Lessons.status_choice if item[0] in obj.status] How to implement a setter when the field is changed by the admin panel? Code (above) works when we got requests for changes but how to implement him when changes are made by the admin panel? I will be grateful for your help! -
How to create users in Django?
I am trying to use Django's user model, but when I cannot create a new user. I already ran python manage.py makemigrations and python manage.py migrate. If I try to run the commands again, I get a "No Changes Detected" message. I was able to create a superuser for Django admin, and I can use that user to log into my web application using the views that I created, but if I try to create a user, it does not appear in Django admin. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): pass views.py for creating the user from django.db import IntegrityError from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User def register(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] confirm = request.POST["confirm"] if password != confirm: return render(request, "capstone/register.html",{ "error_message": "Your passwords must match." }) try: user = User.objects.create_user(username, password) user.save() except IntegrityError: return render(request, "capstone/register.html",{ "error_message": "You will need to pick another username." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "capstone/register.html") I have also added AUTH_USER_MODEL = 'capstone.User' to my project's setting.py. … -
Django - Giving a view access to multiple models
I followed a tutorial on Youtube that makes a website to create posts. Currently, I am working on displaying other people's profiles and their posts on their profile pages. I did it by accessing the author of the first post, but it only works if the user posted something. Is there another way to do it? The view: class UserProfileView(ListView): model = Post template_name = 'blog/user_profile.html' # defaults to <app>/<model>_<viewtype>.html--> blog/post_list.html context_object_name = 'posts' #defaults to objectlist paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') user_profile.html: {% extends 'blog/base.html' %} {% block title %}{{ view.kwargs.username }}'s Profile{% endblock title %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ posts.first.author.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <p class="text-secondary">{{ posts.first.author.email }}</p> <p class="article-content">{{ posts.first.author.profile.bio }}</p> </div> </div> {% if posts.first.author == user %} <a class="btn btn-outline-secondary ml-2" href="{% url 'change_profile' %}">Edit Profile</a> {% endif %} </div> <br> {% if posts.first.author == user %} <h3 class="ml-2 article-title">Blogs You Posted</h3> {% else %} <h3 class="ml-2 article-title">Blogs By {{ view.kwargs.username }}</h3> {% endif %} And the Post and Profile module: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) … -
Django upgrade to 4.0 Abstract models cannot be instantiated
I'm upgrading my Django App from 2.2 to 4.0.6. I made different code upgrades and have the APP mostly working. But I get the following error "Abstract models cannot be instantiated" and can't find clues on how to solve this (without downgrading Django versiion as in this post Models class AbstractMes(models.Model): mes = models.DateField(blank=False, null=True) operaciones = models.IntegerField(blank=True, null=True) facturacion = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) unidades = models.IntegerField(blank=True, null=True) diferencia = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) diferencia_porc = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) diferencia_media_movil = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class Meta: abstract = True def __str__(self): return str(self.mes) class Meses(models.Model): mes = models.DateField(blank=False, null=True) operaciones = models.IntegerField(blank=True, null=True) facturacion = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) facturacion_dolar = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) unidades = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.mes) In views meses = Meses.objects.all() abstract_meses = AbstractMes(meses) Any clues welcome. Thanks! -
Django dependent smart-select not working properly
django smart-select not working properly The first column is working but second column is not working , I added the scripts in the html page , but my problem not solved I added this scripts <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> in url I added urlpatterns = [ path('admin/', admin.site.urls), path('', include('hospitalapp.urls')), path(r'^chaining/', include('smart_selects.urls')), ] -
How dynamically change video resolution on a web-site
I have my own video hosting created on django, and I want to add the ability to change the quality of the video. What is the best way to do this? I save multiple copies of videos with different resolutions, and when users change the quality, I change the displayed video, but how can I dynamically change the resolution and not store many copies? -
choose one value multiple time in many to many field of Django
i'm creating a Ecommerce website & i have a order item model which has many to many relationship with product model so customer can add products to their order. everything is okay with my system but the customer can't order one product twice or more since Many to many field choose an option once! how can i add one value twice in a many to many field?? also if you think there's a better way rather than using this system & many to many field, you can suggest! #my_views_py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.SET_NULL) name = models.CharField(max_length=100,null=True) email = models.CharField(max_length=100,null=True) def __str__(self): return self.name or str(self.id) class Product(models.Model): title = models.CharField(max_length=200) price = models.FloatField() image = models.ImageField(upload_to='static/images') def __str__(self): return self.title class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.SET_NULL,blank=True,null=True) date = models.DateField(auto_now_add=True,blank=True) complete = models.BooleanField(default=False,null=True,blank=False) transaction_id = models.CharField(max_length=200,null=True,blank=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ManyToManyField(Product,blank=True) order = models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,blank=True) date = models.DateField(auto_now_add=True) def __str__(self): return str(self.order) -
Multiple Count annotations in Django filtering causing ProgrammingError
I am running a search page on a model which has two linked models with a ManyToMany (ForeignKey) relationship. class Session(models.Model): ... fields ... class Tuition(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) ... class Housing(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) ... I would like to filter on aggregate Counts of these two models. For Housing it's just a simple Count, I want to filter by if there is housing available for that session (aka if housing_count__gt=0) queryset.annotate(housing_count=Count('housing', distinct=True)) For Tuition I'm including a filter in the Count, because I want to account for both those where the price is listed and those where it's null. And thus, I want to again filter for sessions where only at least tuition with that price (or one null price) is linked. (tuition_count__gt=1) queryset = queryset.annotate(tuition_count=Count('tuition', filter=Q(Q(tuition__price__lte=max_tuition_passed) | Q(tuition__price__isnull=True)), distinct=True)) **However, I keep running into an issue, **seemingly in particular with the tuition_count (I've tried commenting out one/both at a time). ProgrammingError at /search/programs/summer-intensives function count(integer, boolean) does not exist LINE 1: ...ECT COUNT(*) FROM (SELECT "session"."id" AS Col1, COUNT(DIST... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I've tried … -
pgAdmin Table not showing in database after successfull migration
I am trying to create a REST API using psql and Django , i've reached the stage of applying migrations to add tables to my database, these migrations are successfull but when i open pgadmin to view my database their are no tables no matter how many times i refresh. Below is how i run the migrations: python manage.py makemigrations ExampleApp python manage.py migrate ExampleApp Any help would be much appreciated as I am completely lost at this stage :) -
Choose how to order Django Model choices
When displaying the below choices, I want to be able to order them as follows Preparation, Review, Update, Finalised and Completed. Right now, they are ordered alphabetically. The below is a simple model: class Choice(models.Model): status_choices = [ ("", "Select Current Status"), ("Preparation", "Preparation"), ("Review", "Review"), ("Update", "Update"), ("Finalised", "Finalised"), ("Completed", "Completed"), ] current_status = models.CharField( max_length=32, choices = status_choices, default = "Select current status", ) class Meta: ordering = ["current_status"] I read that assigning a number in the Tuple can allow them to be ordered, which I tried per the below: status_choices = [ ("", "Select Current Status"), ("1", "Preparation"), ("2", "Review"), ("3", "Update"), ("4", "Finalised"), ("5", "Completed"), ] However, this made no difference. forms.py listed below: class TaskForm(ModelForm): class Meta: model = Choice fields = [ 'current_status', ] widgets = { 'current_status' : forms.Select(attrs={'placeholder':'Select Current Status', 'class':'table_data_request_status'}), } I feel like this should be very simple but maybe not. Any help would be greatly appreciated. I have searched previous questions but no luck. -
Creating a separate comments app for a ticket app. Keep getting NoReverseMatch error
I'm creating a separate comments app for a ticket app project. How do I get the ticket pk from the Ticket model into get_absolute_url method that's within my Comment model? These are my models ticket models.py class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('ticket-detail', kwargs={'pk': self.pk}) comment models.py class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets:ticket-detail', kwargs={'pk': self.ticket_id}) -
accordion items in jinja2 flaks for loop collapse and show together and not independently
my accordion items do not expand separately when one is clicked on. They either both show their content or both remain close. I tried interactive IDs but this did not work. {% for study in studies %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{{ study.uid }}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs- target="#collapse{{ study.uid }}" aria-expanded="true" aria-controls="collapse{{ study.uid }}"> {{ study.uid }} </button> </h2> <div id="collapse{{ study.uid }}" class="accordion-collapse collapse" aria- labelledby="heading{{ study.uid }}" data-bs-parent="#accordionExample"> <div class="accordion-body"> text </div> </div> </div> {% endfor %} is it maybe something to do with jquery and bootstrap not being the same version? Inspecting the code shows that each accordion item in the loop has a different ID...enter image description here -
Heroku "Application error" on a Django/React app
I'm currently working on a to do list project for my studies and I was able to chose the technologies involved. I decided to use Django, React, MongoDB for the app and Heroku for the hosting. I had previous experience with React MongoDB and NodeJS and managed to host the app on heroku very easily. However with this new project I always get an "Application Error" whenever I try to access the website. I struggled to find up to date information on how to properly host a Django/React app on Heroku and none of the answers I found solved my problem. What concerns me the most is that the deployment log do not show any major issue during the build process : > Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Delta compression using up to 8 threads Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 356 bytes | 356.00 KiB/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: … -
django form not submitting when rendering specific fields in template
I have an UpdateUserForm: class UserUpdateForm(UserChangeForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) username = forms.CharField(max_length=100, widget=forms.TextInput()) last_login = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type': 'hidden'})) is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) date_joined = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type': 'hidden'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'last_login', 'date_joined') def update_user_notification(self): email = self.cleaned_data['email'] username = self.cleaned_data['username'] if self.is_valid(): update_user_notification_task.delay(email, username) and a UserUpdate view: class UserUpdate(generic.UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/update_user.html' def get_object(self): return self.request.user def form_valid(self, form): instance = form.save() form.update_user_notification() return HttpResponseRedirect(reverse('user_detail', args=[str(instance.pk)])) I originally wrote this form in the template as {{form.as_p}} and it worked, but there were some things I wanted to fix: <h1>Update Information...</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <button>UPDATE</button> </form> <br></br> <a href="{% url 'user_detail' user.pk %}">Back</a> <a href="/">Home</a> {% endblock %} Rendered as this: I wanted to get rid of those password related things at the bottom so I changed my form to: <form method="POST"> {% csrf_token %} <p><label>{{form.email.label}}: </label>{{form.email}}</p> <p><label>{{form.username.label}}: </label>{{form.username}}</p> <p><label>{{form.first_name.label}}: </label>{{form.first_name}}</p> <p><label>{{form.last_name.label}}: </label>{{form.last_name}}</p> <button>UPDATE</button> </form> This worked on the frontend, but now my form isn't submitting. When I click update, the page looks as if it's … -
How to populate model with having model django?
I have model People: with name, phone email, address fields using Django's management commands I want populate Contact model with the same fields command file: from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Sorting leads ' def handle(self, *args, **kwargs): pass 1.Multiple People with the same name and phone number should be merged together, so the resulting Contact contains all emails and addresses from merged Leads. 2. Multiple People with the same name, but different phone number and e-mail should be saved as separate contacts How have I do it ? Should I do with raw sql or there is better solution. -
Django ModelForm DateField value render
models.py class MyModel(models.Model): date = models.DateField() views.py if request.method == 'GET': instance = MyModel.objects.get(pk=pk) form = MyModelForm(instance=instance) return render(request, 'update.html', context={'form': form}) update.html <input type="date" name="date" value="{{ form.date.value.isoformat }}" /> Works fine. But in POST method if the form is not valid I rerender the template with errors and I want to render values got from POST data. views.py if request.method == 'POST': instance = MyModel.objects.get(pk=pk) form = MyModelForm(request.POST, instance=instance) form.is_valid(): pass return render(request, 'update.html', context={'form': form}) But then form.date.value is in isoformat already (because it came from POST) and the template's code stops render date value properly. How to fix it? The solution I have found is value="{{form.start_date.value.isoformat|default:form.start_date.value}}" but I don't think it is good. -
Django Forms Show Extra Categories For Users Part Of Group
I'd like to show these categories below additionally with users who have the blogger category. The current issue is.. For a blogger user it's only showing blogger categories when it should be showing all For a normal user it's showing blogger categories when it should only be showing the original 3 forms.py class PostCreateForm(ModelForm): class Meta: model = Post fields = [ "title", "category", "associated_portfolios", "body", ] exclude = ('allow_comments',) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) blogger = User.objects.filter(groups__name='blogger').exists() print("Current User:", user) print("Blogger User:", blogger) super(PostCreateForm, self).__init__(*args, **kwargs) self.fields['category'].choices = ( ("Watchlist", "Watchlist"), ("Lesson/Review", "Lesson/Review"), ("General", "General"), ) if User.objects.filter(groups__name='blogger').exists(): self.fields['category'].choices = ( ("Analysis", "Analysis"), ("Milestone", "Milestone"), ("Features", "Features"), ("Tutorials", "Tutorials"), ("Careers", "Careers"), ("Community", "Community"), ) -
How to model complex left join Django
I have two Django models that have a relationship that cannot be modelled with a foreign key class PositionUnadjusted(models.Model): identifier = models.CharField(max_length=256) timestamp = models.DateTimeField() quantity = models.IntegerField() class Adjustment(models.Model): identifier = models.CharField(max_length=256) start = models.DateTimeField() end = models.DateTimeField() quantity_delta = models.IntegerField() I want to create the notion of an adjusted position, where the quantity is modified by the sum of qty_deltas of all adjustments where adj.start <= pos.date < adj.end. In SQL this would be SELECT pos_unadjusted.id, pos_unadjusted.timestamp, pos_unadjusted.identifier, CASE WHEN Sum(qty_delta) IS NOT NULL THEN pos_unadjusted.qty + Sum(qty_delta) ELSE qty END AS qty, FROM myapp_positionunadjusted AS pos_unadjusted LEFT JOIN myapp_adjustment AS adjustments ON pos_unadjusted.identifier = adjustments.identifier AND pos_unadjusted.timestamp >= date_start AND pos_unadjusted.timestamp < date_end GROUP BY pos_unadjusted.id, pos_unadjusted.timestamp, pos_unadjusted.identifier, Is there some way to get this result without using raw sql? I use this query as a base for many other queries so I don't want to use raw sql. I've looked into QuerySet and extra() but can't seem to coerce them into having this precise relationship. I'd love for position and PositionUnadjusted to have the same model and same API with no copy-pasting since right now updating them is a lot of copy pasting. -
Getting NOT NULL CONSTRAINT from both views using django
I have an app that displays a folder which also allows you to create a subfolder within that folder. Within both the folder and the subfolder, you can upload files. Whenever I try to do that, I get the NOT NULL CONSTRAINT error. If I try uploading a file in the parent folder i get NOT NULL constraint failed: documents_document.subfolder_id and if I try uploading a file in the subfolder I get NOT NULL constraint failed: documents_document.folder_id. parent folder detail view @login_required @group_required('Document Supervisor') def folder_detail(request, pk): folder = Folder.objects.get(id=pk) documents = Document.objects.filter(folder=folder) form = DocumentForm() subfolders = SubFolder.objects.filter(folder=folder) if request.method == "POST": form = DocumentForm(data=request.POST or None, files=request.FILES or None) if form.is_valid(): form = form.save(commit=False) form.folder = folder form.created_by = request.user form.name = str(form.file.url) form.name = form.name.replace("/media/", "") form.save() messages.success(request, "Document added successfully!") return redirect(f"/documents/folder/{folder.id}") context = { "folder": folder, "documents": documents, "form": form, "subfolders": subfolders, } return render(request, "documents/folder_detail.html", context) subfolder view @login_required @group_required('Document Supervisor') def subfolder_detail(request, pk): sub = SubFolder.objects.get(id=pk) documents = Document.objects.filter() form = DocumentForm() if request.method == "POST": form = DocumentForm(data=request.POST or None, files=request.FILES or None) if form.is_valid(): form = form.save(commit=False) form.sub = sub form.created_by = request.user form.name = str(form.file.url) form.name = form.name.replace("/media/", "") form.save() … -
Selenium,Django, On Ubuntu 20.04 digital ocean VPD
I have created the web scraper and integrated it with Django. Everything is working perfectly fine. Now I want to host that Django app with webscraper on the VPS so that he can access it anywhere. I am using gunicorn and nginx too. I tried that Django app with webdriver.remote() using seleniumgrid its working fine on my normal windows environment, but as soon as I put it on my ubuntu vps it works only in half of cases - like all my Django stuff is accessible and operational, but when my django calls the scraper, it just passes without any response. def chromedriver_setup(): user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36' # proxies = proxies = [{"_id":"62cd1bf852694154bb14f2e7","ip":"178.32.148.251","anonymityLevel":"elite","asn":"AS16276","city":"Gravelines","country":"FR","created_at":"2022-07-12T07:00:08.515Z","google":True,"isp":"OVH SAS","lastChecked":1657848951,"latency":5.13,"org":"MICHOTTE Maxime","port":"8080","protocols":["socks4"], "speed":37,"updated_at":"2022-07-15T01:35:51.569Z" },{"_id":"60d613cdce5b3bb0e932edce","ip":"64.227.62.123","port":"80","anonymityLevel":"elite","asn":"AS14061","city":"Santa Clara","country":"US","created_at":"2021-06-25T17:35:09.953Z","google":True, "isp":"DigitalOcean, LLC","lastChecked":1657847332,"latency":153,"org":"DigitalOcean, LLC","protocols":["http"], "speed":306,"updated_at":"2022-07-15T01:08:52.862Z" ,"upTime":99.98473981382573,"upTimeSuccessCount":6552,"upTimeTryCount":6553}] # random_ip = random.choice(proxies) # PROXY = str(random_ip["ip"] + ":" + random_ip["port"]) option = webdriver.ChromeOptions() option.add_argument("--headless") option.add_argument(f'user-agent={user_agent}') option.add_argument("--window-size=1920,1080") option.add_argument("--start-maximized") option.add_argument("--disable-gpu") # # option.add_argument('--proxy-server=%s' % PROXY) option.add_experimental_option("excludeSwitches", ["enable-automation"]) option.add_experimental_option('useAutomationExtension', False) option.add_argument("--disable-blink-features=AutomationControlled") option.add_experimental_option("detach", True) print("chrome driver setup passed") driver = webdriver.Remote( command_executor='192.168.72.1:4444', desired_capabilities = DesiredCapabilities.CHROME, options=option, ) return driver Is there any way I can solve that issue or test i..? -
AttributeError: type object ' ' has no attribute 'object'
I am working on REST API and i get an error saying "AttributeError: type object 'Project' has no attribute 'object'" when trying to access http://127.0.0.1:8000/projects/ here is my files : --> views.py: from django.http import JsonResponse from .models import Project from .serializers import ProjectSerializer def project_list(request): drinks = Project.object.all() serializer = DrinkSerializer(projects, many=True) return JsonResponse(serializer.data) --> models.py from django.db import models class Project(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) def __str__(self): return self.name + ' ' + self.description --> urls.py from django.contrib import admin from django.urls import path from projects import views urlpatterns = [ path('admin/', admin.site.urls), path('drinks/', views.drink_list), ] -
Django tests suddenly failing for no apparent reason
I have a django project with hundreds of unit tests and after a big update that added about 50 more tests, all the project's tests that creates an instance of a specific model are failing with the following error message: Traceback (most recent call last): File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor.execute(sql, params) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File ".../venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in _execute self.db.validate_no_broken_transaction() File ".../venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 437, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. During handling of the above exception, another exception occurred: File ".../venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File ".../venv/lib/python3.9/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File ".../venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1145, in execute_sql cursor.close() File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 83, in close while self.nextset(): File ".../venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 137, in nextset nr = db.next_result() MySQLdb._exceptions.OperationalError: (2006, '') The update did not change … -
Got Errno 13 when trying to save image with Pillow [Python, Django]
Got [Errno 13] when trying to save images using Pillow. Exact error is: PermissionError: [Errno 13] Permission denied: 'C:/Users/django/PycharmProjects/django/csvs/photos/blah-summer-jean\cropped-788x1000'. My code is below: from PIL import Image from blah import settings from django.core.files.storage import default_storage from blah.storage_backends import MediaStorage import os app_storage = None image_dir = 'C:/Users/django/PycharmProjects/sassigen/csvs/photos/blah-summer-jean' cropped_dir = 'C:/Users/django/PycharmProjects/sassigen/csvs/photos/blah-summer-jean/cropped-788x1000' if settings.DEBUG: app_storage = default_storage else: app_storage = MediaStorage def crop_image(image): try: img = Image.open(image) width, height = img.size if width <= 788 and height <= 1000: pass else: xcenter = img.width / 2 ycenter = img.height / 2 x1 = xcenter - 488 y1 = ycenter - 600 x2 = xcenter + 488 y2 = ycenter + 600 image_to_crop = img.crop((int(x1), int(y1), int(x2), int(y2))) output_size = (788, 1000) final_image = image_to_crop.resize(output_size) img.close() return final_image except AttributeError: pass except Exception as e: raise e for each_image in os.listdir(image_dir): cropping = crop_image(os.path.join(image_dir, each_image)) if not os.path.exists(cropped_dir): os.mkdir(cropped_dir) cropping.save(os.path.join(cropped_dir, each_image), 'jpeg')