Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework serializer returning nested records that should be filtered out on update
I override my FormSerializer's update method. It marks some nested field records as is_deprecated if necessary. However, the Api call returns all records, even though my get_queryset filters out everything is_deprecated. As far as I can tell, the get_queryset is being called to get the instance, which is then passed to the serializer. This instance does not contain any previously deprecated records. After the update method completes, it looks like another query must be run that gets ALL of these nested records and serializes them. This only occurs on updates. I get the correct records on a standard GET request. Any idea where this second query is being called and how to override it? Alternatively, I guess I could edit the serialized data in to_representation, but I'd like to understand what is going on here first. View class FormViewSet(LoginRequiredMixin, viewsets.ModelViewSet): serializer_class = FormSerializer queryset = Form.objects.all() def get_queryset(self): if 'pk' in self.kwargs: qs = Form.objects.filter(id=self.kwargs['pk']) else: qs = Form.objects.filter(id__in=name_dict.values()).order_by('name') queryset = FormSerializer.eager_loading(qs) return queryset Serializer class FormSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False, allow_null=True) fields = FieldSerializer(many=True) class Meta: model = Form fields = '__all__' @staticmethod def eager_loading(queryset): return queryset.prefetch_related(Prefetch('fields',queryset=Field.objects.filter(is_deprecated=False).order_by('field_order'))) -
I added ajax to my voting buttons and it is working but it is not updating number of votes without refreshing
I would like to ask you for your help. I use Django and I built my voting system and added ajax to it to avoid refreshing my page after clicking "UP" or "DOWN". And it is working (it updates my buttons without actually refreshing page). But my votes numbers are also included in the same part of code but they are not updating alongside buttons. To view change in number of votes i actually need to refresh whole site (f5). Could someone please explain to me why is that and what can I do about it ? My voting section: Vote Up: {{ total_voteup }} Vote Down: {{ total_votedown }} {% if is_voteup %} <form method='POST' action="{% url 'voteup' %}"> {% csrf_token %} <button type='submit' id="voteup" name="question_id" value="{{ question.id }}">Revert /\</button> </form> {% elif is_votedown %} <form method='POST' action="{% url 'votedown' %}"> {% csrf_token %} <button type='submit' id="votedown" name="question_id" value="{{ question.id }}">Revert \/</button> </form> {% else %} <form method='POST' action="{% url 'voteup' %}"> {% csrf_token %} <button type='submit' id="voteup" name="question_id" value="{{ question.id }}">/\</button> </form> <form method='POST' action="{% url 'votedown' %}"> {% csrf_token %} <button type='submit' id="votedown" name="question_id" value="{{ question.id }}">\/</button> </form> {% endif %} My js scripts: <script type="text/javascript"> $(document).ready(function(event){ … -
Django Page Error 404 - Loading JSON via uri
Hi I am working on a React Frontend - Django rest framework, serving API as backend. When I am loading a model it returns this error 404. I am not sure how I can include the /models in the urls.py so that I am able to load the .json files. Can i use Media_URL or static_URL to serve json files ? Page not found (404) Request Method: GET Request URL: http://localhost:8000/models/movies.json Using the URLconf defined in movieproject.urls, Django tried these URL patterns, in this order: ^api/movies/$ [name='movies-list'] ^api/movies\.(?P<format>[a-z0-9]+)/?$ [name='movies-list'] ^api/movies/(?P<pk>[^/.]+)/$ [name='movies-detail'] ^api/movies/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='movies-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] The current path, models/movies.json, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
how to make the divs at the same size
how can i make all the divs at the same size i am using django ?? <div class="row text-left"> {% for meg in objj %} <div class="col-lg-6 col-md-12"> <!--Image--> <div class="view overlay rounded z-depth-1-half mb-3"> <img src="{{ meg.img.url }}" class="img-fluid" alt="Sample post image" height="100%" width="150%"> <a> <div class="mask rgba-white-slight"></div> </a> {% endfor %} models: class News(models.Model): title = models.CharField(max_length=250) body = models.TextField() img = models.ImageField(upload_to='media/') def __str__(self): return self.title enter image description here -
Param Url to view Django
I have an URL with a parameter session: urlpatterns = [ path('session/<str:sessions>', photographies.views.session, name='session'), #añadido ] And what I want to do is to filter some pictures with a common session name into the db <a href="http://127.0.0.1:8000/session/{{photography.session}}"> So I try already making query to the db using .get() and also trying to pass the param direct into the view using new_session and then filter inside the view whit a simple if, the problem, it doest work, when I compare the photography.session == sessions nothing happen and when i print {{sessions}} it print in the view but like this: ('param',) def session(request, sessions): #añadido new_session = sessions, photographies = Photography_session.objects.get(session=sessions) #añadido print(new_session) return render(request, 'photographies/session.html', { 'photographies':photographies, 'new_session': new_session }) #añadido Thank you for your help in advance. -
How can I exclude rest-auth endpoint from the Django built-in API documentation?
To hide the endpoint in the Django documentation just @schema(None) has to be added for example to GenericAPIView, however I have a problem with these three urls: url(r'^swagger/', schema_view), url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), I am not able to add @schema(None) decorator because I do not have declared views for these urls. Any ideas how to work it around? -
How to validate post data if it exists with Django rest api
I have a front end built with Angular 9 and a django rest api to capture the email for a subscription form. I would to validate the entry from the frontend to make sure it does not exist in the database before it is saved if it does not exsit. here is the model: class Email(models.Model): email = models.EmailField(max_length=50) def __str__(self): return str(self.email) The view set: class EmailViewSet(viewsets.ModelViewSet): queryset = models.Email.objects.all() serializer_class = serializers.EmailSerializer def create (self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response(serializer.data,status=status.HTTP_201_CREATED) def perform_create(self,serializer): queryset = models.Email.objects.filter(email=request.data) if queryset.exists(): raise ValidationError('Email exist!') serializer.save(email=request.data) -
i want to edit the question queryset in my serializer and django api view to make the teacher not see his question when make review
my serializer.py is class RateSerializer(serializers.ModelSerializer): class Meta: model = Rate fields = ('id','author','question', 'stars', 'comment','creation_time') read_only_fields = ('id', 'author') and my views is class RateViewSet(viewsets.ModelViewSet): """Manage Rate API""" serializer_class = RateSerializer queryset = Rate.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.IsAuthenticated, IsTeacherOrAdminOrReadOnly) def perform_create(self, serializer): """Create a new Rate""" teacher = Teacher.objects.get(user=self.request.user) questions = Question.objects.get(question_author!= teacher) serializer.save(author=teacher,question=questions) -
Is there a way to pass in environment variables to python script?
I am trying to write a python test that involves testing if the environment variables provided are valid. I am passing the environment variables as follows env = EnvironmentVarGuard() env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS) The GOOGLE_CREDENTIALS is an import from a python file. the GOOGLE_CREDENTIALS works while in a .env but once I do the import from a file I receive the following error self.__credentials = ServiceAccountCredentials.from_json_keyfile_dict( File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/oauth2client/service_account.py", line 251, in from_json_keyfile_dict return cls._from_parsed_json_keyfile(keyfile_dict, scopes, File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/oauth2client/service_account.py", line 185, in _from_parsed_json_keyfile signer = crypt.Signer.from_string(private_key_pkcs8_pem) File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/oauth2client/_pure_python_crypt.py", line 167, in from_string marker_id, key_bytes = pem.readPemBlocksFromFile( File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/pyasn1_modules/pem.py", line 44, in readPemBlocksFromFile substrate = ''.encode().join([base64.b64decode(x.encode()) for x in certLines]) File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/pyasn1_modules/pem.py", line 44, in <listcomp> substrate = ''.encode().join([base64.b64decode(x.encode()) for x in certLines]) File "/Users/esir/.pyenv/versions/3.8.0/lib/python3.8/base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding the part using the env variable is ServiceAccountCredentials.from_json_keyfile_dict(json.loads(os.getenv('GOOGLE_CREDENTIALS'), strict=False), scopes=self.__scope) so my question is why does it work if I just set the GOOGLE_CREDENTIALS on the .env file buf fails if I try using EnvironmentVarGuard -
Cannot resolve keyword
I recevied an error when I request any page in the blog project I am working on, and I have no idea what is going wrong. Please help! views.py def post(request, id): post = get_object_or_404(Post, id=id) PostView.objects.get_or_create(user=request.user, post=post) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() return redirect(reverse("post-detail", kwargs={ 'id': post.id })) context = { 'post': post, 'form': form, } return render(request, 'post.html', context) here is the model.py: class Post(models.Model): title = models.CharField(max_length=50) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() author = models.ForeignKey(Author, on_delete=models.CASCADE) #thumbanail = models.ImageField() #comment_count = models.IntegerField(default= 0) #view_count = models.IntegerField(default= 0) categories = models.ManyToManyField(Category) featured = models.BooleanField() def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) def get_update_url(self): return reverse('post-update', kwargs={ 'id': self.id }) def get_delete_url(self): return reverse('post-delete', kwargs={ 'id': self.id }) class Meta: verbose_name_plural = 'Posts' def __str__(self): return f'{self.title}' @property def get_comments(self): return self.comments.all().order_by('-timestamp') @property def comment_count(self): return Comment.objects.filter(post=self).count() @property def view_count(self): return PostView.objects.filter(post=self).count() This is the I am receiving: FieldError at / Cannot resolve keyword 'comment_count' into field. Choices are: author, author_id, categories, comments, content, featured, id, overview, postview, timestamp, title * -
Setting the Format for the Django DatetimeInput Widget
I would like to use the included Django DateTimeInput widget as a datetimepicker on my website. No matter what I try however, the widget returns a datetime value in an incorrect format which will not send to my database. I need the format '%Y-%m-%d %H:%M:%S', but the widget returns '%d/%m/%Y %H:%M:%S' This problem has been discussed a tad here: http://stackoverflow.com/a/35968816/1382297 I believe the problem may be from setting the input_type to DateTime-local, but I don't know other options and cannot find any in the documentation. I've tried passing format='%Y-%m-%d %H:%M:%S' to the widget, as well as FORMAT_INPUTS = ['%Y-%m-%d %H:%M:%S'], and tried initializing these in the DateInput class, all with no luck. Here is my forms.py class DateTimeInput(forms.DateTimeInput): input_type = 'datetime-local' class EnterMatchForm(forms.ModelForm): class Meta: model = match fields = ('match_name', 'player1', 'player2', 'victory', 'match_description', 'match_date') widgets = { 'match_date': DateTimeInput(), } What is the right way to set up the widget so that it returns datetime values in the format Y-m-d H:M:S? Thanks in advance! -
Get an error when I try to run manage.py runserver
So I am trying to start a project in Django and I installed everything according to the documentation here:https://docs.djangoproject.com/en/3.0/intro/tutorial01/ Now, when I try to run the server with the command "py manage.py runserver", I get the following error: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have added all the required environment variables and I can't figure out what's the issue here. Any help would be great! :) -
Django Model method variable put into template
I have a model and I want to get the method variable "row_count and column" count to put the value into the templates. class Data(models.Model): """ Model of Data""" user = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_at = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(default=0, max_digits=6, decimal_places=2, blank=True, null=True) def calculate_amount(self): # wb = xlrd.open_workbook('media/' + self.document.name) wb = xlrd.open_workbook(os.path.join(settings.MEDIA_ROOT, self.document.name)) worksheet = wb.sheet_by_index(0) # Show this value into templates row_count = worksheet.nrows column_count = worksheet.ncols -
Unable to log in with provided credentials django DRF
My first time trying django REST api , I am doing some athentification , now i facing this error whene i run this commande : [curl -X POST -d "username=&password=" http://127.0.0.1:8000/api/auth/login/] error : {"non_field_errors":["Unable to log in with provided credentials."]} views.py : class CreateUserAPIView(CreateAPIView): serializer_class = CreateUserSerializer permission_classes = [AllowAny] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) # We create a token than will be used for future auth token = Token.objects.create(user=serializer.instance) token_data = {"token": token.key} return Response( {**serializer.data, **token_data}, status=status.HTTP_201_CREATED, headers=headers ) serializers.py class CreateUserSerializer(serializers.ModelSerializer): username = serializers.CharField() password = serializers.CharField(write_only=True, style={'input_type': 'password'}) class Meta: model = get_user_model() fields = ('username', 'password', 'first_name', 'last_name') write_only_fields = ('password') read_only_fields = ('is_staff', 'is_superuser', 'is_active',) def create(self, validated_data): user = super(CreateUserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user urls.py urlpatterns = [ path('auth/login/', obtain_auth_token, name='auth_user_login'), path('auth/register/', CreateUserAPIView.as_view(), name='auth_user_create'), path('auth/logout/', LogoutUserAPIView.as_view(), name='auth_user_logout') ] -
add class depending on condition to html via python
the following code is the one I am using for the header on all the templates of my site and adding it to each of them with: {% include 'header.html' %} I am trying to figure out how to add class="active" to the links on my header in order for it to highlight the corresponding nav-item depending on the current page. I was trying to define a function that returned different values depending on which template was active but I dont think I defined it correctly because when I put the condition inside the html it threw an error. Should I use the jinja tags inside the class attribute or outside the whole tags. Also, how can I know which is the current template. Pease help, thanks! {% load static %} <header role="banner"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand " href="{% url 'main:index' %}">my site</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample05" aria-controls="navbarsExample05" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample05"> <ul class="navbar-nav pl-md-5 ml-auto"> <li class="nav-item"> <a class="nav-link active" href="{% url 'main:index' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'main:about' %}">Nosotros</a> </li> <li class="nav-item"> <a class="nav-link" href="projects.html">Ingeniería</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="{% … -
How to return data from a Django server to an android app. Currently I can post the data from android app to the django API using retrofit
Code in python for django API @api_view(["POST"]) def getb64encodedimg(encodedImg): try: #print(encodedImg.body) with open("abc.jpg", "wb+") as fh: temp = unquote(unquote(encodedImg.body.decode("utf-8"))) fh.write(base64.b64decode(temp)) subprocess.call([r'C:\\Users\\LENOVO\\Desktop\\Capstone Project\\Run_FaceRecoginition.bat']) f = open("C:\\Users\\LENOVO\\Desktop\\result.txt","r") name = f.read() f.close() return Response(name) except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) This is the API code that takes input from the android app, runs certain tasks and returns the name value...How should I access the name data from the android app. Retrofit client instance code: (all java below) package com.example.policeapp.api; import retrofit2.Retrofit; import retrofit2.converter.scalars.ScalarsConverterFactory; public class RetrofitClientInstance { private static Retrofit retrofit; private static String BASE_URL = "http://10.0.2.2:8000/"; public static Retrofit getRetrofitInstance() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create()) .build(); } return retrofit; } } API Interface file: package com.example.policeapp.api; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface ApiService { @POST("getb64encodedimg/") Call<String> uploadPhotos(@Body String base64Image); } Android app code for uploading: Code from here all JAVA: public void Upload(){ ApiService service = RetrofitClientInstance.getRetrofitInstance().create(ApiService.class); service.uploadPhotos(base64img).enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { if (response.isSuccessful()) { showToast("Success"); } else { showToast("Failed"); } } @Override public void onFailure(Call<String> call, Throwable t) { showToast("Failed"); } }); } -
Django Rest 'PageNumberPagination' object has no attribute 'page' error
I have a function based Django API as shown in this sample: @api_view(['GET']) def findData(request): dataId = request.GET['dataId'] page_query_param = 'page' page_size = request.GET['page_size'] paginator = PageNumberPagination() paginator.page_size = page_size paginator.page_query_param = page_query_param qry_set = Data.objects.all() serializer = dataIdSerializer(qry_set, many=True) theData= serializer.data return Response(paginator.get_paginated_response(theData)) But I keep getting this error: AttributeError: 'PageNumberPagination' object has no attribute 'page' I tried setting paginator.page_query_param = page_query_param But still same problem. Please advise of how to fix. Thank you -
Django Celery Beat cannot connect to postgres database from inside docker container
My docker contianer django server, postgres, celery worker and celery beat. Running the application by itself there is no issue with connecting to the database however when the timed task to update the database runs I get an error celery_1 | django.db.utils.OperationalError: could not connect to server: No such file or directory celery_1 | Is the server running locally and accepting celery_1 | connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? below are my files docker-compose.yaml version: "3" services: redis: image: redis:alpine db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword ports: - "5432:5432" volumes: - "db:/var/lib/postgresql/data" pgadmin: image: dpage/pgadmin4 depends_on: - db ports: - "5555:80" environment: - PGADMIN_DEFAULT_EMAIL=dev@localhost - PGADMIN_DEFAULT_PASSWORD=password dj-dividend: container_name: dividend build: backend command: sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:80" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword volumes: - ./backend:/code ports: - "80:80" depends_on: - db - redis celery: build: backend command: celery -A backend worker -l info volumes: - ./backend:/code depends_on: - db - redis celery-beat: build: backend command: celery -A backend beat -l info volumes: - ./backend:/code depends_on: - db - redis - celery volumes: db: settings.py import os from celery.schedules import … -
Django 3 Cannot migrate DB syntax error at or near "WITH ORDINALITY"
I recently upgraded my server from Python2.7 to Python3.7 and Django from 1.11 to 3.0.6. Most things are fine, but I am unable to migrate the database. Following this link: Errors when I try to migrate in Django2 I deleted all migrations, ran a new makemigrations, did a new migrate --fake and everything went fine. Then I updated my models.py file, and it gave me the same error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 565, in alter_field old_db_params, new_db_params, strict) File "/webapps/jboycecom/local/lib/python3.7/site-packages/django/db/backends/postgresql/schema.py", line 154, in _alter_field new_db_params, strict, … -
how can i create a custom validate method to show errors in django forms
Hi im a junior django developer and i want to made a method that validates some fields like these def validar_empresa(self): ruc = self.cleaned_data['ruc'] if EmpresaCanchas.objects.filter(ruc=ruc).first(): raise forms.ValidationError("La empresa ya esta registrada.") if self.cleaned_data['nombre_negocio'] == "": raise forms.ValidationError('Es necesario el nombre de tu negocio') if self.cleaned_data['direccion'] == "": raise forms.ValidationError('Es necesario la direccion de tu negocio') if self.cleaned_data['telefono_negocio'] == "": raise forms.ValidationError('Es necesario un telefono de tu negocio') if self.cleaned_data['representante'] == "": raise forms.ValidationError('Es necesario el nombre del representante de tu negocio') if self.cleaned_data['hora_apertura'] == "": raise forms.ValidationError('Es necesario la hora de apertura de tu negocio') if self.cleaned_data['hora_cierre'] == "": raise forms.ValidationError('Es necesario la hora de cierre de tu negocio') return True The code its works but doesn display the errors in the template, just redirect to default error page like so My form: class ResgitroUsuarioForm(ModelForm): dni = CharField(max_length=8, widget=TextInput(attrs={'type':'number'})) nombres = CharField(max_length=256) apellidos = CharField(max_length=256) telefono = IntegerField() password1 = CharField(label='Password', widget=PasswordInput) password2 = CharField(label='Password confirmation', widget=PasswordInput) tengo_negocio = BooleanField(required=False, label="Tengo un Negocio") nombre_negocio = CharField(max_length=129, required=False) ruc = CharField(max_length=11, required=False) direccion = CharField(max_length=200, required=False) telefono_negocio = CharField(max_length=9, required=False) representante = CharField(max_length=128, required=False) hora_apertura = IntegerField(max_value=23, min_value=0, required=False) hora_cierre = IntegerField(max_value=23, min_value=0, required=False) My template: {% for error in … -
Handling the view count in the wagtail page
According to the user tracking analysis, I have been created a tracking method to save TrackUserRest record and update the Restaurant.view_count. The version 1 pop up an error when imported into Restaurant models. The version 2 save record and updates the view_count amount successfully, but I am not sure that it is the right way? For the further enhancement study, can anyone get me some examples to update the wagtail page in the right way? sorry for my English. class RestaurantPage(Page) .... #other attribute view_count = models.PositiveIntegerField(default=0, editable=False) @property def restaurant_page(self): return self.get_parent().specific def get_context(self, request, *args, **kwargs): context = super(RestaurantPage, self).get_context(request, *args, **kwargs) context['restaurant_page'] = self.restaurant_page context['restaurant'] = self self.tracking(request) return context def tracking(self, request): track = TrackUserRest() if request.user.is_authenticated: track.user_id = request.user.id else: track.user_id = 0 track.restaurant_id = self.pk track.time = timezone.now() track.save() self.view_count = self.view_count+1 return super(RestaurantPage, self).save() #version 1 class TrackUserRest(models.Model): user_id = models.ForeignKey(ExtendedUser, on_delete=models.CASCADE) restaurant_id = models.ForeignKey(RestaurantPage, on_delete=models.CASCADE) time = models.DateTimeField(auto_now=True, auto_now_add=False) class Meta: ordering = ('time', ) def __str__(self): return 'Restaurant Tracking system: usee.id({}) viewed rest.id({}) at timezone.({})'.format(self.user, self.rest.title, self.time) #version 2 class TrackUserRest(models.Model): user_id = models.PositiveIntegerField(null=True) restaurant_id = models.PositiveIntegerField(blank=False, null=False) time = models.DateTimeField(auto_now=True, auto_now_add=False) class Meta: ordering = ('time', ) def __str__(self): return … -
django-allauth Not Saving Social Info and social token etc
I have a customer profile assisiated with user so I wanted to make a customer profile on first login so I made a adopter for this like this class MyAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user if user.id: return try: user = User.objects.get(email=user.email) # if user exists, connect the account to the existing account and login sociallogin.state['process'] = 'connect' perform_login(request, user, 'none') raise ImmediateHttpResponse(redirect(settings.LOGIN_REDIRECT_URL.format(id=request.user.id))) except Exception as e: incominguser = User.objects.filter(email=user.email).first() if not incominguser: user.username=user.email user.save() newCustomer = Customer() newCustomer.customerProfile = user newCustomer.save() perform_login(request, user, 'none') raise ImmediateHttpResponse(redirect(settings.LOGIN_REDIRECT_URL.format(id=request.user.id))) else: raise ImmediateHttpResponse(redirect(settings.LOGIN_REDIRECT_URL.format(id=request.user.id))) ISSUE by doing this tables like Social application tokens are not being generated or nor Social accounts are being created . -
Use django variables passed as context in script tag of HTML file
I am stuck using <script> tags to render a googlemaps api window in my django webapp. In my views I passed my data as such: def map_view(request): context = { 'title': 'My Map', 'machines': Machine.objects.all(), } return render(request, 'gui/map_view.html', context) But can't figure out how to use machines in the javascript code. Tried both {{ }} and {% %} -
How to use django-autocomplete-light on form with multiple charfields
I have installed django-autocomplete-light. My form without autocomplete looks like this: class FilterForm(forms.Form): form_origin = forms.CharField(label='From country', max_length=100, required=False, widget=forms.TextInput(attrs={ 'placeholder': 'From country', 'arial-label':'C2', })) form_target = forms.CharField(label='To country', max_length=100, required=False, widget=forms.TextInput(attrs={ 'placeholder': 'To country', 'arial-label': 'C1', })) I have written a view following the instructions here, which gives all the countries which start with the same letter as my input. class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Country.objects.all() qs = qs.filter(name__istartswith=self.q) return qs However, I am having issues with using it with the form, which has two char fields, both to use the same model called Country. The tutorial isn't tailored to that. In essence, I hope to have two text boxes, with autocomplete of the country to and from, a bit like skyscanner. Any advice to the right direction is appreciated! My model looks like this: class Country(models.Model): iso3 = models.CharField('3 Digit ISO', max_length=3, unique=True) name = models.CharField('Name', max_length=50) lon = models.FloatField() lat = models.FloatField() def __str__(self): return self.name -
ImportError: cannot import name 'force_unicode' caused another exception
I was playing with calendars in my django app so I did a: pip3 install django-scheduler (https://github.com/llazzaro/django-scheduler) The minute I did my usual python3 manage.py runserver it failed with this long exception: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/filer/utils/compatibility.py", line 71, in <module> from django.utils.encoding import force_unicode # noqa ImportError: cannot import name 'force_unicode' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/shane/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/shane/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/shane/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/shane/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/shane/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/shane/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/shane/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/shane/.local/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed …