Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pipenv install djangorestframework_simplejwt fails
When I try to install simplejwt using this command: pipenv install djangorerestframework_simplejwt It is showing this: Installing djangorerestframework_simplejwt... Collecting djangorerestframework_simplejwt Error: An error occurred while installing djangorerestframework_simplejwt! Could not find a version that satisfies the requirement djangorerestframework_simplejwt (from versions: ) No matching distribution found for djangorerestframework_simplejwt I tried reinstalling python (Which I might not have done properly.) I tried these: https://apple.stackexchange.com/questions/284824/remove-and-reinstall-python-on-mac-can-i-trust-these-old-references also, https://osxuninstaller.com/uninstall-guides/properly-uninstall-python-mac/ -
Prevent Django from removing equals signs in URL
I have some verification emails links that look like the following: https://test.example.com/auth/security_questions/f=ru&i=101083&k=7014c315f3056243534741610545c8067d64d747a981de22fe75b78a03d16c92 In dev env this works fine, but now that I am getting it ready for production, it isn't working. When I click on it, it converts it to: https://test.example.com/auth/security_questions/f%3Dru&i%3D101083&k%3D7014c315f3056243534741610545c8067d64d747a981de22fe75b78a03d16c92/ This prevents react-router-dom from matching the correct URL, so a portion of the web application does not load properly. The link is constructed using the following. link = '%s/auth/security_questions/f=%s&i=%s&k=%s' -
How to get just one item from ForeignKey Model in django?
I have below two models in my app, class Question(models.Model): question_text = models.CharField(max_length=200) question_author = models.ForeignKey(User, on_delete=models.CASCADE) q_pub_date = models.DateTimeField('Date Question Published') def __str__(self): return self.question_text class Answer(models.Model): answer_text = models.CharField(max_length=5000) answer_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ans_auth') question = models.ForeignKey(Question, on_delete=models.CASCADE) a_pub_date = models.DateTimeField('Date Answer Published') def __str__(self): return self.answer_text I want to show latest questions on home page in a list. Each item in list will show question text and one answer out of many posted for that particular question. I am able to show question text but I am not able to find a way to get the answer item for every question item in my view below, def home(request): latest_question = Question.objects.order_by('-q_pub_date')[:15] -
Django - Save Canvas object as a PDF-File to FileField
(How) is it possbile to save a canvas object as a PDF-file in a FileField ? https://docs.djangoproject.com/en/2.0/howto/outputting-pdf/#outputting-pdfs-with-django views.py class SomeView(FormView): form_class = SomeForm template_name = 'sometemplate.html' def form_valid(self, form): item = form.save(commit=False) # create PDF filename = "somefile.pdf" p = canvas.Canvas(filename) p.drawString(100, 100, "Hello world.") p.showPage() p.save() # this will not work, but i hope there is another way # Error: 'Canvas' object has no attribute '_committed' item.file = p # save form item.save() return super(SomeView, self).form_valid(form) -
Cannot save new users due to ValueError, Django
I'm saving business hours to restaurants when they sign up on my platform but, I'm getting this error: "ValueError: save() prohibited to prevent data loss due to unsaved related object restaurant." It was working prior and changed after I dropped my tables to start a new migration. Here is where the error is pointing to: def restaurant_sign_up(request): user_form = UserForm(request.POST or None) restaurant_form = RestaurantForm(request.POST or None, request.FILES or None) if request.method == "POST": if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username = user_form.cleaned_data["username"], password = user_form.cleaned_data["password"], )) for i in range(1, 8): OpeningHours.objects.create( restaurant=new_restaurant, day_of_week=i, opening_time="08:00", closing_time="22:00" ) return redirect(restaurant_home) return render(request, 'restaurant/signup.html', { "user_form": user_form, "restaurant_form": restaurant_form, # "hours_form": hours_form }) The traceback points to the "closing_time="22:00"" as the issue. The hours of operations should just be created by default when This is how the models are set up: class OpeningHours(models.Model): WEEKDAYS = [ (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ] day_of_week = models.IntegerField(choices=WEEKDAYS) opening_time = models.TimeField() closing_time = models.TimeField() restaurant = models.ForeignKey('buddysapp.Restaurant', on_delete=models.CASCADE) def __str__(self): return self.get_day_of_week_display() class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') restaurant_name = models.CharField(max_length=500, blank=False) phone = … -
nginx not returning Cache-Control header from upstream gunicorn
I'm using WhiteNoise to serve static files from a Django app running under gunicorn. For some reason, the Cache-Control and Access-Control-Allow-Origin headers returned by the gunicorn backend are not being passed back to the client through the nginx proxy. Here's what the response looks like for a sample request to the gunicorn backend: % curl -I -H "host: www.myhost.com" -H "X-Forwarded-Proto: https" http://localhost:8000/static/img/sample-image.1bca02e3206a.jpg HTTP/1.1 200 OK Server: gunicorn/19.8.1 Date: Mon, 02 Jul 2018 14:20:42 GMT Connection: close Content-Length: 76640 Last-Modified: Mon, 18 Jun 2018 09:04:15 GMT Access-Control-Allow-Origin: * Cache-Control: max-age=315360000, public, immutable Content-Type: image/jpeg When I make a request for the same file via the nginx server, the two headers are missing. % curl -I -H "Host: www.myhost.com" -k https://my.server.com/static/img/sample-image.1bca02e3206a.jpg HTTP/1.1 200 OK Server: nginx/1.10.3 (Ubuntu) Date: Mon, 02 Jul 2018 14:09:25 GMT Content-Type: image/jpeg Content-Length: 76640 Last-Modified: Mon, 18 Jun 2018 09:04:15 GMT Connection: keep-alive ETag: "5b27758f-12b60" Accept-Ranges: bytes My nginx config is pretty much what is documented in the gunicorn deployment docs, i.e. I haven't enabled nginx caching (nginx -T | grep -i cache is empty) or done anything else I would think is out of the ordinary. What am I missing? -
What's wrong with my paypal invoice?
I have a little problem with making paypal invoices using paypal sdk in my django project. when I trying to execute this code invoice_id = '' invoice = Invoice({ "merchant_info": { "email": '', # You must change this to your sandbox email account "first_name": str(merchant.first_name), "last_name": str(merchant.last_name), "business_name": str(merchant_full_name), "phone": { "country_code": "001", "national_number": str(merchant.phone) }, "address": { "line1": str(merchant_address.address), "city": str(merchant_address.city), "state": str(merchant_address.state), "postal_code": str(merchant_address.zip_code), "country_code": "US" } }, "billing_info": [{"email": buyer.paypal_address}], "items": [ { "name": "Slab", "quantity": 1, "unit_price": { "currency": "USD", "value": float(slab.price) } } ], "note": "Invoice for slab", "payment_term": { "term_type": "NET_45" }, "shipping_info": { "first_name": buyer.first_name, "last_name": buyer.last_name, "business_name": str(buyer_full_name), "phone": { "country_code": "001", "national_number": str(buyer.phone) }, "address": { "line1": str(buyer_address.address), "city": str(buyer_address.city), "state": str(buyer_address.state), "postal_code": str(buyer_address.zip_code), "country_code": "US" } }, "shipping_cost": { "amount": { "currency": "USD", "value": 0 } } }) if invoice.create(): print(json.dumps(invoice.to_dict(), sort_keys=False, indent=4)) invoice_id = invoice['id'] return invoice_id else: print(invoice.error) My server return me those errors INFO:paypalrestsdk.api:Request[POST]: https://api.sandbox.paypal.com/v1/oauth2/token INFO:paypalrestsdk.api:Response[200]: OK, Duration: 1.156739s. INFO:paypalrestsdk.api:PayPal-Request-Id: 660f7807-961f-4460-bafd-18412b489a91 INFO:paypalrestsdk.api:Request[POST]: https://api.sandbox.paypal.com/v1/invoicing/invoices INFO:paypalrestsdk.api:Response[401]: Unauthorized, Duration: 1.213655s. INFO:paypalrestsdk.api:Request[POST]: https://api.sandbox.paypal.com/v1/oauth2/token INFO:paypalrestsdk.api:Response[200]: OK, Duration: 1.53491s. As I understand it's a problem with paypal token, right? -
Django login not working. Only works for superuser/admin
I was using django-registration-redux for my registration backend earlier and everything worked fine. I then decided to change the registration backend to django's default registration django.contrib.auth and the registration has been working fine but the login doesn't work. However, the thing is, only my superuser acoount can login, every other user can't login, both the regular users and the ones with staff clearance. Below is the login section of my views.py def signin(request): if request.user.is_authenticated: return HttpResponseRedirect("/") form = LoginForm() errors = None if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') username = username.lower() password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if user.is_staff: return redirect('sweet:vendor_index') else: return redirect('sweet:index') else: errors = "Invalid Username or Password" return render(request, 'myregistration/signin.html', {'form':form, 'errors':errors}) Below is my signin.html {% extends "base.html" %} {% block title %}sign in{% endblock %} {% block content %} <h1>Sign in</h1> {% if form.errors %} <p class="error">Please correct the errors below:</p> {{ errors }} {% endif %} <form method="post" action="{% url 'myregistration:signin' %}">{% csrf_token %} <dl> <dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt> <dd>{{ form.username }}</dd> <dt><label for="id_password">Password:</label>{% if form.password.errors %} <span class="error">{{ form.password.errors|join:", " }}</span>{% endif %}</dt> <dd>{{ … -
Django auto_now=True for Timestamp not working when using normal mysql update query
I have a model like Main as shown below class Main(models.Model): Timestamp = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) ......................... ......................... Main.objects.filter(id=1).update(name="abc") is updating the Timestamp to current datetime but when I use mysql query UPDATE Main SET name="abc" WHERE id=1 is not updating the Timestamp to current Datetime Note: I want to use mysql query only. can anyone tell me how to do -
HyperlinkedModelSerializer writable related field
Models: class User(AbstractUser): ROLE_CHOICES = ( ('R', 'rider'), ('D', 'driver'), ) role = models.CharField(max_length=1, choices=ROLE_CHOICES) phone_number = models.CharField(max_length=10) cab = models.OneToOneField('Cab', on_delete=models.CASCADE, blank=True, null=True) class Cab(models.Model): color = models.CharField(max_length=20) rn = models.CharField(max_length=20) available = models.BooleanField(default=True) model = models.CharField(max_length=50) Driver Serializer: class DriverSerializer(serializers.HyperlinkedModelSerializer): cab = serializers.HyperlinkedIdentityField(view_name='cab_detail') class Meta: model = User fields = ('id', 'username', 'email', 'phone_number', 'cab', 'password') extra_kwargs = { 'password': {'write_only': True}, 'cab': {'required':True} } #depth = 1 def create(self, validated_data): password = validated_data.pop('password') instance = User(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance driver_list view @api_view(['GET', 'POST']) def driver_list(request): if request.method == 'GET': riders = User.objects.filter(role='D') serializer_context = { 'request': request, } serializer = DriverSerializer(riders, context = serializer_context, many=True) return Response(serializer.data) elif request.method == 'POST': #context = {'role':'D'} #serializer = DriverSerializer(data=request.data, context=context) serializer_context = { 'request': request, } serializer = DriverSerializer(data=request.data, context = serializer_context) if serializer.is_valid(raise_exception=True): serializer.save(role='D') return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This gives the following output on GET drivers/ The cab field points to cab object with same id as user object id [ { "id": 2, "username": "aditi", "email": "aditi@gmail.com", "phone_number": "8130022156", "cab": "http://127.0.0.1:8000/api/cabs/2" }, { "id": 7, "username": "test3", "email": "himanshu@gmail.com", "phone_number": "9976544776", "cab": "http://127.0.0.1:8000/api/cabs/7" }, I want the cab field … -
how to write multiple table name during inspection of specific table in django 2.0.7
when I first execute this command it create model in my model.py but when I call it second time for another table in same model.py file then that second table replace model of first can anyone told the reason behind that because I am not able to find perfect solution for that? $ python manage.py inspectdb tablename > v1/projectname/models.py when executing this command secondtime for another table then it replace first table name. $ python manage.py inspectdb tablename2 > v1/projectname/models.py -
DJANGO STATIC AND MEDIA FILES AWS S3
I have configured an S3 bucket to work with my django project, the static files(css,js) are all working fine. I've been trying to do have a user upload an image file to store in the S3 Bucket also, i've followed all tutorials but think the issue is with my form save. This is my save view.py def tour_create(request, template_name='tourguides/tour_form.html'): form = TourForm(request.POST or None) new_tour = form.save(commit=False) print(new_tour) data={} new_tour.title = request.POST.get('title', False) new_tour.length = request.POST.get('length', False) a = request.POST placesList = a.getlist('placesdj') final_places = ','.join(placesList) new_tour.places = final_places if form.is_valid(): new_tour.save() new_tour.placesdj.add(request.POST.get('placesdj', False)) form.save_m2m() messages.success(request, 'Tourguide added successfully.') return redirect('tour_list') return render(request, template_name, {'form': form }) The error im getting is the ValueError: The Tourguide could not be created because the data didn't validate. The line thats causes is the new_tour= form.save(commit=False) I have ensure the s3 bucket is set up correctly. This is my settings.py for the static and media files MEDIA_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION) DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage' STATIC_LOCATION = 'static' STATICFILES_LOCATION = 'app.storage_backends.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATIC_LOCATION) my storage_backends.py is like so from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.DEFAULT_FILE_STORAGE … -
How to return aggregated data with tastypie
I'm having hard times with trying to return aggregated data on GET request - I'm using django and tastypie. I can generate what i need in django shell: X.objects.using("myDB").values("some_name").annotate(Avg("number")) this is what I need in response on GET request, but in tastypie it doesn't work... Here's my model: class X(models.Model): some_name = models.CharField(max_length=128, blank=True, null=True) other_name = models.CharField(max_length=128, blank=True, null=True) another_name = models.CharField(max_length=255, blank=True, null=True) number = models.IntegerField() class Meta: managed = False db_table = 'some_table' Here's resource: class XResource(ModelResource): class Meta: queryset = X.objects.using("myDB").values("some_name").annotate(Avg("number")) resource_name = 'myResource' I'm trying to get a response which would look like this: {'meta': {'limit': 20, 'next': None, 'offset': 0, 'previous': None, 'total_count': 5}, 'objects': [{"some_name": "name_1", "number__avg": 100}, {"some_name": "name_2", "number__avg": 200}, {"some_name": "name_3", "number__avg": 300}, {"some_name": "name_4", "number__avg": 400}, {"some_name": "name_5", "number__avg": 500}]} But I'm getting this error: { "error_message": "'dict' object has no attribute 'pk'", "traceback": "Traceback (most recent call last):\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 227, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 467, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 499, in dispatch\n response = method(request, **kwargs)\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 1364, in get_list\n for obj in to_be_serialized[self._meta.collection_name]\n\n File \"C:\\django\\master\\lib\\site-packages\\tastypie\\resources.py\", line 1364, in <listcomp>\n for obj in … -
Django admin custom AdminURLFieldWidget widget misses the Browse button
I'm trying to customize Django admin and I need to create a custom URL displayed for a FileField record in the change_form template. So, by googling I've found the following recipe adpated from a customization of an image field found here. Here is my code: class MyAdminURLFieldWidget(URLInput): template_name = 'admin/widgets/url.html' def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(MyAdminURLFieldWidget, self).__init__(attrs=final_attrs) def get_context(self, name, value, attrs): context = super(MyAdminURLFieldWidget, self).get_context(name, value, attrs) context['current_label'] = _('Currently:') context['change_label'] = _('Change:') context['widget']['href'] = smart_urlquote('/DownloadView/' + str(value.instance.id) + '/attachment/') if value else '' return context class FilesAdmin(admin.ModelAdmin): list_display = ('id', '_animalid', '_filename', '_filedesc', '_ispublic', 'extra_info') search_fields = ('subjectid__animalid',) list_per_page = 50 def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'filename': request = kwargs.pop("request", None) kwargs['widget'] = MyAdminURLFieldWidget return db_field.formfield(**kwargs) else: return super(FilesAdmin, self).formfield_for_dbfield(db_field, **kwargs) However, the form display the field without the `Browse button: I would like to have something like the default: So, how can I make the Browse button to appear in my custom widget? -
Set up read-the-docs environment via script
I have an self hosted read-the-docs server which is able to build and to host documentation from different projects. It can be connected to my Git server with the use of the read-the-docs webinterface and everything works fine. What i am trying to do now is to set up the environment for a new documentation with a script which does some basic stuff to make project documentation easier. These points are already done: After creating a project, by starting the script: set the project folder set Programming language (script generates folders and files which are needed to generate a basic documentation on my readthedocs server with Sphinx, Doxygen or JsDoc) set up Git repository and upload to my Git server What is missing now in the script: set up the project on my read-the-docs server At the moment I have to set up the project on the readthedocs webinterface and connect it to my Git server. I hope that somebody has already some experience with this and could give me a hint. Thanks -
How to Filter ModelChoiceFilter by current user using django-filter
I'm using django-filter which is working great but I am having a problem filtering my drop down list of choices (which is based on a model) by the current user. It's a fairly basic and common scenario where you have a child table which has a many to one relationship to a parent table. I want to filter the table of child records by selecting a parent. This is all fairly easy, standard stuff. The fly in ointment is when the parent records are created by different users and you only want to show the parent records in the drop down list that belongs to the current user. Here is my code from filters.py import django_filters from django import forms from .models import Project, Task from django_currentuser.middleware import get_current_user, get_current_authenticated_user class MasterListFilter(django_filters.FilterSet): project = django_filters.ModelChoiceFilter( label='Projects', name='project_fkey', queryset=Project.objects.filter(deleted__isnull=True, user_fkey=3).distinct('code') ) class Meta: model = Task fields = ['project'] @property def qs(self): parent = super(MasterListFilter, self).qs user = get_current_user() return parent.filter(master=True, deleted__isnull=True, user_fkey=user.id) This bit works fine: @property def qs(self): parent = super(MasterListFilter, self).qs user = get_current_user() return parent.filter(master=True, deleted__isnull=True, user_fkey=user.id) This filters my main list so that only records that have a master flag set, have not been deleted and … -
DAL-yl is not defined
I am trying to implement autocomplete following django-autocomplete-light tutorial And I could confirm that Autocomplete view was created successfully typing url directly as below. However, when I test using form view, autocomplete is not working and get following error in console. Uncaught ReferenceError: yl is not defined Does anyone know what is causing this problem and how to solve this? html page {% extends "base.html" %} {% load crispy_forms_tags %} {% crispy document_form document_form.helper %} {% load staticfiles %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static 'css/form.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'vendor/css/select2.css' %}" /> <h3>Upload Project</h3> {% crispy form %} <script src="{% static 'vendor/js/select2.js' %}"></script> {% endblock %} forms.py from django import forms from project.models import html from django.forms import widgets from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from dal import autocomplete class DocumentForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(DocumentForm,self).__init__(*args,**kwargs) self.helper=FormHelper(self) self.helper.form_id='projectForm' self.helper.form_method='post' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model=html fields=['project','version','diff','program','location','certificate','user','html','idf','eso'] wdigets={ 'project':autocomplete.ModelSelect2(url='project:project-autocomplete') } class ProjectAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs=html.objects.all() if self.q: qs=qs.filter(project__istartswith=self.q) return qs -
Error: lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups
I have the following models: class Item(models.Model): name = models.CharField(max_length=255) ....... class ItemImage(models.Model): item = models.OneToOneField(Item, related_name='item_image', on_delete=models.CASCADE) and also, a custom Queryset(used as_manager): def get_list(self): qs = self.only('id', 'name', 'description') qs_image = ItemImage.objects.all().only('image', 'additional', 'item_id') qs = qs.prefetch_related(Prefetch('item_image', queryset=qs_image, to_attr='image')) return qs the corresponding View: class ItemListView(ListView): def get_context_data(self, *args, **kwargs): item_list = context['item_list'] if item_list: for item in item_list: .... change_image(image, IMAGE_TYPE_LIST) def get_queryset(self, *args, **kwargs): return Item.objects.get_list() I receive the error: 'image' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. The error is on change_image(image, IMAGE_TYPE_LIST), in which I just get the object and replace the image with a smaller image. Besides get_list I don't call other querysets that involves image and I have no idea what causes the error. -
TypeError: save() got an unexpected keyword argument 'max_length'
I have a simple model: class Contract(models.Model): address = models.CharField(blank=True, max_length=255, unique=True) logo = models.ImageField(upload_to='contracts', max_length=255) def __str__(self): return self.address def get_absolute_url(self): return reverse("contracts:detail", kwargs={"pk": self.pk}) When I try to save it through the admin, I get the following error: I do not override the save() method, and I do not save the object outside of the admin. What could be the problem ? -
Initiate the template form with stored data
I collect user info with the following template: <div class="row text-center vertical-middle-sm"> <h1>Profile</h1> <div class="row"> <div class="col-md-6"> <div class="row"> <div class="col-md-4 text-right"><span>Username:</span></div> <div class="col-md-8 text-left"><span>{{ user.username }}</span></div> </div> <div class="row"> <div class="col-md-4 text-right"><span>Gender:</span></div> <div class="col-md-8 text-left"><span>{{ user_profile.get_gender_display }}</span></div> </div> In the view, there's lot of hardtyping to initiate the data: else: user_form = UserForm(instance=request.user) user_profile_form = UserProfileForm( initial={'birthday':user_profile.birthday, 'telephone':user_profile.telephone, 'school':user_profile.school, 'company':user_profile.company, 'profession':user_profile.profession, 'country':user_profile.country, 'about_me':user_profile.about_me, }) context = {"user_form":user_form, "user_profile_form":user_profile_form,} return render(request, "account/edit_profile.html", context) How to refactor the initial={} shorter? -
Prevent Context from updating in Django
So my very little lack of django knowledge makes it a bit hard to explain exactly what's going on.I think specifically the lack of knowledge in regards to how this boilerplate/project/framework is set up makes it a bit hard for me explain the issue but I'll give it a try I'm trying to render a Django Template with a given context. Now I manage to render the template but the context keeps updating itself. How do I make the template differentiate between the contexts ? or how do I prevent the context from updating itself ? def render_stateTree(self,request,temp_context): c = RequestContext(request, temp_context) # Create a response response = TemplateResponse(request, 'admin/StateTree.html', c) # Register the callback response.resolve_context(temp_context) # Return the response return response def get_urls(self): from django.conf.urls import patterns, url, include if settings.DEBUG: self.check_dependencies() def wrap(view, cacheable=False): def wrapper(*args, **kwargs): return self.admin_view(view, cacheable)(*args, **kwargs) return update_wrapper(wrapper, view) # Admin-site-wide views. urlpatterns = patterns('', url(r'^$', wrap(self.index), name='index'), url(r'^logout/$', wrap(self.logout), name='logout'), url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'), url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True), name='password_change_done'), url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'), url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut), name='view_on_site'), url(r'^(?P<app_label>\w+)/$', wrap(self.app_index), name='app_list') ) # Add in each model's views. for model, model_admin in six.iteritems(self._registry): urlpatterns += patterns('', url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)) ) #urlpatterns += patterns('',url(r'statetree', … -
Why do i need to set kwargs as parameter of CBV in Django
While overriding get_context_data,2 parameters are passed self and **kwargs while the CBV already has kwargs at self.kwargs(which are arguments passed from URL to the CBV) Why do we need this extra kwargs(one passed to the function) Example of overriding and even updating the context dict with function kwargs as shown in line 64. -
Can't seek video with file size > 10MB in localhost - Django
I have an issue about Video in Django. I hope your guys help me to fix it. I have 2 videos. Video 1: smaller than 10MB, have URL: http://localhost:8000/media/users/2/videos/9.mp4 This video can be loaded and seeked normally, no error You can see this video: https://www.youtube.com/embed/u2XXkkpE_Ns Video 1: larger than 10MB, have URL: http://localhost:8000/media/users/2/videos/58.mp4 This video cannot be loaded and seeked normally. It load partially and I can't even seek it. Please see this error in video: https://www.youtube.com/watch?v=6RoVLUL__JQ What is this problem? Is this an issue coming by Server? -
Multiple Django apps used for multiple authentication role.
Using MySql in BackEnd. There are two roles, Customer and Vendor.I have to use custom authentication for both of them. I have generated two apps customer and vendor,i was successful in overwriting Django's AUTH_USER_MODEL by using class User(AbstractBaseUser): model in customer app which created the table customer_user replacing the auth_user table provided by Django in default. custom auth_user_model for customer Now similarly I want to create vendor_user table in the database, with custom authentication for Vendor App. -
Modify settings to skip tests through command line
I have a Django 1.11 app which has two types of tests: pytest tests and selenium tests. I am currently using tags to decide which set of suites will be run, but I would prefer it if the selenium tests are ignored by default, and then run by overriding something in the command line. So the command I run at the moment is python manage.py test but I want it to ignore the tagged selenium tests. I was thinking I could do something like this: from django.conf import settings @unittest.skipIf(getattr(settings,'SKIP_SELENIUM_TESTS', False), "Skipping Selenium tests") But then how could I make it so that I could change the value of SKIP_SELENIUM_TESTS via a single command in the command line? Any help would be much appreciated.