Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix CSRF error on logging in using REST API in Django Rest Framework?
I am beginner to Django, following this tutorial to implement register, login and logout using DRF. The register is working fine, but I am not able to login using postman, it is showing CSRF error. Already tried using @csrf_exempt decorator, but then it is showing AttributeError on LoginAPI.asView() AttributeError: 'function' object has no attribute 'as_view' <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please … -
How i can convert list value in String in Django?
I have some values store in my database in this format ["Same Drive","Test Drive","Safe Drive"], and same values are displaying on my HTML page, I want to display these values in this format Same, Test, Safe Drive, Please let me know how I can display these values in this formant. here is my HTML file code.. <p>{{datas.types}}</p> and this is displaying data in this format ["Same Drive","Test Drive","Safe Drive"] -
Django template variable not set
The title says everything. Two days ago the following code worked fine but now journeys is not set or empty or ... def map(request, jid): journeys = None if request.user.is_authenticated: journeys = Journey.objects.filter(user_id=request.user.id) #some stuff context = { 'jc': len(journeys), #only for testing 'journeys': journeys } return render(request, 'JourneyMap/map.html', context) map.html extends base.html Inside base.html: <div class="dropdown-menu" aria-labelledby="dropdown05"> <p>{{ jc }}</p> <-- only for testing {% for journey in journeys %} {% if journey.user_id == user.user_id %} {% if forloop.counter < 4 %} <a class="dropdown-item" href="{% url 'JourneyMap_journey' jid=journey.id %}">{{ journey.title }}</a> {% endif %} {% endif %} {% endfor %} </div> Result: -
Django: what is the best way to prevent multiple click on a button?
I have a Django form with a popup confrimation before form validation. When validated, I save form data in a table, update 2 other tables, send an email and user is redirected to another confirmation page. It works but it may be slow in some situation. And in these situation, I have experienced the case a user click another time. Doing that, form data are sent again but form validation failed (normal behavior to prevent duplicate) but user is never redirected to the confirmation page and that is problematic. To fix this issue, I would like : to prevent user to be able to click 2 times the popup button (disable after first click) improve data process in my view improve my logic For the first point, I must use JS, right? For the second point, as 2 table are update, I think using update would be better For the third, ? thanks for advice def randomisation_edit(request): if request.method == "POST": form = RandomisationForm(request, data=request.POST or None) if form.is_valid(): randomisation = form.save() pays = randomisation.ran_num[0:3].upper() centre = randomisation.ran_num[4:6].upper() status = randomisation.ran_vih severity = randomisation.ran_sta rand = Randomiser(pays, centre, status, severity) # Mise à jour de la base de données -> … -
How to run an async function without blocking the execution in Django channels
I have an AsyncWebsocketConsumer running django channels for an online turn-based game. There is need to verify that the player associated to the current turn is online, and if they aren't, the turn should be updated and passed onto the next player. At the end of the function that sends the new state to connected players, you have these two lines: await self.send_new_state_to_all_players(event_specifics) await self.check_current_player_online(game_id) # routine to handle the case where current player isn't online The method check_current_player_online() does this: async def check_current_player_online(self, game_id): current_turn_player_number = await self.get_current_turn(game_id) if await self.is_online(await self.get_player_id_from_number(game_id, current_turn_player_number)): # if current player is online, resume normal game flow return await asyncio.sleep(5) if not await self.is_online(await self.get_player_id_from_number(game_id, current_turn_player_number)): # if player hasn't come back, increment turn await self.increment_turn(game_id) await self.send_new_state_to_all_players({ 'type': 'pass_turn', }) Expected behavior: when the turn of a player who isn't online comes, every player should receive the new state sent by send_new_state_to_all_players, and be informed it's xyz's turn (the offline player), then after 5 seconds, if xyz hasn't come back online, the socket should send a new state message after updating the turn. This intended behavior takes place for everyone but the last player who sent a message to the socket, which … -
TemplateDoesNotExist at / while deployment
I developed a webapp using Django framwork, it's running fine in my localhost server but when I try to deploy it on any server like Heroku or PythonAnywhere I am getting this error I am not getting how to resolve it I tried changing paths and directories then also I am getting the same error can anyone please help me to resolve this error. Here is the error its showing me on the server:- Environment: Request Method: GET Request URL: http://alfeed21.pythonanywhere.com/ Django Version: 3.1.1 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /home/Alfeed21/Webapp3.0/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/Alfeed21/.virtualenvs/task3/lib/python3.8/site- packages/django/contrib/admin/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/Alfeed21/.virtualenvs/task3/lib/python3.8/site- packages/django/contrib/auth/templates/index.html (Source does not exist) Traceback (most recent call last): File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Alfeed21/Webapp3.0/credit/views.py", line 6, in home re turn render(request, 'index.html ') File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) … -
psycopg2.OperationalError: FATAL: password authentication failed for user "test"
I get the above FATAL error when running the containers dictated in the below files. It's a Django project being deployed to docker containers. The issue is I'm trying to get Postgresql to work in the docker setting but for some reason I can't get the login to work! Appreciate the help docker-compose.yml version: '3' services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: mu_chat_clone volumes: - .:/mu_chat_clone ports: - "8000:8000" env_file: - ./.env depends_on: - db redis: image: redis:latest expose: - "6379" db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=test - POSTGRES_PASSWORD=password - POSTGRES_DB=mu_chat_clone volumes: postgres_data: .env SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=mu_chat_clone SQL_USER=test SQL_PASSWORD=password SQL_HOST=db SQL_PORT=5432 settings.py DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } -
Django CharField unique argument in new Django version
In my forms.py file I am using CharField. I read about unique argument of CharField in the book: it says if the unique argument = True, then that model's CharField cannot repeat. In the book Django 2.1 version is presented. As for now, the argumen's name has been changed. I think so because Django shows an error sign TypeError: __init__() got an unexpected keyword argument 'unique' -
How can I create a form for making an appointment to a specialist?
Is it possible in Django to create a form for making an appointment to a specialist (doctor, hairdresser, auto repair shop), with the condition that if the first client signed up for a certain time, this time will not be available for the next one? If so, where can I read about it or see a sample? -
I'm looking for a library that will allow Django users to OAuth authenticate to an API and Django to access their data
I've done some Googling but I can't find the right Django library to use. Here's the scenario: My Django website has muiltiple users who register and log in using the built in Django user management features. I now want the website to access these users data from a third party site via that site's REST API. The third party site API requires the users authenticate via OAuth2. User registers on my website and logs in User follows link on my site, to give my site access their data stored on third party website, via REST API User is forwarded to the third party website where they agree to give my website access and are sent back as per OAuth pattern. My website should then be able to access the users data on the third party site, which it will access once per day, at night, to download the latest data. Access needs to be maintained indefinitely (token needs to refresh?), so that their data is accessible to my site, until the user chooses to disable the feature. -
Using same database tables for different projects in django postgresql
I am new to using Django framework. I want to use the same database(PostgreSQL) tables for 2 different projects. I was able to access the same database from two different projects. But how to access the tables? Firstly, I have models in project1 class employees(models.Model): employeeID = models.IntegerFiled() employeeName = models.CharField(max_length=100) This would create a project1_employees table in the database. I want to access this table in project2. If I have the same model in the project2 and migrate it creates a new table project2_employees in the same database. These are two entirely different projects. -
How to build an admin page from the record edit pages of several models?
For example I have three models: class Person(models.Model): nick = models.CharField(max_length=60, unique=True) name = models.CharField(max_length=60) age = models.PositiveIntegerField() class CurrentPersonPair(models.Model): person_1 = models.ForeignKey(Person, on_delete=models.CASCADE) person_2 = models.ForeignKey(Person, on_delete=models.CASCADE) class CurrentRegionPair(models.Model): region_1 = models.CharField(max_length=60) region_2 = models.CharField(max_length=60) CurrentPersonPair relations on Person and CurrentRegionPair just by it self. CurrentPersonPair and CurrentRegionPair have limit of one record. I need them to look like this: CurrentPersonPair and CurrentRegionPair gives their first records since they have only one and the Save button saves changes in both models (with all validations, errors etc). And Person works the same if it was a page just for this model. So is there a way to do that? I know about inlines but they work on record edit page but here I need to use something like that on the list page. -
Django widget FilteredSelectMultiple
I'm trying to add the FilteredSelectMultiple widget but it is only showing the 1 half of the widget is rending. I have found some stackoverflow post but none seem to have changed it. Need guidance with FilteredSelectMultiple widget Django FilteredSelectMultiple widget rendered with bootstrap form.py class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') dbs_number = forms.CharField(max_length=13, label='DBS Number') hospitals = forms.ModelMultipleChoiceField(queryset=HospitalListModel.objects.all(), widget=FilteredSelectMultiple('HospitalListModel',False), required=False, ) class Media: css = { 'all': ('/admin/css/widgets.css', 'admin/css/overrides.css'), } js = ('/admin/jsi18n','/admin/jquery.js') url.py from django.urls import path from . import views from django.conf.urls import url from django import views as django_views urlpatterns = [ url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'), ] template {% extends '_base.html' %} {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <link href="{{ STATIC_URL }}admin/css/overrides.css" type="text/css" rel="stylesheet" /> <button class="btn btn-success" type="submit">Sign Up</button> </form> {% endblock content %} -
Relational database in django rest framework serializers
I'm working on a Rest API for a web blog, I have made the custom user class and related between custom user class and the post class, but when i try to make a post request and add a post to the database i'm stuck in serializering the post because of the the relation between the user and the post models, all i want to do is just make the author of the post is the current logged in user but i don't actually know how to do this Custom user model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, blank=False, null=False) username = models.CharField(max_length=255, unique=True, blank=False, null=False) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_superuser Post model: class Post(models.Model): title = models.CharField(max_length=255, blank=False, null=False) content = models.CharField(max_length=10000, blank=False, null=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title Post serializer: class PostSerializer(ModelSerializer): class Meta: model = Post # I don't know if this way is right fields = ('id', 'title', 'content', 'author') extra_kwargs = {"author": {"read_only": True}} def create(self, validated_data, request): post = Post( title=validated_data['title'], content=validated_data['content'], # I … -
How to count data in Related Model in Django?
I am trying to count value of related model, but i am unable to count, Please let me know where i am Mistaking.. Here is my models.py file... class Project(models.Model): name=models.CharField(max_length= 225) slug=models.SlugField(null=True, unique=True) class Detail(models.Model): project = models.OneToOneField('Project', related_name='detailsofpro', on_delete=models.CASCADE, blank=True, null=True) possession = models.CharField(max_length=50, null=True, blank=True, choices=(('Under Construction', 'Under Construction'),('New launch', 'New Launch'),('Ready To Move', 'Ready To Move'))) here is my views.py file.. def admin_view(request): project = Project.objects.prefetch_related('project_details').annotate(Count('possession')) return render(request, 'index.html', {'project': project}) here is my index.html frile <p>{{project.project_details.possession.count}}</p> i want to count possession from details model, please let me know how i can count -
How to upload files to another APIs from django views using requests package
How to upload files to APIs from django views using requests package. -
Learning Django and Spring simultaneously
Is it possible to learn Django and spring at the same time? Is it a bad idea? I like java for object oriented programming and Django seems easy to me. So I am confused. Should I go for both? Will it be beneficial if I learn both frameworks simultaneously for web application? -
image upload in a template
My issue is if I upload from admin an image it works fine but if I want to add an image from my template, it seems that my image does not updload. It is weird as in the request.Post form, path of my image is present. I've no message of error... this is my model: class Listing(models.Model): title = models.CharField('Title',max_length=64, blank=False) description = models.TextField('Descritpion', blank=False) Creation_date = models.DateField(auto_now_add=True) enddate= models.DateField('Ending Date', blank=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") initialBid = models.DecimalField('Bid', max_digits=12, decimal_places=2, blank=False) photo = ResizedImageField(size=[300, 150], upload_to='images/', default='images/default.jpg') active = models.BooleanField('Active', default=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") def __str__(self): return f"{self.id} : {self.title} {self.initialBid} {self.Creation_date}" def save(self, *args, **kwargs): # Check how the current ending date is after created date, d1 = self.Creation_date d2 = self.enddate if d2 <= d1: raise ValueError("End date must be a day after today") super(Listing, self).save(*args, **kwargs) my form: class NewListingForm(forms.ModelForm): enddate = forms.DateField(label='Date of auction End', widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',)) def __init__(self, *args, **kwargs): self._newly_created = kwargs.get('instance') is None self.Creation_date = datetime.now() super().__init__(*args, **kwargs) class Meta: model = Listing fields = ('title','description','enddate','category','initialBid','photo','active') my template: <h2>{% if not form.instance.pk %}Create listing {% else %} Edit {% endif %}</h2> <form id="create-edit-client" class="form-horizontal" action="" method="post" accept-charset="utf-8" … -
How can I do to filter hours using Django?
Hello I am using Django and I have these variable : a = '08:00:00' b = '13:30:03' I want to do something like this : Table.objects.filter(myhour__in(a, b)) but it does not work... Could you help me please ? Thank you very much ! -
Recivieng error 500 when deploy Django rest-Vue project on Heroku
I'm been able to deploy my first project to heroku. The API is this: https://segmentacion-app.herokuapp.com/cluster/, and the front is this: https://cluster-app-wedo.herokuapp.com/, the problem appears when I try to consume the api, I receive this: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Error: Request failed with status code 500 at t.exports (createError.js:16) at t.exports (settle.js:17) at XMLHttpRequest.p.onreadystatechange (xhr.js:61) Home.vue:598, can I have some feedback about what i've missed? Home.vue let datos = await axios.post('https://segmentacion-app.herokuapp.com/cluster/',json) .then(response => { ... server.js const express = require('express'); const port = process.env.PORT || 8080; const app = express(); app.use(express.static(__dirname + '/dist/')); app.get(/.*/, function(req, res) { res.sendfile(__dirname + '/dist/index.html'); }); app.listen(port); console.log("Server started..."); settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://cluster-app-wedo.herokuapp.com/',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MiApp', 'import_export', 'django_extensions', 'rest_framework', 'api', 'corsheaders', ] MIDDLEWARE = [ … -
How to hide objects after deletion in Django admin?
in my Django admin interface if I delete something it leads to default Django admin deletion page. In that page under objects category can we delete any object message or make changes in it? I have provided with the image!! -
How to remotely enter email credentials in django?
My web app is deployed by the computer team but developed by me. It is essential that the emails are sent using my team's email id. Hence, I am using a form to enter credentials into a safe file only accessible to my user. This is my settings file from config parser import ConfigParser EMAIL_CREDENTIAL_CONFIG = "credentials.ini" def credential(attr): config = ConfigParser() try: config.read(EMAIL_CREDENTIAL_CONFIG) return config["DEFAULT"][attr] except KeyError: pass EMAIL_HOST_USER = credential("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = credential("EMAIL_HOST_PASSWORD") The issue is that these values are loaded only when the server starts and I cannot remotely update it without using an ssh terminal and manually entering the file location. Can you suggest alternatives to either reload the email credentials automatically or to keep the creds safe from anyone having access to the server pc? -
Cannot Assign variable to Form Field for new entry
When trying to run a form.save() on I am receiving the following error: IntegrityError at /customers/customer/1930/contacts/ ('23000', "[23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Cannot insert the value NULL into column 'idcst_cnt', table 'app_contact_cnt'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The statement has been terminated. (3621)") I cannot seem to figure out how to include the idcst_cnt value which is a variable passed in id which is a hidden field on the form/template. forms.py class ContactsForm(ModelForm): class Meta: model = AppContactCnt fields = ('idcst_cnt', 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt') labels = {'name_cnt': 'Name', 'phone_cnt': 'Phone', 'email_cnt': 'Email', 'note_cnt': 'Note', 'receives_emails_cnt': 'Emails?', } widgets = { 'id_cnt': forms.HiddenInput(), 'idcst_cnt': forms.HiddenInput(), } ContactFormSet = modelformset_factory(AppContactCnt, exclude=()) views.py def customer_contacts(request, id): ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=( 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt'), max_num=3, extra=3) formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=id), prefix='contact') if request.method == 'GET': context = {'formset': formset, 'id': id} return render(request, 'customer_contacts.html', context=context) if request.method == 'POST': print(formset.errors) formset = ContactFormSet(request.POST, prefix='contact') for form in formset: if form.is_valid(): customer = get_object_or_404(AppCustomerCst, id_cst=id) form.idcst_cnt = customer form.save() print("we're updating contacts for " + str(id)) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) context = {'formset': formset, 'id': id} return render(request, 'customer_contacts.html', context=context) … -
How to be able to display any Uploaded Django File in HTML
I am making a site that can store files that means video, audio, text, and many more. But I am having a problem display those files that are in my database as in a media folder. So like I have found that iframe is best until there was a problem with the video and the audio files. When the page loads they auto start and I know that the video tag and img tag is the best of this but How am I suppose to know the file type to display. So like the website is almost like Google Drive except for the styles of course. -_- Well so like what can I do to solve my problem. Thanks in advance -
Multiple authentication for different user types
I have 3 user types (Customers, Vendors, Admins) which I have differentiated using their profiles. I want to have OTP based authentication for Customers from mobile (DRF) and Web app as well, user name and password based auth for Admins and Vendors from mobile (DRF) and Web app. How can I achieve this? If the question is not clear please comment below.