Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
duplicate key value violates unique constraint "booking_reservation_student_id_key" DETAIL: Key (student_id)=(1) already exists
I am new to Django and currently working a hostel booking system. I however experincing some errors. Firstly,I want the is_reserved field in the room model to be True upon reservation,I have tried manay ways but it doesnt work for me. Secondly,I get an error when a user tries to book twice,Is there any way I cane solve this error: Here is my code and errors displayed: def RoomBookingView(request,pk): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() room_id.is_reserved = True return redirect('confirm') return render(request,'room-detail.html',{}) class Reservation(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete = models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Reservation' verbose_name_plural = 'Reservations' def RoomBookingView(request,pk): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() room_id.is_reserved = True return redirect('confirm') return render(request,'room-detail.html',{}) class Room(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,null=True,blank=True,unique=True) price = models.IntegerField() hostel = models.ForeignKey(Hostel,on_delete=models.CASCADE,null=True) number_of_beds = models.IntegerField() room_thumbnail = models.ImageField(null=True) resized_thumbnail = ImageSpecField( processors=[ResizeToFill(620, 430)], format='JPEG', options={'quality': 60}) room_type = models.ForeignKey(Category,on_delete=models.CASCADE) room_number = models.IntegerField() is_reserved = models.BooleanField(default=False) description = models.TextField() def get_absolute_url(self): return … -
How to create templates folder inside of an app in Django?
So Basically I like to create templates folder in main project directory and than I just create HTML file inside of it. But now I want to create this templates folder inside of an app. How can I do it? Thanks Good people in Advance. -
Is there a method to create a persistent variable in my Django view function?
I'm currently grabbing a variable 'type' via GET when my view function is called, as shown. I need to query by this variable in my POST method. def article_delete_view(request, pk): type = request.GET.get('type') #GET THE VARIABLE from referring data-url obj = Listing.objects.get(type=type) # I could query here if I wanted (illustration only) article = get_object_or_404(Article, pk=pk) data = dict() if request.method == 'POST': article.delete() data['form_is_valid'] = True articles = Article.objects.all() obj = Listing.objects.get(type=type) #THIS DOES NOT WORK, since 'type' is not passed on submit. context = {'articles':articles, 'obj':obj} data['article_table'] = render_to_string('article_table.html', context) else: context = {'article':article} data['html_form'] = render_to_string('article_delete.html', context, request=request) return JsonResponse(data) Is there a best-practice way to make that variable persist when POST is called on a submit? I know declaring a global is a bad idea. Thought about writing it to memory (attached to article) but that feels like a hack. I could get my <input> method to pass 'type' but to do so I'd have to refactor a lot of other things. Are django session variables the answer here? Any perspective is helpful. Thanks in advance. -
When are Django model objects initialized?
I'm facing an interesting problem in Python with Django. I think just by putting my code you will get what I'm trying to do. views.py: def ingredients(request): objects = Ingredient.objects.all()[:50] return render(request, 'template.html', {'objects': objects} models.py: class Ingredient(models.Model): stock_by = models.IntegerField(null=False) unit = "" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) unit_type = { 1: 'Units', 2: 'Kilograms', 3: 'Litters' } self.unit = unit_type[IntegerField.to_python(self.cost_by)] Error: TypeError at /Ingredient/ to_python() missing 1 required positional argument: 'value' (Value is None). I think it's clear what I'm trying to achieve. Just a String attribute which will take the name of the unit value (represented by integers in db). -
Trying to understand why Selenium cannot see Binary at '/app/.apt/usr/bin/google-chrome' error despite solutions tried - using Heroku
I am trying to use Selenium and Heroku I've run into a common error: selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome' I've come across this article as to why this may be happening: WebDriverException: Message: unknown error: no chrome binary at C:/.../Chrome/Application/chrome.exe with ChromeDriver Selenium and Python I am using Selenium 3.141.0 It suggests that Chromedriver is unable to locate the binary chrome.exe. It also suggests to ensure that I am not using the deprecated option: ChromeOptions() and don't believe I need to use the keyword argument executable_path as I am launching it from Heroku where I would use '/app/.apt/usr/bin/google-chrome' path. Other solutions I've come across suggests various different configurations and I feel like I have everything configured correctly but maybe not. What else could be the reason that I am unable to get this to work? Buildpacks https://github.com/heroku/heroku-buildpack-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver Heroku Config Variables GOOGLE_CHROME_BINARY = "/app/.apt/usr/bin/google-chrome" CHROMEDRIVER_PATH = "/app/.chromedriver/bin/chromedriver" Options class WebDriver: def __init__(self): self.GOOGLE_CHROME_BINARY = config('GOOGLE_CHROME_BINARY') self.CHROMEDRIVER_PATH = config('CHROMEDRIVER_PATH') self.chrome_options = Options() self.chrome_options.add_argument("--disable-dev-shm-usage") self.chrome_options.add_argument('--no-sandbox') self.chrome_options.binary_location = self.GOOGLE_CHROME_BINARY self.chrome_options.add_argument("headless") self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, options=self.chrome_options) Any help even in just helping me understand what's going on better would be much appreciated -
How can I fix the problem:"TypeError: filter() takes no keyword arguments",please help me
I have followed the official tutorial of Django to make a poll app, but I have gotten an error: File "C:\Users\oliver\Desktop\TPA Part 5\mysite\polls\views.py", line 17, in get_queryset return Question.objects,filter( TypeError: filter() takes no keyword arguments The code(The code is at mysite\polls\views.py and the required changing action is on part 5 of the tutorial): class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future) """ return Question.objects,filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] Could you please help me? The platform: Windows 10 ,Django version: 3.0.4 ,Python version: 3.8.2 ,The database is MySQL8.0 and the tutorial:Tutorial,my code files:Files -
How to get image data from Django form which returns False for is_valid()
How to save image in Django form that is not validated. I could able to save data of Charfield using title = form_name["title"].data Other data that are passed are getting saved but image is not getting saved. How to fix it. form = forms.FormName() if request.method == "POST": form_name = FormName(data = request.POST) title = form_name["title"].data thumbnail = form_name["thumbnail"].data content = form_name["content"].data tags = form_name["tags"].data instance = htmlpage(title=title, thumbnail=thumbnail, content= content, tags=tags, by=request.user) instance.save() -
Django: Iterate queryset over list
I cannot iterate over Querysets. Below produce an error meanwhile if I would manually type: return chain(queryset.filter(company__contains=1, queryset.filter(company__contains=2) it works. How do I solve this?, I cannot find anything online. Key here I that I do not know the size of the list beforehand and cannot use the manual notation, such as 1 | 2 from itertools import chain class ProductListView(ListView): model = Product template_name = 'product_list.html' def get_queryset(self): queryset = super(ProductListView, self).get_queryset() query = [] for g in [1,2]: query.append(queryset.filter(company__contains=g)) return chain(tuple(query)) -
Django is not rolling back with atomic transactions
I have the following models: class InventoryAction(CustomModel): action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción")) action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción")) action_object = GenericForeignKey('action_content_type', 'action_object_id') timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora")) class Meta: verbose_name = _("Acción de Inventario") verbose_name_plural = _("Acciones de Inventario") def __str__(self): return "{}-{}/{}/{}".format(self.id, self.action_content_type.model, self.action_object_id, self.timestamp) class InventoryActionProduct(CustomModel): inventory_action = models.ForeignKey(InventoryAction, on_delete=models.PROTECT, related_name='products', verbose_name=_("Acción de Inventario")) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='actions', verbose_name=_("Producto")) amount = models.FloatField(verbose_name=_("Cantidad")) class Meta: verbose_name = _("Producto de Acción de Inventario") verbose_name_plural = _("Productos de Acciones de Inventario") def __str__(self): return "[{}] {}/{}/{}".format(self.id, self.inventory_action.action_content_type.model, self.product.name, self.inventory_action.timestamp) class InventoryActionItem(CustomModel): inventory_action_product = models.ForeignKey(InventoryActionProduct, on_delete=models.PROTECT, related_name='items', verbose_name=_("Producto de Acción de Inventario")) product_item = models.ForeignKey(ProductItem, on_delete=models.PROTECT, related_name='invetory_action', verbose_name=_("Artículo")) class Meta: verbose_name = _("Artículo de Acción de Inventario") verbose_name_plural = _("Artícuos de Acciones de Inventario") def __str__(self): return "[{}] {}/{}".format(self.id, self.inventory_action_product.product.name, self.product_item.serial_number) class InventoryInput(CustomModel): repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén")) class Meta: verbose_name = _("Entrada de Inventario") verbose_name_plural = _("Entradas de Inventario") def __str__(self): return "{}-{}".format(self.id, self.repository) KARDEX_INPUT = 'INPUT' KARDEX_OUTPUT = 'OUTPUT' KARDEX_CHOICES = ( (KARDEX_INPUT, _("Entrada")), (KARDEX_OUTPUT, _("Salida")), ) class Kardex(CustomModel): type = models.CharField(max_length=6, choices=KARDEX_CHOICES, verbose_name=_("Tipo de Movimiento")) repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='kardex', verbose_name=_("Almacén")) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='kardex', … -
Django Rest Framework filter - Select a valid choice
I encountered such an error when using django rest framework filter. I want to return 0, is it possible to fix this? # http://localhost:8000/api/v1/target/?project=TEST-00002 # RESPONSE 400 Bad Request { "project": [ "Select a valid choice. That choice is not one of the available choices." ] } Definitions and test cases are below. ## Definition class Project(models.Model): project_number = models.CharField(max_length=255, unique=True, null=False, blank=False) project_name = models.CharField(max_length=255, null=False, blank=False) class Target(models.Model): project = models.ForeignKey(Project, db_column='project_number', to_field='project_number', on_delete=models.CASCADE, null=False, default=None) target_name = models.CharField(max_length=255, null=False, default='') comment = models.TextField(default='', blank=True, null=False) class TargetViewSet(viewsets.ModelViewSet): queryset = Target.objects.all() serializer_class = TargetSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ['id', 'project'] class TargetSerializer(serializers.ModelSerializer): class Meta: model = Target fields = '__all__' read_only_fields = ('created_at', 'updated_at', 'delete_at') ## TEST DATA { "hits": { "total": 2, "next": null, "previous": null, "hits": [ { "id": 1, "project": "TEST-00001", "target_name": "bob" }, { "id": 2, "project": "TEST-00001", "target_name": "mary" } ] } } ## TEST ## http://localhost:8000/api/v1/target/?project=TEST-00002 ## 400 bad request { "project": [ "Select a valid choice. That choice is not one of the available choices." ] } ## http://localhost:8000/api/v1/target/?project=TEST-00001 ## no problem { "hits": { "total": 2, "next": null, "previous": null, "hits": [ { "id": 1, "project": "TEST-00001", "target_name": "bob" … -
Should I Use Relational Database OR Non-Relational Database For My Application
I am in the early stages of building a music/video streaming app similar to Tidal/Spotify but for a different niche of artists. I have a somewhat basic question: I am afraid I don't want to make the mistake of building a database that can't scale linearly later on. I have decided I am going to be using Google Cloud Platform. I want to use Google Spanner because it scales very well and is relational (which my data is going to be, I am assuming. Playlists, library, users, artists... can be schemed relationally unless I am not seeing something I should be seeing). Anyways, I see that Google Spanner is really expensive especially for new applications that don't need that scaling option that early on. So my question is should I go with Cloud SQL with Postgres and if whenever if ever this app grows to a significant number of users, then migrate to Google Spanner. Or should I go with a non-relational database like BigTable or Datastore/Firebase that will scale by itself later on and also isn't expensive at the beginning. What databases would you use if you were asked to build this app that is required to scale? I … -
Django models AttributeError: 'User' object has no attribute 'set_attributes_from_name'
I am trying to create a simple chat app with Django and am working on creating the models right now: class User(models.Model): uuid = models.CharField(max_length=10) name = models.CharField(max_length=20) tag = models.IntegerField() creation = models.DateTimeField() status = models.IntegerField(default=0) login = LoginInfo() class Room(models.Model): users = ArrayField(User()) With the above code, I get the following error: AttributeError: 'User' object has no attribute 'set_attributes_from_name' Am I using ArrayField wrong? Does the User class need an extra method called set_attributes_from_name? I'm using postgresql for the databse management. -
Learning Postress for my Django App on Heroku
my app is ready to go live but I tried to deploy on Heroku and their Postgress DB keeps old fields values. I migrated, tried to reset the Heroku DB but still I can see the reason from the error in my log but cannot get hold on it. I need an advice from your own experience. Should I learn Postgress and it will make my life easier or is there a better path ? I'm happy to go full postgres for few days but I want to be sure I dig in the right place. Tks so much for your POV. -
Django forms widget renderer
I am porting some code from Django 1.9 to 1.11. There is the following form: class FruitForm(FormFieldMixin, forms.Form): choices=( ("app", "Apple"), ("pea", "Pea, not Pear"), ), widget=forms.RadioSelect(renderer=CustomRadioFieldRenderer), ) this fails in 1.11 with: TypeError: __init__() got an unexpected keyword argument 'renderer' looking at the source code, RadioSelect in 1.9 inherits from RendererMixin which indeed accepts a renderer argument. RadioSelect in 1.11 inherits only from ChoiceWidget which in turn inherits from Widget. Widget's render accepts a renderer. This is in agreement with the Django release notes for 1.11. So the new way would be to pass a renderer when the Widget render is being called. There are some oblique guidelines here but I cannot imagine how one would use the Widget.render directly. I do not want to set a universal form renderer, just for this one class. In summary, how do I do that class, with a custom widget renderer in 1.11 where we do not have a renderer argument. Thank you. -
Apache web server static files for IP
I am trying to server static files via apache. Its working when I do localhost/static/index.html but when i try 192.0.0.1/static/index.html its not working. where i can specify that private ip for it to work in my lab.am using ubuntu, and trying to run django project. -
Django - WSGI script cannot be loaded as Python module
This is a well-known issue it seems but I have spent 8 hours trying to fix the issue without any success. I have been running a Django project with Apache2 on this VPS before, this issue occurred when I deployed new code and ran a sudo apt-get update. I now receive an Internal server error when trying to reach the website. I am desperate, does anyone have a suggestion of what could have happend? What I have installed on my VPS - sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 - sudo apt-get install mysql-server - sudo mysql_secure_installation - sudo apt install git - pip3 install virtualenv - pip3 install django - sudo apt-get install libmysqlclient-dev - pip3 install mysqlclient Error log [Fri Mar 06 22:47:29.96579 2020] mod_wsgi (pid=4877): Target WSGI script '/var/www/project/project/wsgi.py' cannot be loaded as Python module. [Fri Mar 06 22:47:29.965710 2020] mod_wsgi (pid=4877): Exception occurred processing WSGI script '/var/www/project/project/wsgi.py'. [Fri Mar 06 22:47:29.965712 2020] mod_wsgi (pid=16955): Target WSGI script '/var/www/project/project/wsgi.py' cannot be loaded as Python module. [Fri Mar 06 22:47:29.965917 2020] mod_wsgi (pid=16955): Exception occurred processing WSGI script '/var/www/project/project/wsgi.py'. [Fri Mar 06 22:47:29.967013 2020] Traceback (most recent call last): [Fri Mar 06 22:47:29.967585 2020] File "/var/www/project/project/wsgi.py", line 17, in … -
Python muiltithreading is mixing the data of different request in django
I am using python muiltithreading for achieving a task which is like 2 to 3 mins long ,i have made one api endpoint in django project. Here is my code-- Def myendpoint(request): Print(hello) Lis = [ args ] Obj = Model.objects.get(name = jax) T1 = MyThreadClass(lis, obj) T1.start() T1.deamon = True Return httpresponse(successful, status 200) Class MyThreadClass(Thread): Def __init__(self,lis,obj): Thread.__init__(self) Self.lis = lis Self.obj = obj Def run(self): For i in lis: Res =Func1(i) Obj.someattribute = res Obj.save() Def Func1(i): Some big codes Context =func2(args) Return context By this muiltithreading i can achieve the quick response from the django server on calling the endpoint function as the big task is thrown in another tread and execution of the endpoint thread is terminated on its return statement without keeping track of the spawned thread. This part works for me correctly if i hit the url once , but if i hit the url 2 times as soon as 1st execution starts then on 2nd request i can see my request on console. But i can get any response from it. And if i hit the same url from 2 different client at the same time , both the individual datas are … -
Django template time filter not rendering
I have a little issue with Django's template not really rendering the time format as I'd like it to, following the documentations here proved to be a bit troublesome as it didn't work. Original Code: <p>Obtained this item on {{date_variable|date:"M j, Y"}} at {{time_variable|time}}</p> Tried these two time filter formats as shown below which are given by the Django's documentation. {{time_variable|time}} {{time_variable|time:"TIME_FORMAT"}} They represent the same thing as stated by the documentations. I even went as far as to try different formats i.e. {{time_variable|time:"h:i A"}}, {{time_variable|time:"P"}} etc. but none of it rendered in the web application. One solution I miraculously found was by removing the time filter {{time_variable}} and it showed the time entered from the form except the AM/PM. However, I need to display the AM/PM, looking to try for other solutions. Django version used is 2.2.2. Note: I have tried other solutions that are on stackoverflow but it seemed none of them worked, I don't really know why either as the information is entered through Django's form template, not processed or changed. -
How to make Django Redis cache shared between clients and sessions
This is probably quite related to the way Django uses Redis cache. I installed the debug toolbar and I watched the number of SQL request vs the cached content. Note that I'm using a Kubernetes cluster. So, this is what I do: 1 - I visit a page, I see 40 SQL requests. 2 - I refresh it, I see 40 SQL requests. 3 - I refresh it again, I see 1 SQL request - the cache start working from the second refresh. 4 - At this step, the page should be stored in the redis cache. To test this, I open a new private window ans visit the same page: I see 40 SQL requests! The problem is here. If I'm able to see that the page was cached, why opening a private window doesn't use the same cache ? If cache is only related to the user session, what's the benefit ? Is there a way to create a shared cache between all users ? I use django_redis.cache.RedisCache as a backend with these options: "CLIENT_CLASS": "django_redis.client.DefaultClient", "PICKLE_VERSION": -1, # Use the latest protocol version "SOCKET_CONNECT_TIMEOUT": 5, # in seconds "SOCKET_TIMEOUT": 5, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": … -
How to embed a Django website in external iframe
I would like to embed my Django website in a specific external website (not any website). I read a lot of docs and I don't understand if I have to use django-csp or X_FRAME_OPTIONS (which seems depreciated), or both to be compatible with every navigators. I tried to install and setup django-csp but in that case all of the ressources are blocked. CSP_DEFAULT_SRC = ("'none'", 'https://example.com') CSP_STYLE_SRC = ("'self'" ) CSP_SCRIPT_SRC = ("'self'" ) CSP_IMG_SRC = ("'self'" ) CSP_FONT_SRC = ("'self'" ) Here is the configuration : Django + REST Framework + React Thanks a lot! -
Dynamically getting an attribute from an objet to call a function based on that attribute
I'm inspecting an object and looking for a ManyToMany field that's of model "Risk", and then after that I want to call the obj.somefieldname.add() method. This is what I have so far for field in [f for f in obj.__class__._meta.get_fields() if isinstance(f, models.ManyToManyField) and (f.related_model._meta.object_name == Risk._meta.object_name)]: print(obj[field.name].add(...)) I can get it to fetch the appropriate fieldname, but I have no idea how to call the add function on this. Normally if it wasn't a many to many field I could just setattr but I'm in a bit of a loss as to how to do this. Also is there a better way to do the discovery than my approach? -
allign logged in user to form
I created a simple app where you can create poll, after login and see your polls in view. The problem is that i can't allign logged in user to my object. It worked fine when i had separate forms to create question and choice, but i want to do dynamic form and have these two forms in one view. I came up with that: forms.py class CreateChoiceForm(forms.ModelForm): choice_0 = forms.CharField(required=True) choice_1 = forms.CharField(required=True) class Meta: model = Question fields = ['question_text'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choice = Choice.objects.filter( question=self.instance ) for i in range(len(choice) + 1): field_name = 'choice_%s' % (i,) self.fields[field_name] = forms.CharField(required=False) try: self.initial[field_name] = choice[i].choice except IndexError: self.initial[field_name] = "" field_name = 'choice_%s' % (i+1,) self.fields[field_name] = forms.CharField(required=False) def save(self, commit=True): question = self.instance question.question_text = self.cleaned_data['question_text'] question.choice_set.all().delete question.save() for i in range(2): choice = self.cleaned_data['choice_%i' % (i)] Choice.objects.create(question=question, choice_text=choice) def get_interest_fields(self): for field_name in self.fields: if field_name.startswith('choice_'): yield self[field_name] but now i've got this error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/polls/createPoll/ Django Version: 2.2.5 Python Version: 3.6.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'pollapp'] Installed 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'] Traceback: File "C:\Users\MaineKomputere\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py" in _execute 84. return … -
Selenium error: no chrome binary at '/app/.apt/usr/bin/google-chrome' for deployment to Heroku via Django
I am getting an error with Selenium deployed to Heroku via Django: selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome'. I feel like I've followed the steps exactly of similar problems/solutions but I'm still getting the same error. Is there anything else I can try to fix the issue? I don't understand why Selenium fails to see the Chrome Binary. Selenium options, config vars and full traceback below Builpacks: https://github.com/heroku/heroku-buildpack-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver Heroku Config Variables: GOOGLE_CHROME_BINARY = "/app/.apt/usr/bin/google-chrome" CHROMEDRIVER_PATH = "/app/.chromedriver/bin/chromedriver" Selenium options: from decouple import config class WebDriver: def __init__(self): self.GOOGLE_CHROME_BINARY = config('GOOGLE_CHROME_BINARY') self.CHROMEDRIVER_PATH = config('CHROMEDRIVER_PATH') self.chrome_options = Options() self.chrome_options.add_argument("--disable-dev-shm-usage") self.chrome_options.add_argument('--no-sandbox') self.chrome_options.binary_location = self.GOOGLE_CHROME_BINARY self.chrome_options.add_argument("headless") self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, chrome_options=self.chrome_options) Traceback: File "/app/tcg/tcg_scraper.py", line 19, in __init__ self.driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, chrome_options=self.chrome_options) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__ desired_capabilities=desired_capabilities) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 151, in __init__ self.start_session(desired_capabilities, browser_profile) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 240, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 308, in execute self.error_handler.check_response(response) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: no chrome binary at '/app/.apt/usr/bin/google-chrome' -
Group by and count foreign key
I have a data model where I store certain Events that happen. Each Event is linked to an EventType. The data model roughly looks like this: class EventType(models.Model): name = ... class Event(models.Model): date = ... event_type = models.ForeignKey(EventType) What I would like to know is how often each event time appeared. I tried it like this: Event.objects.values('event_type', count=Count('event_type')) But the result looks like this: <QuerySet [{'count': 1, 'event_type': 71}, {'count': 1, 'event_type': 2}, {'count': 1, 'event_type': 71}, {'count': 1, 'event_type': 71}, ... So the entries did not get grouped. How can I make it such that they are grouped? -
Django test with different database user
I want to keep my unit test database completely separate from other environments including using different user credentials. This is mostly to prevent anyone from unintentionally running unit tests against the development database and mangling the dev data or wiping it out entirely if the --keepdb option isn't specified. The code below detects the "test" in the sys args and this seems to work but is very clunky. If I'm missing a better way to do this please advise. I have separate settings files for each environment so this will only be on the development server where the unit tests are run automatically and won't end up on any production servers. Environment: Django 1.11 Python 3.4.x MariaDB # this works but is clunky import sys if 'test' in sys.argv: DATABASES = { # test db and user 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev_db_test', 'USER': 'test_user', 'PASSWORD': 'secretpassword', 'HOST': 'the-db-host', 'PORT': '3306', 'TEST': { # redundant but explicit! 'NAME':'dev_db_test', }, } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev_db', 'USER': 'dev_db_user', 'PASSWORD': 'dev_password', 'HOST': 'the-db-host', 'PORT': '3306', 'TEST': { 'NAME':'dev_db_test', # redundant but explicit! }, } } I'd like to do this but unfortunately Django doesn't look at …