Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which database for python mysql or postgresql ?
postgresql or mysql I want to create a good web application with python and Django framework but I'm not sure which database i should use? I search on Google and i find postgresql is better but that Posts is for 2 years ago but now in 2018 which database is good ? I need a database that will not need to be changed later with another database Thanks -
Using reflection with Django models to determine module containing the choices?
Let's say I take the following code from the Django documentatation: class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) But instead I want to do: from student_app import choices class Student(models.Model): year_in_school = models.CharField( max_length=2, choices=choices.YEAR_IN_SCHOOL_CHOICES, default=choices.FRESHMAN, ) Is there anyway using reflection to determine which module the choices are imported from? For example: field = Student._meta.fields.get_field_by_name('year_in_school') choices_source = some_clever_function(field) print("Choices imported from '%s'" % choices_source) I want the output to be: Choices imported from 'student_app'. Obviously the clever function does not exist but hopefully clarifies what I'm trying to do. Thanks -
get any instance (if exist) or create new for any child of abstract model
I found myself repeatedly finding record matching some criteria and if none exists, then creating new one with those criteria matched. Basically that does get_or_create() method, but it fails, if more than one such record exists. I am doing this so often, that I do not want write the same similar code all over and instead use some simple function for that All my models are derived from one abstract BaseModel, so it would seem logical, to implement method get_first_or_create there, which would then return object of actual model fullfilling given criteria. In case of more such objects, it would return any one of them. It would also take care about all Exception checking and some other common stuff too in one place. I do not know, how to make it in the BaseModel. Something like class BaseModel(models.model): active = models.BooleanField(default=True) ... class Meta: abstract = True def get_first_or_create(*args,**kwargs): retval=ChildModel.objects.filter(*args,**kwargs).first() # ChildModel is ofcourse wrong, but what to use? if retval: return retval else: retval = ChildModel(*args,**kwargs) retval.save() return retval # actually make more Exceptions/sanity/whatever checks here # but this is core of the idea class Car(BaseModel): name = models.TextField(blank=True) color = models.TextField(blank=True) ... class Animal(BaseModel): cute=models.BooleanField(default=True) ... and then … -
How to save a file generated in view to the model?
I have a model.py: class SomeModel(models.Model): name = models.CharField(max_length = 30) file_field = models.FileField(upload_to=os.path.join(settings.MEDIA_ROOT,'strategies/')) and view.py def test(request): csv = get_csv(args) My function get_csv() returns string of csv. And I need to save this in my Model. I don't want to create a file and put existing url into my model, because I'll always need TO generate a new file name, but I know, it can be done automatically. Could you please advice me any way to solve this problem? -
How to configure Django with Webpack/React using create-react-app on Ubuntu server
I'm following this tutorial: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/ The tutorial describes how to set up a Django/React app using webpack. Everything works fine on my development machine but I have problems with the static files on a remote server (Ubuntu 16.04.4). These are my questions: 1) Why is my development version looking for the static files in localhost? 2) If I use Nginx/Passenger to serve the production version, the static files are not loaded in the browser even though the links look correct. Why is this? 3) Do I need to configure STATIC_ROOT for production and run collectstatic? Many thanks for any help! Here is more information and code: In order to make sure I've not made any typos, I've cloned the source code, switched to the branch 'part-1' and followed all the instructions in the README. I added 'xx.xx.xx.xx' to settings.py ALLOWED_HOSTS where xx.xx.xx.xx is my server's IP address. I added "proxy": "http://localhost:8000" to frontend/package.json. 1) Development version I'm running the development server with: ./manage.py runserver xx.xx.xx.xx:8000 I have also run 'npm run build' before starting the webpack server with 'npm run start' in the frontend folder. The problem: when I navigate in a browser to xx.xx.xx.xx:8000, I see a blank page. … -
Django & Javascript : Display picture in popup
I would like to get your help in order to handle pictures in HTML template. I'm using Django 1.11.16. I display pictures like this in my HTML template : <a href="{{ element.publication.cover.url }}"> <img class="popup_image" id="img_{{ element.publication.id }}" src="{{ element.publication.cover.url }}"> </a> So when I click on picture, it displays this one inside a full window because it goes to media url. I have to make click on browser previous button to come back in the template. My question is : How I can display the picture inside a popup ? So when I click on the thumbnail, it displays a popup with the picture and close button ? Thank you so much -
How to integrate wordpress blog in django app?
I want to render wordpress blog from http://my-wordpress-app.com/ in my django project i have use this package https://django-wordpress-api.readthedocs.io/en/latest/integration.html but it is not working I followed all the steps mentioned in document. But it gives 404 page when i hit blog url -
Django using nested resultset in template
I am trying to implement a 2 (or 3-tiered) collapsible navigation in a Django system (that I am extremely unfamilair with) that would looks as follows: - Type 1 -- Sub_Type1 -- Sub_Type2 --- Sub_Sub_Type1 I have a model that (in a simplified form) looks as follows, where the Subactivity and Subsubactivity tables and values are newly added: class Activity(models.Model): activity_type = models.CharField(max_length=50) def __str__(self): return self.activity_type def __unicode__(self): return u"%s" % self.activity_type class Subactivity(models.Model): subactivity_type = models.CharField(max_length=50) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) def __str__(self): return self.subactivity_type def __unicode__(self): return u"%s" % self.subactivity_type class Subsubactivity(models.Model): subsubactivity_type = models.CharField(max_length=50) subactivity = models.ForeignKey(Subactivity, on_delete=models.CASCADE) def __str__(self): return self.subsubactivity_type def __unicode__(self): return u"%s" % self.subsubactivity_type class Foo(models.Model): barcode = models.CharField(max_length=200) name = models.CharField(max_length=200) activity = models.CharField(max_length=200, blank=True, null=True) activity_type = models.ForeignKey(Activity, on_delete=models.CASCADE) sub_activity_type = models.ForeignKey(Subactivity, blank=True, null=True) sub_sub_activity_type = models.ForeignKey(Subsubactivity, blank=True, null=True) confidential = models.BooleanField(default=True) The View that I have been trying (the original is commented away, which was a single tiered collapsible system). class IndexView(generic.ListView): template_name = 'gts/index.html' context_object_name = 'latest_foo_list' def get_queryset(self): # Tiered menu refactor try: resultList = [] for types in Foos.objects.values('Activity_type').distinct(): for sub_types in Foos.objects.values('Sub_activity_type').distinct(): if self.request.user.is_staff: resultList.append(Foos.objects.filter(Activity_type=types.values()[0], Sub_activity_type=sub_types.values()[0])) else: if Foos.objects.filter(Activity_type=types.values()[0], Sub_activity_type=sub_types.values()[0], confidential=0): resultList.append(Enzymes.objects.filter(enzyme_activity_type=types.values()[0], enzyme_sub_activity_type=sub_types.values()[0])) return resultList except: … -
django login using class based for custom user
here is my user model. class User (models.Model): username = models.CharField(max_length=50) # token = models.CharField(max_length=50) email_id = models.EmailField(max_length=50) password = models.CharField(max_length=50) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) and here is my views for creating user class UserView(APIView): def post(self,request): try: # RequestOverwrite().overWrite(request, {'token':'string'}) user_data = UserDetailSerializer(data=request.data) if not(user_data.is_valid()): return Response(user_data.errors) user_data.save() return Response("user created successfully",status=status.HTTP_201_CREATED) except Exception as err: print(err) return Response("Error while creating user") now what i want to do is to create a token when i post a user and that token is used later for login. also i want to validate user if it exist in database then make user authenticate. what should i do..?any suggestion below is my serializers.py class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','email_id','password','is_deleted','created_at','updated_at') extra_kwargs = { 'password': { 'required':True, 'error_messages':{ 'required':"Please fill this field", } } } -
Django: Not fetching the same object
I have a form where i am entering four details 'Persona Name', 'Persona Key' ,'Persona Key Label' and 'Persona Key Value' and on entering these values i am pressing Submit button which generates a GET request on my server. Following are django views:- def PersonaSave(request): persona_name = request.GET.get('persona_name',) persona_key = request.GET.get('key_name',) persona_key_value = request.GET.get('key_value',) persona_key_label = request.GET.get('key_label',) persona_submit = request.GET.get('Save',) return( persona_name , persona_key , persona_key_label , persona_key_value , persona_submit ) def TestPageView(request): x=PersonaSave(request) persona_name = x[0] persona_key = x[1] persona_key_label=x[2] persona_key_value=x[3] persona_submit=x[4] if(persona_name is None and persona_key is None and persona_key_label is None and persona_key_value is None): return render(request, 'dashboard/test_page.html') # Update function starts from here---- elif TestPersonaName.objects.filter(name=persona_name).exists(): t= TestPersonaName.objects.get(pk=persona_name) testpersona = TestPersona.objects.get(name=t) if testpersona.key == persona_key: testpersona.label= persona_key_label testpersona.value = persona_key_value #-----This is where update function ends If persona name is different then complete new TestPersonaName object and TestPersona object will be formed. For this the function starts here---- t=TestPersonaName(name=persona_name) t.save() testpersona = TestPersona(name=t,key=persona_key,label=persona_key_label,value=persona_key_value) testpersona.save() # --and ends here. return render(request,'dashboard/test_page.html') Now the problem is for the same persona name and same persona key two different TestPersona objects are being formed. For e.g If I enter persona_name = Ankit, key = 'city' and value = 'New Delhi' and … -
Add Billing Address Validation in Stripe.js
I have a Django Saleor based website which is using stripe.js to manage the payments. During the checkout process, I am collecting the billing address as part of the checkout process but once I enter valid card details (even though billing address is incorrect) the payment is still successful. On the stripe dashboard I can see that the street and postcode check failed but the payment is successful. Anybody know how I can enable this. This is a copy of my stripe.js: document.addEventListener('DOMContentLoaded', function () { var stripeInput = document.getElementById('id_stripe_token'); var form = stripeInput.form; var publishableKey = stripeInput.attributes['data-publishable-key'].value; Stripe.setPublishableKey(publishableKey); form.addEventListener('submit', function (e) { var button = this.querySelector('[type=submit]'); button.disabled = true; Stripe.card.createToken({ name: this.elements.id_name.value, number: this.elements.id_number.value, cvc: this.elements.id_cvv2.value, exp_month: this.elements.id_expiration_0.value, exp_year: this.elements.id_expiration_1.value, address_line1: stripeInput.attributes['data-address-line1'].value, address_line2: stripeInput.attributes['data-address-line2'].value, address_city: stripeInput.attributes['data-address-city'].value, address_state: stripeInput.attributes['data-address-state'].value, address_zip: stripeInput.attributes['data-address-zip'].value, address_country: stripeInput.attributes['data-address-country'].value }, function (status, response) { if (400 <= status && status <= 500) { alert(response.error.message); button.disabled = false; } else { stripeInput.value = response.id; form.submit(); } }); e.preventDefault(); }, false); }, false); My end goal is to make sure where the billing address doesn't match, these transactions are declined. -
django URL doubled
when i clicked the anchor tag going to the detailed view of my product the url is doubled. http://127.0.0.1:8000/products/products/t-shirt/ i think it is supposed to be like this http://127.0.0.1:8000/products/t-shirt/ List.html {% for object in object_list %} <a href="{{ object.get_absolute_url }}">{{object.title}}</a> <br> {{object.description}} <br> {{object.price}} <br> <br> {% endfor %} models.py class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=19, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # For url when you click a product def get_absolute_url(self): return "products/{slug}/".format(slug=self.slug) def __str__(self): return self.title urls.py from django.conf.urls import url from products.views import (product_view, product_detail_view, product_featured_view, ) urlpatterns = [ url(r'products/$', product_view), url(r'products/(?P<slug>[\w-]+)/$', product_detail_view), url(r'featured/$', product_featured_view), ] view.py from django.shortcuts import render, get_object_or_404, Http404 from .models import Product def product_view(request): queryset = Product.objects.all() context = { 'object_list': queryset, # 'featured': fqueryset } return render(request, 'products/list.html', context) def product_detail_view(request, slug=None, *args, **kwargs): try: instance = get_object_or_404(Product, slug=slug) except Product.DoesNotExist: raise Http404("Not Found..") except Product.MultipleObjectsReturned: queryset = Product.objects.filter(slug=slug) instance = queryset.first() context = { 'object': instance } return render(request, 'products/detail.html', context) def product_featured_view(request): queryset = Product.objects.filter(featured=True) context = { 'object_list': queryset } return render(request, 'products/featured-list.html', context) -
Heroku Deployment : ModuleNotFoundError: No module named 'django_summernote'
During the deployment for my python django blog app, this happening keeps continuing! so I don't know how to deal with it anymore. Actually I've found the sticking error ModuleNotFoundError: No module named 'django_summernote'. I solved many previous errors, h10, h14 but the ModuleNotFoundError still exists. in my Installed App in setting.py, it doesn't have any problem with it. So I couldn't catch up.. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles', 'templates', 'django_summernote', 'sorl.thumbnail', 'gunicorn', ] and below is the Error part State changed from crashed to starting 2018-12-10T13:25:48.417441+00:00 heroku[web.1]: Starting process with command `gunicorn djangoblog.wsgi:application --log-file - --log-level debug` 2018-12-10T13:25:48.000000+00:00 app[api]: Build succeeded 2018-12-10T13:25:51.553811+00:00 app[web.1]: [2018-12-10 13:25:51 +0000] [4] [DEBUG] Current configuration: 2018-12-10T13:25:51.553836+00:00 app[web.1]: config: None 2018-12-10T13:25:51.553838+00:00 app[web.1]: bind: ['0.0.0.0:47277'] 2018-12-10T13:25:51.553839+00:00 app[web.1]: backlog: 2048 2018-12-10T13:25:51.553841+00:00 app[web.1]: workers: 2 2018-12-10T13:25:51.553842+00:00 app[web.1]: worker_class: sync 2018-12-10T13:25:51.553844+00:00 app[web.1]: threads: 1 2018-12-10T13:25:51.553845+00:00 app[web.1]: worker_connections: 1000 2018-12-10T13:25:51.553847+00:00 app[web.1]: max_requests: 0 2018-12-10T13:25:51.553848+00:00 app[web.1]: max_requests_jitter: 0 2018-12-10T13:25:51.553850+00:00 app[web.1]: timeout: 30 2018-12-10T13:25:51.553851+00:00 app[web.1]: graceful_timeout: 30 2018-12-10T13:25:51.553852+00:00 app[web.1]: keepalive: 2 2018-12-10T13:25:51.553854+00:00 app[web.1]: limit_request_line: 4094 2018-12-10T13:25:51.553855+00:00 app[web.1]: limit_request_fields: 100 2018-12-10T13:25:51.553857+00:00 app[web.1]: limit_request_field_size: 8190 2018-12-10T13:25:51.553858+00:00 app[web.1]: reload: False 2018-12-10T13:25:51.553859+00:00 app[web.1]: reload_engine: auto 2018-12-10T13:25:51.553861+00:00 app[web.1]: reload_extra_files: [] 2018-12-10T13:25:51.553862+00:00 app[web.1]: spew: False 2018-12-10T13:25:51.553864+00:00 app[web.1]: check_config: False 2018-12-10T13:25:51.553865+00:00 app[web.1]: preload_app: False … -
django-rest-framework: int() argument must be a string, a bytes-like object or a number, not Deferred Attribute
I am creating sample rest API using django-rest-framework, I refereed the tutorial on there website https://www.django-rest-framework.org/tutorial/1-serialization/ I api is working fine when list and create new object but it throwing the exception during detail view(http://127.0.0.1:8000/cars/1) of object. I have added my code snippet below, Please let me know what wrong i am doing Models.py class Car(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=True, default='') price = models.TextField() class Meta: ordering = ('created',) serializers.py class CarsSerializer(serializers.ModelSerializer): class Meta: model = Car id = serializers.IntegerField(read_only=True) fields = ('id', 'created', 'name', 'price') Views.py @csrf_exempt def car_list(request): """ List all code cars, or create a new car. """ if request.method == 'GET': cars = Car.objects.all() serializer = CarsSerializer(cars, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CarsSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def car_detail(request, pk): """ Retrieve, update or delete a code cars. """ try: car = Car.objects.get(pk=pk) except Car.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = CarsSerializer(Car) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = CarsSerializer(Car, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': Car.delete() return HttpResponse(status=204) Urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), path('cars/', … -
Django and Javascript Dictionary with variable
I'm been looking all over but can't find how to write/access value from a dictionnary in javascript while writing the key dynamically. The below is a dictionnary of Json objects corresponding to specials itinaries. This is working : var geojson1 = {{ mydict["USA2019"]|safe }}; map.getSource('data-update').setData(geojson1); What I would like to do is pass as variable the name of the dictionnaries. I can select in my HTML several trip name and would like to get the json of the selected trip thanks to the value of "mysavedtrip" let mysavedtrip_select = document.getElementById('mysavedtrip'); mysavedtrip.onchange = function() { mysavedtrip = mysavedtrip_select.value; Is there a way to pass the variable in the dictionary in Javascript ? something like the below code ? var geojson = {{ mydict[ + mysavedtrip + ]|safe }}; map.getSource('data-update').setData(geojson); any idea ? -
Django default at database
So as I recently came to understand, the default that we specify in a Django field is merely for filling up pre-existing rows, and doesn't function as a "real" default value at the database level. This can be verified by looking up column_default from the database shell. If I understand correctly, default is used by Postgres to put in values when there is no input. If that is so, then we shouldn't be able to create a new object in Django without providing the default value, right? For ex - class MyModel(models.Model): name = models.CharField(max_length=255) status = models.BooleanField(default=True) # new field added For the above model, the default is used for only backfilling the newly added field for pre-existing rows. It doesn't actually set a default at the database level. column_name | column_default -------------+---------------- mymodel | But if that is so, I shouldn't be able to run this query - MyModel.objects.create(name='test') since there's no "real" default. But I can, and I don't understand why. Thank you! -
Connecting Django to MongoDB using Djongo Connector throws SSL Handshake exception
I'm trying to connect to MongoDb from my django application, but it throws [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) Exception. This is the same exception, that pymongo throws, when I connect to MongoDB., but I can get the connection working by appending &ssl_cert_reqs=CERT_NONE , at the end of my connection uri. Basically, the MongoDb that I'm trying to connect to, has ssl implemented in it, and I don't want to pass certificates to get the connection. However, in dango, it expects us to pass a dictionary of key-value pairs in the database configuration section of settings.py file. I tried specifying the same 'SSL':True,'SSL_CERT_REQS':'CERT_NONE' connection settings from my application, but it keeps on throwing same exception. Any help, how to configure certificates or just simply bypassing certificate check on client side to make the connection work is highly appreciated. Thanks ! -
request.FILES empty, though file is present in request
Following the example on the django website I'm trying to upload a file, perform checks on the contents, then feedback to the user and store the file contents. However, I'm having trouble with the request.FILES which is always empty. My code is as follows (note the output after the print statements): **forms.py** class UploadFileForm(forms.Form): data_import = forms.FileField() class Meta: model = Recipe fields = ('data_import',) **view** def recipes_list(request): template = 'recipes/recipes_list.html' if request.method == 'GET': user = request.user queryset = Recipe.objects.filter(user=user) form = UploadFileForm() return render(request, 'recipes/recipes_list.html', context={'recipes': queryset, 'form': form}) elif request.method == 'POST': print(request.FILES) # <MultiValueDict: {}> print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['...'], 'data_import': ['recette.json']}> form = UploadFileForm(request.POST, request.POST.data_import) if form.is_valid(): return HttpResponseRedirect(template) else: print(form.errors) **template** <form method="post"> {% csrf_token %} {{ form }} <button type="submit">submit</button> </form> The error I'm getting is: <ul class="errorlist"><li>data_import<ul class="errorlist"><li>This field is required.</li></ul></li></ul> But i can see that the file is uploaded, and is in the request.POST.get('data_import'). I would like to run validation on the form, but I can't do this if request.FILES is empty. I'm clearly doing something wrong, can someone please point me in the right direction? -
Is it okay to have a model property and a Django queryset annotation with the same name
Summary It appears we can create a property on a Django model, and add a queryset annotation with the exact same name. This appears to work, at least in our initial tests, effectively allowing us to filter a model property. However, I wonder if this is could lead to problems later on... Background We have an existing database with a FooBarModel with field bar, which is used in many places in our project code, e.g. in queryset filters. Now, for some reason, we need to add a new field, foo, which should be used instead of the bar field. The bar field still serves a purpose, so we need to keep that as well. If foo has not been set (e.g. for existing database entries), we fall back to bar. Implementation Now to make this work, we implement the model with a foo property, a _foo model field, a set_foo method and a get_foo method that provides the fallback logic (returns bar if _foo has not been set). However, as far as I know, a property cannot be used in a queryset filter, because foo is not an actual database field. _foo is, but that does not have the fallback … -
Define model permission in django raise error
I defined this in my djang model : class Meta: permissions = ( ("view_sth", "Can view sth"), ) but when I try to migrate this error raise: The permission codenamed 'view_sth' clashes with a builtin permission for model 'myapp.sth'. I couldn't find a solution on the internet for it -
Trouble with understanding a queryset in Django
I have a user profile page connected to a model which amongst other fields contain the following: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') That works like it should; the profile image connected to the user in question is loaded, and the distinction between users is made. What I'm trying to do now is connect a separate gallery model to the profile page, that the users may have a small image gallery to goof around with. The gallery model looks like this: class GalleryModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) img_1 = models.ImageField(default='default.jpg', upload_to='images') img_2 = models.ImageField(default='default.jpg', upload_to='images') img_3 = models.ImageField(default='default.jpg', upload_to='images') The views.py file looks like this: class ProfileDetailView(DetailView): model = Profile # Is something iffy here? Should this refer to the GalleryModel as well? template_name = 'account/view_profile.html' def get_object(self): username = self.kwargs.get('username') if username is None: raise Http404 return get_object_or_404(User, username__iexact=username, is_active=True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) username = self.object.username context['person'] = GalleryModel.objects.get(user__username=username) #loads username string context['img_1'] = GalleryModel.objects.last().img_1 context['img_2'] = GalleryModel.objects.last().img_2 context['img_3'] = GalleryModel.objects.last().img_3 return context I've tried a bunch of ideas (i.e. various approaches to the filter() and get() methods) and scrutinizing https://docs.djangoproject.com/en/2.1/topics/db/queries/ and sifting through what I could find on SO, but I … -
function get_form_kwargs() not being called
I'm trying to pass a parameter from a redirect to the CreateView and to the form. I have no problem retrieving the value from the redirect to the CreateView. But my issue is when trying get the value to the form. I'm overriding get_form_kwargs function of my CreateView but when I try to do operations from that function, I'm not able to get any result. I tried to do a print but the print won't display anything. class NoteCreate(LoginRequiredMixin, CreateView): login_url = 'login' model = Note form_class = NoteForm success_url = reverse_lazy('note:list') def get_form_kwargs(self): kwargs = super(NoteCreate, self).get_form_kwargs() kwargs.update({'file_id' : self.kwargs['file_id']}) print("im alivveeeeeeeEeeeeeeeeeeeee!") return kwargs the print statement doesn't seem to be working. It does not show anything in the console. I'm able to render the form with no errors in the console. -
Selenium with Django. Error import webdriver
I am using Selenium, inside a Django Project. I am using it in views.py, inside to my app, and I link it by url. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException def allyears(br): global browser path = os.environ['PATH'] browser = webdriver.Chrome(executable_path="/"+path+"/chromedriver) browser.get('https://www.address.com/recipes/)) I am trying to install Webdriver Chrome in a Django project. I linked to path environment, but not working. Anyway, when I will update it to a server, I can not link to a physical route. So, how can import webdriver.Chrome or webdriver.Firefox in Django? -
django-admin "ModuleNotFoundError:" after change in settings structure for development & production
Background I have recently started to learn Python Django. I read that it was good practice to have separate settings file for different environments. Consequently I have tried to implement something similar to what is describe in the "Simple Package Organization for Environments" section of this wiki: https://code.djangoproject.com/wiki/SplitSettings Problem When I now run a django-admin command I get a ModuleNotFoundError. Below I have copy pasted the error log I get for "django-admin check --deploy". "python manage.py runserver --settings=CollegeComp.settings.development" works fine. Things I've tried I was reading that I may have to reset the DJANGO_SETTINGS_MODULE environment variable in my virtual environment. I entered "set DJANGO_SETTINGS_MODULE=CollegeComp.settings.development" but I still get the same error. Python path When I type the following in the shell with my virtual environment activated: import sys print(sys.path) I get the following: ['C:\\Users\\myusername\\Documents\\UdemyDjango\\MyPersonalProject\\College-Project-master\\CollegeComp', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\python37.zip', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\DLLs', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\lib', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\lib\\site-packages'] Error log During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\Scripts\django-admin-script.py", line 10, in <module> sys.exit(execute_from_command_line()) File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 329, in run_from_argv connections.close_all() File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 220, in close_all for alias in self: File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 214, in __iter__ return … -
Run django-admin
I'm new to django and I would like to follow this tutorial: https://docs.djangoproject.com/en/2.1/intro/tutorial01/ Unfortunately, django-admin is not in my path. When I try to run the django-admin.py script directly, I have the following error: $ /usr/local/lib/python3.7/site-packages/django/bin/django-admin.py Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/bin/django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core Here is my configuration: System: macOS 10.13 Python: 3.7.0 (installed via Homebrew Django: 2.1.4 What am I doing wrong?