Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Django best practice on relative path from an AJAX request
I am currently failing at trying to read a CSV file stored in my django static repository from an AJAX request. Failed to load resource: http://127.0.0.1:8000/static/users/feedbacks/data.csv the server responded with a status of 404 (Not Found) Is there a best practice for this to work properly as well in production? here is the js: if (replayCSV){ $(document).ready(function() { $.ajax({ type: "GET", url: "/static/users/feedbacks/data.csv", dataType: "csv", success: function(data) {readData(data);} }); console.log(dataToRead); }); } And my django project structure looks like: main_repository -... -project_folder --app_folder ---static ----js -----therequest.js static_repository -static --users ---feedbacks ----data.csv -
Django rest api: How to handle method object has no attribute 'COOKIES' error
I have a django api. I want to enforce it to have csrf cookie using @ensure_csrf_cookie but I get error using this curl command: curl -i -c -H 'Accept: application/json; indent=4' -H 'Content-Type:application/json' -H 'Referer:https://dev.ga.coach' -X POST https://mydomain/users/:register/ -d "id=222111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames=" The error is: File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py" in _wrapped_view 141. result = middleware.process_request(request) File "/usr/local/lib/python3.5/dist-packages/django/middleware/csrf.py" in process_request 205. csrf_token = self._get_token(request) File "/usr/local/lib/python3.5/dist-packages/django/middleware/csrf.py" in _get_token 177. cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] Exception Type: AttributeError at /users/:register/ Exception Value: 'ApiUserRegister' object has no attribute 'COOKIES' My class in views.py is: class ApiUserRegister(APIView): authentication_classes = (BasicAuthentication,) permission_classes = () serializer_class = RegisterUserSerializer @method_decorator(csrf_exempt) @ensure_csrf_cookie def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint serializer.is_valid(raise_exception=True) data = serializer.data token = get_token(request) if User.objects.filter(id=data['id']).exists(): user = User.objects.get(id=data['id']) is_new = "false" resp_status = status.HTTP_200_OK else: user = User.objects.create(id=data['id'], firstname=data['firstname'], yearofbirth=data['yearofbirth'], lastname=data['lastname'], othernames=data['othernames']) user.save() is_new = "true" resp_status = status.HTTP_201_CREATED resp = {"user": serializer.get_serialized(user), "isnew": is_new, "csrftoken": token} return Response( resp, status=resp_status, headers = {"X-CSRFToken":token, "Referer":"https://mydomain/users/:register/"}) In settings.py I have: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( #'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework.authentication.SessionAuthentication', #'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ) } -
Embedding Tableau into Django Project
I am currently trying to connect Django with Tableau to use Tableau as a reporting unit to my (data input) Django project. Unfortunately I wasn't able to find anything on the web. Does anyone have experience to bridge Django and Tableau? Is it possible to share one Log-In or even pass User-Restriction information from Django to Tableau? Many thanks in advance for the help! -
Django Model form with a hidden field won't pass validation
When I have a field which is hidden but specified in the modelform, it fails to pass validation. The below form fails to pass validation for the postcode field, even though I pass in the postcode data in the constructor. How do I attach data to it to pass validation correctly so that it can save? eg class SupplyAddressForm(forms.ModelForm): full_address = forms.ChoiceField() def __init__(self, postcode, *args, **kwargs): super().__init__(*args, **kwargs) raw_addresses_data = get_full_address(postcode) addresses = raw_addresses_data['data']['addresses'] ........... self.fields['postcode'].initial = postcode def save(self, commit=False): address = super().save(commit=False) cd = self.cleaned_data full_address = cd['full_address'] full_address = json.loads(full_address) ...... return address class Meta: model = Address fields = [ 'supply_months', 'supply_years', 'postcode', 'residential_status', ] widgets = { 'postcode': forms.HiddenInput } -
Tests ran in gitlab-ci fail as Postgres can't been seen
Tests using gitlab-ci in docker fail as the Postgres service in not accessible. In my dev environment, I run tests successfully with: $docker-compose -f local.yaml run web py.test But in gitlab, the command - docker run --env-file=.env_dev $CONTAINER_TEST_IMAGE py.test -p no:sugar in the gitlab-ci.yaml file fails with: 9bfe10de3baf: Pull complete a137c036644b: Pull complete 8ad45b31cc3c: Pull complete Digest: sha256:0897b57e12bd2bd63bdf3d9473fb73a150dc4f20cc3440822136ca511417762b Status: Downloaded newer image for registry.gitlab.com/myaccount/myapp:gitlab_ci $ docker run --env-file=.env $CONTAINER_TEST_IMAGE py.test -p no:sugar Postgres is unavailable - sleeping Postgres is unavailable - sleeping Postgres is unavailable - sleeping Postgres is unavailable - sleeping Postgres is unavailable - sleeping Basically, it cannot see the Postgres service. The text Postgres is unavailable - sleeping comes from an entrypoint.sh file in the Dockerfile Below are some relevant files: gitlab-ci.yml image: docker:latest services: - docker:dind stages: - build - test variables: CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME before_script: - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build script: - docker build --pull -t $CONTAINER_TEST_IMAGE --file compose/local/django/Dockerfile . - docker push $CONTAINER_TEST_IMAGE pytest: stage: test script: - docker pull $CONTAINER_TEST_IMAGE - docker run --env-file=.env_dev $CONTAINER_TEST_IMAGE py.test -p no:sugar when: on_success Dockerfile: # ... other configs here ENTRYPOINT ["compose/local/django/entrypoint.sh"] entrypoint.sh: # ..... other configs here export DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@postgres:5432/$POSTGRES_USER function postgres_ready(){ … -
Submiting variable number of forms in Django
So I'm working on a web-based process simulator for a steel pickling plant. I have 6 different types of forms (from 6 different Models) on the same template, which should be all submitted by the same button. Here are the models that matter to my question: class Settings(models.Model): simulation = models.ForeignKey(Simulation, on_delete=models.CASCADE) final_time = models.IntegerField(default=3000) time_steps = models.IntegerField(default=50) film_thickness = models.FloatField(default=0.001) plate_thickness = models.FloatField(default=0.0005) plate_width = models.FloatField(default=10.0) number_of_pickling_tanks = models.PositiveSmallIntegerField(default=4) number_of_rinsing_tanks = models.PositiveSmallIntegerField(default=4) coil_temperature = models.FloatField(default=373.0) system_pressure = models.FloatField(default=100000.0) total_vaporization = models.FloatField(default=0.005) plate_velocity = models.FloatField(default=3.0) class PicklingTank(models.Model): settings = models.ForeignKey(Settings, on_delete=models.CASCADE) number = models.PositiveSmallIntegerField() volume = models.FloatField(default=30) concentration_hcl_initial = models.FloatField(default=180.84) concentration_fecl2_initial = models.FloatField(default=11.35) concentration_fecl3_initial = models.FloatField(default=5.81) temperature_initial = models.FloatField(default=323.15) hasextinlet = models.BooleanField(default=False) All of these are made forms as in: class SettingsForm(forms.ModelForm): class Meta: model = Settings fields = '__all__' class PicklingTankForm(forms.ModelForm): class Meta: model = PicklingTank fields = '__all__' I've already done my research on how to submit several forms with one button only (django submit two different forms with one submit button), but my problem is quite different: the number of PicklingTankForms changes dynamically depending on the value the user inputs in Settings.number_of_pickling_tanks (I am rendering one instance of the PicklingTankForm using my views.py and replicating it "on … -
Django POST handler receives different JSON than what I send
I have a Django POST handler like this: class FooListView(View): def post(self, request): fields = request.POST foo = self.Foo.objects.create(**fields) json = serializers.serialize('json', [foo]) return JsonResponse(json, safe=False) And a unit test like this: class FooTests(TestCase): def setUp(self): self.url = '/foo/' self.fields = {'foo': 'bar'} def test_post_data(self): response = self.client.post(self.url, data=self.fields) data = json.loads(response.json()) self.assertEqual(self.fields, data[0]['fields']) In IntelliJ, I set a break point on the first lines of test_post_data() and post(). Inspecting self.fields in test_post_data() shows the dict that I set it to. But then when I inspect fields in post(), it's value is <QueryDict: {'foo': ['bar']}>. I see the correct key in this QueryDict, but now the value is a list containing the string that I sent from the test. Why is the value changed from what I sent? p.s. My model is like this: class Foo(models.Model): foo = models.CharField(max_length=25) -
redefine options metadata documentation in a @detail_route method
Im trying to redefine the @detail_route documentation end point to make a better explanation of the method that I had, This is my views.py class SomeModelViewSet(viewsets.ModelViewSet): """ This is the documentation of SomeModel viewset, and its visible from the navigator, I also can edit some things as shown here http://www.django-rest-framework.org/topics/documenting-your-api/#self-describing-apis """ queryset = SomeModel.objects.all() serializer_class = SomeModelSerializer @detail_route(methods=['GET']) def somemethod(self, request, pk=None, *args, **kwargs): # pk= None """ I want that this documentation where shown in the API GUI in the navigator as shown here http://www.django-rest-framework.org/api-guide/routers/#example """ return Response({'name': 'some response')}) the problem its that I can't find the way to edit that description or options, when i access to mydomine.com/somemodel/1/somemethod I've got Api Root > SomeModel List > SomeModel Instance > SomeModel Options = {"name": "SomeModel", "description": "This viewset automatically provides `list`, `create`, } I want to have something like Api Root > SomeModel List > SomeModel Instance > somemethod Options = {"name": "somemethod", "description": "this is the description that i want to edit" } It's there a way to make that? should I define a new metadata ? Thanks !! -
Django - Createview form_valid object.id error
I'm trying to create a form where the object created (a project) has a relationship with another model (the channel). The problem is I can't workout how to call the channel's primary key for the project's relationship. Models.py: class Project(models.Model): channel = models.ForeignKey( 'Channel', on_delete=models.CASCADE, ) Views.py: class ProjectCreate(CreateView): model = Project fields = ['name', 'description'] def form_valid(self, form): Project = form.save(commit=False) form.instance.channel = Channel.objects.get(id=self.kwargs['channel']) Project.channel = channel return super(ProjectCreate, self).form_valid(form) I think something else needs to be added to the forms.py file as well: Forms.py: class ProjectForm(forms.Form): name = forms.CharField(max_length=50) description = forms.CharField(widget=forms.Textarea) -
Seo for hidden anchor tags
I have a very simple doubt, does google seo or other seos recursively crawl hidden hyperlink tags. I googled but could not find any solution. Any experience or any lead will be helpful.