Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-shared-session is not working properly despite instructions
Does anyone have an example of using django-shared-session successfully? Per the instructions I've set the domains included the shared session tempalte tags etcetera. However, the login between domains isn't being shared despite the package saying it will share logins and session data. -
Django + PostgreSQL trigger causes "violates foreign key constraint"
In my Django... schema? I have a model structure for Products, their prices and a historic (kind of a log) of the prices the products went through. A bit like the following (simplified for this question): class ProductPricing(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2, help_text='price in dollars') product = models.OneToOneField('app.Product', related_name='pricing', null=False, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=100) # .pricing --> related name from 'ProductPricing' To keep the history of the prices, I have an OldProductPricing model, which is pretty much a copy of ProductPricing but allows multiple OldProductPricing(s) per product: class OldProductPricing(models.Model): valid_until = models.DateTimeField(null=False) product = models.ForeignKey('app.Product', related_name='+', null=False, on_delete=models.CASCADE) To make sure that each and every time that a product's price is modified or deleted, I try to create an entry in my OldProductPricing table. In order to do that, I have created a Posgresql trigger on update or delete: CREATE TRIGGER price_change_trigger AFTER UPDATE OR DELETE ON app.productpricing FOR EACH ROW EXECUTE PROCEDURE price_change_trigger_func(); The part of the trigger function that creates the insertion is as follows: CREATE OR REPLACE FUNCTION price_change_trigger_func() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE retval RECORD; BEGIN IF (TG_OP = 'DELETE') THEN retval := OLD; ELSE retval := NEW; END IF; RAISE LOG … -
How to start download immediately (but can't chunk data)?
I have a view like this: def download(request): response = StreamingHttpResponse([save_virtual_workbook(make_xl_workbook())], content_type="application/vnd.ms-excel") response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename return response But it waits to prompt the user to download until after make_xl_workbook has run. I was reading that I can't chunk out the data returned from make_xl_workbook because xlsx files are zipped. So I was hoping to start the download right away, then run the function and then pump the full data into the response once that function has run. I also tried this but it didn't seem to help: def download(request): def save_xl(): yield save_virtual_workbook(make_xl_workbook()) response = StreamingHttpResponse(save_xl(), content_type="application/vnd.ms-excel") response[u'Content-Disposition'] = u'attachment; filename="%s"' % filename return response -
Django - iterating through generic detailview context in html
Can someone help me understand when passing context to the HTML template using the detailview class why a for loop can't be used to iterate through the contents in the html page? I'm able to access the context variable directly by name to display the values: collection_details.Name or collection_details.date but when using a for loop to iterate, it doesn't work. views.py: class AcqSummaryView(DetailView): model = AcqSummary context_object_name = 'collection_details' def get_context_data(self, **kwargs): context = super(AcqSummaryView, self).get_context_data(**kwargs) return context html: {% for item in collection_details.items %} <p>{{ item }}</p> {% endfor %} -
How to delete Django object after countdown?
In the platform I am working on we want users to be able to set expiry times on the objects they create. After the countdown they set expires, that object should be deleted. How would you recommend doing this? -
Filtering Birthdays at specific date range inside date fields
I'm struggling to filter birthdays at born dates using django rest framework and django-filters (http://django-filter.readthedocs.io/en/master/). The biggest problem is that using django common filters I would need to do something like class birthdayFilter(django_filters.rest_framework.FilterSet): day = django_filters.RangeFilter(name="born_date__day") month = django_filters.RangeFilter(name="born_date__month") class Meta: Model = User fields = ['day','month'] The problem occurs if the user selects a time period like this: 27/11 to 1/12 In this case I would always receive an empty server response, because by default it would try to get dates with days bigger than 27 and lower than 1, which is always none. Another problem is if the user selects something like: 27/10 to 1/01 or 27/10 to 1/12 I think the solution is to get my hands dirty and write my own filter, but the documentation of django filters is not clear about how to do that. -
simple way to add existing users database(non django) to django
O.K. I have a headache with this problem. I have to different sites(non django) with login option and I would like to join in it into one new website based on django. Each of these two user databases consist of table with columns:(username, password, e-mail). The problem is, I just can not copy it to User table in Django as we all know django is very rigid about it, so I am trying to think a way, existing users would be able to login to site as nothing has changed. Is there any django/pythonic way to do so? I was thinking to create an app, which would take a foreign key to User model. Within User model I would create two users (database_1, database_2), so whenever a user from database 1 would login, e.g. JohnSmith, he would be connected as database_1 user, but so would JessicaSimpson if she would be in database 1. I am just thing to create Authentication and Authorization app as system app in some way... Is this a right way thinking? Would love to hear from professionals. Thanks -
Django inheritance - accessing child class fields
I have the following Django models: class Image(TimeStamp): hash = models.CharField(max_length=33, unique=True, editable=False) filesize = models.PositiveIntegerField(blank=True, null=True, editable=False) class Image1(Image): image = models.ImageField(upload_to='image1/') class Image2(Image): image = models.ImageField(upload_to='image2/') I want to be able to automatically compute filesize and hash upon image creation and the most reasonable place seems to me in a super class. However, I need to be able to access child class image field from the super class in order to compute hash and filesize. Is there a way to achieve this? I added this save method to the superclass, but of course it doesn't know about image: def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) self.hash = hashlib.md5(self.image.read()).hexdigest() self.filesize = self.image.size -
¿Custom pk in PUT method of Django ModelViewSet?
I´m trying to provide a url 'perfil/update' to the user for update hiself data in a Model called 'Perfil'. class Perfil(viewsets.ModelViewSet): serializer_class = perfilSerializer permission_classes = (IsAuthenticated) def get_queryset(self): queryset = PerfilModel.objects.all().filter(username=self.request.user) return queryset def put(self, request, pk, format=None): request.data['iduser'] = 6 serializer = perfilSerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How I would can set request.data['iduser'] = 6, for every update my iduser save as '6' only accessing to 'perfil/update'? Thanks! -
Add my own query parameters to django admin
I have a model that uses latitude and longitude fields for location. One of the queries that I want to run using query params is search around a specific radius. I have the queryset read and I override it: queryset = super().get_queryset(request) if 'radius' in request.GET: queryset = queryset.in_distance(request.GET['radius'], fields=['location__latitude',location__longitude'], points=[lat, lon]) return queryset When calling my admin page with /admin/dal/listing?radius=50 I get redirected to the admin without the query string. Followed Django's code and found this: # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them needs distinct(). If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) use_distinct = use_distinct or lookup_needs_distinct(self.lookup_opts, key) return filter_specs, bool(filter_specs), lookup_params, use_distinct except FieldDoesNotExist as e: six.reraise(IncorrectLookupParameters, IncorrectLookupParameters(e), sys.exc_info()[2]) In a nutshell because the query string is not a known field django gracefully panics and redirect a not filter admin page. What can … -
Django+gunicorn+nginx telegram webhook ssl trouble
I was trying to setup a django as webhooks for telegram bots. I create a ssl cert's using this commands: openssl genrsa -out webhook_pkey.pem 2048 openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem # In Common Name i type a server IP address Setup run gunicorn on port 800, setup proxy_pass in nginx to localhost:800. Web site work correctly, i can open it on browser and see my main page. Gunicorn starts with that command: gunicorn wsgi -b 127.0.0.1:800 # wsgi is django generated wsgi.py file My nginx.conf file: upstream django { server 127.0.0.1:800; } server { listen 80; listen 443 ssl; server_name 111.111.111.111 # these ip addres of my server ssl_certificate /path/to/webhook.cert; ssl_certificate_key /path/to/webhook.pkey; charset utf-8; client_max_body_size 10M; location /media { alias /path/to/media; } location /static { alias /path/to/static; } location / { proxy_pass http://127.0.0.1:800; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; } } I'm use a pyTelegramBotApi. from telebot import TeleBot bot = TeleBot(token) cert = open('webhook.cert', 'r') bot.remove_webhook() bot.set_webhook("https://111.111.111.111:80/user_bots/, certificate=cert) # I'm trying a differents ports cert.close() user_bots - it's some path for view in django, where a logging some data from request After i run this code i see … -
Can not pop up window when click field of raw_id_field in django admin
I use nested inline in admin, I need to install django-nested-inline==0.3.7 and django-salmonella==1.1 by pip but raw_id_field can not pop-up window when clicking field of raw_id_field, the website will direct the url, not pop window I can not fix the bug, Can someone help me?? Thank All -
should i have separate database for some model or shard them according users django
I'm sorry if my question is a little weird I'm new to databases should I just have a separate database like (comments, likes, tags) and shard them if they grow according to that or should I have all of them on a single database and shard them according to users. I really can't understand if I do either of them then how queries will work. -
uWSGI in an environment with Python 2 and Python 3
I started with python2 and uwsgi. Got my Django app running. I installed python3 and now I'm trying to get my app to run using python3. However it seems uwsgi doesn't want to run using python3 - even if passing it the venv flag for my virtualenv with python3. I have an emperor running a few vassals, if I include the venv flag said vassal doesn't work. On a test server, I simply removed python2, then aliased /usr/bin/python to python3. Which fixed the issue. But this seems like the wrong solution and would result in more significant downtime on my application. Whats the best way to get uWSGI to work with python3 without deleting python3? Is it really to create an alias? -
How to get started with dj-stripe 1.0?
What do I need to do to make payments available with Stripe and Django using dj-stripe 1.0? I found the documentation quite unforgiving for a newcomer to dj-stripe. I think I have gleaned that most configuration of e.g. subscription plans are done at stripe.com and updated via webhooks to my application. However, what do I need to implement myself and how? -
how to favorite in Django
i am trying to make a favorites button, where the user simply clicks the button and the spot_information is Favorited for the user, and can also remove the favorite. i am wondering why when i click the favorite button it loads a white page with the "({'success': True})" at the very top. also i am learning from Bucky Roberts GitHub and YouTube channel "theNewBoston", so i am sort of a beginner views.py def favorite(request, spot_id): spot = get_object_or_404(spot_information, pk=spot_id) try: if spot.a_favourite: spot.a_favourite = False else: spot.a_favourite = True spot.save() except (KeyError, spot.DoesNotExist): return JsonResponse({'success': False}) else: return JsonResponse({'success': True}) urls.py # favorite url(r'^(?P<spot_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), my index html code {% for spotinformation in all_spot_information %} ... <a href="{% url 'cityinfo:favorite' spotinformation.id %}" class="btn-favorite"> <button type="button" class="btn btn-primary"> <span class="glyphicon glyphicon-star-empty" {% if spotinformation.afavorite %}active{% endif %}></span>&nbsp; Favorite </button> </a> ... {% else %} {% endif %} thanks for your help. -
What's the best way to encode and decode QR code with Django?
We want to put a QR code on a school test paper. This QR code should contains information about the position of the answers (like the position of the squares in which the students are supposed to write the answers of the related questions) so that we can scan the copy of each student and retrieve with an algorithm all the answers. To do so we need to know the position of each answer and we were thinking to put a QR code that stores those informations. We found pyqrcode but we are not sure if this is the best solution. -
Importing Django authentication model in another project
ProjectA uses a custom authentication model CustomUser. ProjectB uses the default model, auth.User. One of the view classes in ProjectB needs to access some info in CustomUser in ProjectA. Upon trying to import the model I am getting the following error: "Manager isn't available. 'AppInProject1.CustomUser' has been swapped for 'auth.User'" AUTH_USER_MODEL has been properly specified in settings.py in each project. Any ideas on how to fix this? -
Python Django based query
You are asked to test an app for marks of Students in various Classes. You can make the following assumptions: Each student has a Unique Roll Number Has 3 exams in an year Has 4 subjects Student roll numbers are unique across classes & sections Please design the automated test cases, and the high level architecture for testing that works for iOS, Android & Web applications. -
How do I organize my models when creating a 'changelog' that depends on old data?
I'm trying to make a changelog which will note 1) the date-time an object is created/updated and 2) the objects themselves(strings) over a long course of time. Essentially, it "snapshots" the date-time along with the values of the objects at that specific time when .save() is called. Here is an example changelog I'm attempting to display: Oct. 24, 2017, 11:22 a.m "preference: bots", "preference: chocolate sundaes" Oct. 19, 2017, 12:04 p.m "preference: dogs", "preference: potatoes" Sep. 03, 2017, 01:22 a.m "preference: cats", "preference: cheese" The example above shows a single Changelog of three updates, and a single Changelog belongs to a single Profile object. What makes it difficult to establish is the fact that I'm not querying for the current date-time or objects' value, but all previous date-time and values must have persisted in the database to be displayed. Therefore, I thought I must create a model for not only the whole Changelog object, but also for the date-time, CLDate, and the objects, which I have called: CLPreference. Including Profile, here are all four of the models: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) main_preference = models.CharField(max_length=54, blank=True, null=True) secondary_preference = models.CharField(max_length=54, blank=True, null=True) timestamp = models.DateTimeField(auto_now=True) def __str__(self): … -
DRF haystack - More Like This returning zero results
File "/foo/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 105, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, 'No handler found for uri [/foo/modelresult/foo.item.288132/_mlt?search_size=0&mlt_fields=text&search_from=0] and method [GET]') [26/Oct/2017 14:44:34] "GET /api/search/288132/more-like-this/ HTTP/1.1" 200 5557 I'm trying to get the more-like-this function working and I'm getting the error above. The URL link appears in my API but returns zero values. -
pythod code with Django
I know this could be a repeated question for many of you but I have not been able to find a proper answer for this yet. I am a beginner to Django and Python. I have a python code which runs and produce output on cli at present but I want the same program to run its output on web. I read that for web django is best suitable framework and for this purpose I started to study django. I see in every tutorial people have discussed apps, views urls etc but not seen an example which integrate a python code with django. All I am looking for to understand how can I integrate my python script with Django and where do I place my code in Django project or app. Should I import it within views? if yes, then how to present my output to web. Here is the sample code I am running, it basically opens two files and run some regex to extract the desired information. import re def vipPoolFileOpen(): # function opens vip and pool config file and store them to vip_config and pool_config variables with open("pool_config.txt",'rb') as pool_config: pool_config = pool_config.read() pool_config = pool_config.split('ltm') with … -
'readonly' attribute doesn't work on my modelform
There is a 'league_type' field in my form and I want to make it 'readonly'. I used widget.attr['readonly'] = True but it doesn't work. model: class League(models.Model): league_types = ( ('league', 'League'), ('knockout', 'Knockout'), ) .... season = models.ForeignKey(Season, related_name = "league_season") league_type = models.CharField(max_length=10, choices = league_types, default ='league') ... modelform: class LeagueForm(forms.ModelForm): class Meta: model = League fields = ('title', 'league_type', 'season', 'status') widgets = {'season':forms.HiddenInput(),} view.py: if League.objects.filter(season = season, league_type = 'knockout').count(): form = LeagueForm(initial={'season': season, 'league_type': 'league'}) form.fields['league_type'].widget.attrs['readonly'] = True else: form = LeagueForm(initial={'season': season}) -
Django UserForm edit no username
I made a custom user interface for user. I can create the user and edit with no problem except that when in edit form, the previous user doesn't show (nor does the passwor1, but thats ok I guess). I don't know what I'm missing. It's a silly thing maybe, but I want it to be displayed. The form: class UserForm(UserCreationForm): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs = {'class': 'form-control',}) self.fields['password1'].widget = PasswordInput(attrs = {'class': 'form-control',}) self.fields['password2'].widget = PasswordInput(attrs = {'class': 'form-control',}) class Meta: model = User fields = ['username', 'password1', 'password2'] The view: class UserUpdateView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView): model = User form_class = UserForm template_name = 'security/user_create.html' success_message = "El usuario fue editado exitosamente." permission_required = ('user.can_update') def get_success_url(self, **kwargs): context = super(UserUpdateView, self).get_context_data(**kwargs) person_id = self.kwargs['person_id'] return reverse('people:person-detail', args = [person_id]) def get_context_data(self, **kwargs): context = super(UserUpdateView, self).get_context_data(**kwargs) context['person'] = Person.objects.get(pk = self.kwargs['person_id']) context['form_user'] = self.form_class return context The template: <div class="form-group"> <div class="col-sm-9"> {{ form_user.username }} </div> </div> Thanks! -
django error: unrecognized arguments:
I'm using django with VB Linux Red Hat. I've tried using the command "python manage.py runserver - 192.168.1.100:8000" in order to get access to my website. It worked fine until now, but then it showed me this message: manage.py runserver: error: unrecognized arguments: 192.168.1.100:8000" I think it has something to do with the settings.py file, I can't remember what exactly I've changed there. Here is the content of the settings.py file: """ Django settings for mysite project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o-g4ql*yum(+ollra+t%1x)$svtr!sd7mrcv=lj@_p&hrbq_&z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['192.168.1.100'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ) MIDDLEWARE_CLASSES = ( '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', ) ROOT_URLCONF = 'mysite.urls' WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, …