Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to wait for a promise to resolve before the next iteration in for loop
I have got two data tables I want to query some data from, so the way i thought about doing it is fetch url and based on a field from list, I do fetch(url) once more to get related data from another data table and I want to append them together to display on the browser. The issue here is that for loop iteration doesn't wait until the previous fetch is finished. I am using django_restframework, and it is me trying to fetch data by passing criteria(variables) through urls. can anyone help? var url = 'http://127.0.0.1:8000/creditor-detail/'+pmt_id+'/supplier/'+crm_spplier_id+'/' var results = fetch(url) .then((resp) => resp.json()) .then(function(item){ var list = item for (var i in list){ getCustomer(list[i].customer_id) .then(function test(user) { return user[0].customer_name }); var spmt = ` <tr id="data-row-${i}"> <td>${list[i].po_no}</td> <td>${list[i].amount}</td> <td>${I want return value[user[0].customer_name]}</td> </tr> ` wrapper.innerHTML+= spmt } }) function getCustomer(customer_id){ var url = 'http://127.0.0.1:8000/user-detail/'+customer_id+'/' var results = fetch(url) .then((resp) => resp.json()) .then(function(item){ return item }) return results } -
Create local files with python in Django
I want to create files with the extension .txt, .csv, .bin, etc. so the ideal would be with import os I think or if there is some other better way. But I don't want to save those in the DB they are to consult the once or sporadically, that is, locally are uploaded to the server and then it is replaced and that's it. In a simple way, I create the files I need, upload them and replace them when I need something that will not be so common. The directory for these local files would be /app/files/. -
Adding shipping information @ Stripe payment | Django
I'm trying to add some shipping information in my view.py to charge a customer but it's not working out. I'm using Stripe payment and below is my Django view: charge = stripe.Charge.create( customer=customer, amount=100, currency='brl', description='First Test Ever!', shipping={ "address": { "line1": request.POST['rua'], "line2": request.POST['bairro'], "city": request.POST['cidade'], "state": request.POST['estado'], "postal_code": request.POST['cep'], }, } If I remove the 'shipping' dict, the code runs without any problem. Link for more Stripe charge information: https://stripe.com/docs/api/charges/create?lang=python#create_charge-shipping-address-country Do you have any idea? Thank you! -
ProgrammingError during TestCase
I am trying to create my first functional TestCase and having an issue with a ProgrammingError occurring. I will first start by showing my TestCase. Note: I am using TenantTestCase because I am using Django-Tenant-Schemas to separate clients to separate schemas/sub-domains. I am not sure what self.c = TenantClient(self.tenant) does. class FunctionalTestCase(TenantTestCase): def setUp(self): self.browser = webdriver.Chrome() self.c = TenantClient(self.tenant) def test_company_reg_btn_works(self): self.browser.get('http://localhost:8000') time.sleep(3) reg_btn = self.browser.find_element_by_id('register-link') reg_btn.click() self.c.get('/company-reg/', follow=True) def tearDown(self): self.browser.quit() After running this I get the traceback: File "/home/david/PycharmProjects/clearpath_project/venv/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/david/PycharmProjects/clearpath_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "memos_memo_company" does not exist LINE 1: ..."memo_id", "memos_memo_company"."company_id" FROM "memos_mem... I am guessing this error is occurring as if the migration has not been run, but I am not sure. Can someone help explain what my next troubleshooting steps should be? Or what may cause this? -
Buildpack error when proper buildpack is already installed
I'm trying to Deploy to heroku on my django app, but I'm receiving an error saying: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure however I'm running the correct build pack as far as I can see: (virtual) MacBook-Pro-de-Stephen:src stephenlang$ heroku buildpacks === programatic-learning Buildpack URL heroku/python Could it be the way I have my files structured? Procfile: web: gunicorn blog.wsgi --log-file - runtime.txt: python-3.8.5 Is there something I'm missing with regards to deployment? -
How to use Django with PGBouncer?
I have an application launched in Django, which has a very high traffic of requests and queries to the databases. I am having problems and I have read that with PGBouncer and some settings in Django I can solve the problem. The question is how to integrate PGBouncer with Django. I have the Django application in Docker. The database is Postgres and it is in the RDS service of Amazon web services. Would PGBouncer be installed on the instance where the Django application runs? -
'bytes' object has no attribute 'objects' in django
here is my views.py function def searchfromimage(request): image_file = request.FILES['file'] os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'home/ServiceAccountToken.json' client = vision.ImageAnnotatorClient() content = image_file.read() image = vision.types.Image(content=content) response = client.document_text_detection(image=image) docText = response.full_text_annotation.text docText.replace('\n',' ') searchquery = docText allposts = content.objects.filter(title__icontains=searchquery) context = {'allposts':allposts} return render(request,'searchpage.html',context) when I am trying to print docText it gives the desired output but I am not able to use it to search it showing the error 'bytes' object has no attribute 'objects' I have tried str(docText, 'utf-8') but it is giving 'str' object has no attribute 'decode' error and I also tried with base64 and ASCII but nothing is working -
Why did djongo create a migration on my local server when I specified the host to be on Mlab?
In my settings.py file I have the following: 'ENGINE': 'djongo', 'NAME': '<db_name>, 'HOST': 'mongodb://username:<password>@ds147436.mlab.com:47436/<db_name>', 'USER': 'username', 'PASSWORD': '<password>', But when I run 'py manage.py makemigrations' then 'py manage.py migrate', the MongoDB collections get created on my local server MongoDB Compass. I don't know why it isn't creating my database over at Mlab? Where do I have to change my settings, or perhaps run a few different commands? In my terminal I get the following when I run 'py manage.py migrate': (env) PS D:\Business\Daydoa\v6-Django_with_MongoDB3\djongo_project> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://www.patreon.com/nesdis Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://www.patreon.com/nesdis OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://www.patreon.com/nesdis This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://www.patreon.com/nesdis OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://www.patreon.com/nesdis This version of djongo does not support "DROP CASCADE" fully. Visit https://www.patreon.com/nesdis OK Applying auth.0002_alter_permission_name_max_length... … -
Can you resave a Django object in same method
I have a django function, I am saving the object twice in the same function. As I need the id for the object in my .delay (python celery) function. Is it ok to use .save() twice, or is it not good practice: def some_function(request, emailname, emailbody): email = Email() email.name = emailname email.save() email_id = email.id celery_task = send_email.delay(email_id, emailbody) email.celery_task_id = celery_task.id email.save() -
Django Import error for foreign key field on the Admin Screen
I am looking to put together a basic motor vehicle database app using Django. I am getting the error msg below when I try to upload a file containing fk values of the cat make and model to match to the car make/manufacturer. I have tried to resolve this a number of ways and have the FK Widget resource in place but having no luck, greatly appreciate some guidance. Error msg Models.py class MotorModelsV2(models.Model): MotorMakeName2 = models.ForeignKey("MotorMakes",on_delete=models.CASCADE, to_field='MotorMakeName',null=True) MotorModelName = models.CharField(max_length=50) def __str__(self): return self.MotorMakeName2 or '' def __unicode__(self): return u'%s' % (self.MotorMakeName2) or '' class MotorMakes(models.Model): MotorMakeName = models.CharField(max_length=50, unique=True) def __str__(self): return self.MotorMakeName or '' def __unicode__(self): return u'%s' % (self.MotorMakeName) or '' Admin.py class MotorMakeResource(resources.ModelResource): class Meta: model = MotorMakes exclude = ('is_active',) class MotorModelResource(resources.ModelResource): class Meta: model = MotorModelsV2 exclude = ('is_active',) class MotorModelResource(resources.ModelResource): motormakename = import_export.fields.Field( column_name='MotorMakeName1', attribute='MotorMakeName1', widget=ForeignKeyWidget(MotorMakes, 'MotorMakeName')) class Meta: fields = ('MotorMakeName1',) admin.site.register(MotorModelsV2, MotorModelsV2FileAdmin) admin.site.register(MotorMakes, MotorMakesFileAdmin) -
Hitcount Not Counting No. of Visits for A Detail View
I have followed https://github.com/thornomad/django-hitcount to implement Django Hitcount but I might be missing something I am not sure what it is as the count is 0 and remained like this even if I refreshed and even changed users. I think there might be some problem in the views just before the context where there is an arrow Here is the models.py @python_2_unicode_compatible class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, unique=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') Here is the views.py class PostDetailView(HitCountDetailView, DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context.update({ 'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3], <----- I think error from here }) context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context here is the urls.py app_name = 'score' urlpatterns = [ path('', PostListView.as_view(), name='score'), path('details/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('hitcount/', include(('hitcount.urls', 'hitcount'), … -
unable to create superuser in Django pycharm
trying to create superclass for the first time using pycharm also i have installed pscopg2 and django but still (maybe) i see some issues related to importing psycopg2 it would be great if someone helps tried a lot but can't figure out... ** (untitled) C:\Users\User\PycharmProjects\untitled>python manage.py createsuperclass Traceback (most recent call last): File "C:\Users\User\PycharmProjects\untitled\lib\site- packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\User\PycharmProjects\untitled\lib\site-packages\psycopg2\__init__.py", line 51, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\User\PycharmProjects\untitled\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\PycharmProjects\untitled\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\User\PycharmProjects\untitled\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\PycharmProjects\untitled\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\User\PycharmProjects\untitled\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen … -
Does Django index Autofield / ID keys in PostrgeSQL?
Django's docs state that id fields created with AutoField are indexed: id is indexed by the database and is guaranteed to be unique. Similarly it applies an index to every FK relationship. However, in PostgreSQL whilst FKs appear to be indexed, IDs are not. Here's an example: class TestModelBase(models.Model): name = models.CharField(max_length=50) fkfield = models.ForeignKey(TestModelFK, blank=True, null=True, on_delete=models.CASCADE) m2mfield = models.ManyToManyField(TestModelM2M, related_name='base_m2m') This model appears to apply the fkfield index, but not the id autofield. From PGAdmin below: Am I missing something? -
Gunicorn, error with Django: "ModuleNotFoundError: No module named 'store'"
The server uses Ubuntu 20.4 How looks my main folder: In src folder I have all Django structure: diasmart folder here is the project folder (contains settings.py, wsgi.py...) My apps in settings.py ... INSTALLED_APPS = [ ... # My apps 'store.apps.StoreConfig', 'orders.apps.OrdersConfig', 'profiles.apps.ProfilesConfig', ] My wsgi: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'diasmart.settings') application = get_wsgi_application() gunicorn_config.py (main/gunicorn_config.py): command = '/root/DiaStore/env/bin/gunicorn' pythonpath = '/root/usr/bin/python' bind = '127.0.0.1:8001' workers = 2 user = 'root' limit_request_fields = 32000 limit_request_field_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=src.diasmart.settings' In bin folder (main/bin), I have "start_gunicorn.sh" file: (DiaStore its the name of the main folder) #/bin/bash source /root/DiaStore/env/bin/activate exec gunicorn -c "/root/DiaStore/gunicorn_config.py" src.diasmart.wsgi I wrote in terminal (DiaStore is the opened folder): source ./bin/start_gunicorn.sh I got: Traceback (most recent call last): File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File … -
Django autocomplete broken
I followed the solution in https://stackoverflow.com/a/55992659/13837243 because I was trying to filter my autocomplete fields. I made the override file in a folder in one of my apps at myapp/static/admin/js/. The autocomplete fields in that app stopped working. In fact, all autocomplete fields in my project (including in other apps) stopped working. I reverted the changes made, but still, autocomplete fields are all broken in my project. The autocomplete fields now look like normal dropdowns, except without any options. If a field already had an option selected, it looks like a normal dropdown that only displays the selected option. How can I fix this without potentially having to reinstall django? -
View does not update the current date (Django)
It is implemented to call get_week in view. 'now', which is printed directly as a template, is normally displayed, but the result of get_week, which is output through the module, is output as the value before 1 week. If you have fixed a similar bug, please help For reference, the source code below is a function to generate a weekly report. #: 금주 보고서는 read/modify @login_required def weekly_report_view(request): context = { 'site_title': '취약점 Dashboard', 'site_header': '취약점 Dashboard', 'user': request.user, 'has_permission': True, 'now': datetime.datetime.now() } this_week = False week_num = request.GET.get('week_num') if week_num is None: start_date, end_date, week_num = get_week() stats = Statistics2020.objects.filter(week_num=week_num) if len(stats) == 0: return redirect('/dashboard/stat/weekly/create') stat = stats[0] if stat.end_date >= datetime.date.today(): this_week = True stat_date_update(stat.week_num, stat.start_date, stat.end_date) else: pass context['stat'] = Statistics2020.objects.get(week_num=week_num) context['raw'] = json.loads(stat.raw) context['this_week'] = this_week return render(request, template_name='dashboard/weekly_report.html', context=context) def get_week(today=datetime.datetime.now().date()): shift = BASE_WEEK_START - 1 print(today) week_number = today.isoweekday() - shift if week_number <= 0: week_number += 7 startdate = today - datetime.timedelta(days=week_number-1) enddate = startdate + datetime.timedelta(days=6) #print('%s~%s'% (startdate, enddate)) return startdate, enddate, int(startdate.isocalendar()[1]) -
Execute celery task from model - Django
I have a model in my Django app: class MyTask(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() I want to filter any MyTask object and assign a task to it, right now, I have like a "dummy" task which prints a message to console: from project._celery import _celery from celery.result import AsyncResult from django.apps import apps @_celery.task(name="print_object") def print_object(bind=True): model = apps.get_model(app_label='my_app', model_name='MyTask') new = model.objects.filter(pk__in=[1,2,3]) new.task = app.AsyncResult.task_id print("Hello, I'm an Object!") I just want to assign this task, to MyTask objects having pk's 1,2 and 3. I know that with model = apps.get_model(app_label='my_app', model_name='MyTask'), I can access my model. But, in any case, this line says: NameError: name 'MyTask' is not defined I do have the apps.py file on my app directory: from django.apps import AppConfig class MyAppAppConfig(AppConfig): name = 'my_app' So, no idea why this is happening, btw, my tasks.py file is inside a folder, inside my module folder, could that be the cause for this? Also, from what I want to achieve, do you think this is the ebst way to do it? Thanks in advance -
Why user.is_active is false if the username and password are stored in the database?
Every time I try to log in in the website I created, it returns the else in the user_login function in views.py, but I don't understand why since it stores correctly in Users in the database. views.py from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.models import User from .forms import UserForm # Create your views here. def index(request): return render(request, 'app1/index.html') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request, 'app1/register.html',{'user_form':user_form, 'registered':registered}) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username = username, password = password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Not Active") else: print("Someone tried to login and failed") print(f"Username: {username} and password {password}") return HttpResponse ("Invalid Login details supplied") else: return render(request, 'app1/login.html',) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email', 'password') models.py from … -
How to solve Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings issue
I am running on Windows 10 and have successfully installed the gdal 64 bit library from this resource: https://trac.osgeo.org/osgeo4w/ My django app is running with pipenv I also added in my settings.py the variable : GDAL_LIBRARY_PATH = 'C:\OSGeo4W64\bin' and also add this variable also to the path variable ins system variables. After every run of the development server i got the error : Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Maria\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\Maria\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Maria\.virtualenvs\ev-loader-backend-7qq6TCvy\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Maria\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
how to add speech recognition to a web app?
I would like to someone to guide me to know how to add speech recognition to a web app, specifically to Zoom Meetings within a web app. The main idea is to get into text the meetings using Django. I trained a CNN model using tensorflow, but I was seeing that I will not be able to use it within the web app using django, because I'm using pyaudio library, which captures the internal audio of the computer. The same will happend using the standar library SpeechRecongnition. Maybe it is possible using the Zoom's API and some property that can be used in django or using speech regonition API from google. Any guidance or scope someone can do to both the answer and the question will be considered -
CSS all properties not working with Django/bootstrap
I'm trying to create some custom css. I'm using django and a bootstrap template to have something to begin with. I'm trying to use this css: a { position: relative; display: inline-block; padding: 15px 30px; color: #f02720; text-transform: uppercase; text-decoration: none; font-size: 24; overflow: hidden; transition: 0.2s; } a:hover { color: #255784; background: #2196f3; box-shadow: 0 0 10px #2196f3, 0 0 40px #2196f3, 0 0 80px #2196f3; transition-delay: 1s; } Things like the changing the color work, but some don't. Is there a reason why? Are there limitations because I'm also using bootstrap? -
Getting error notices while developing with Django - Visual Studio
I started to use the framework Django on Visual Studio Code, and even though my code is correct and works just fine when I run it, Visual Studio keeps sending error warnings (see pic), which is something that it never does when I don't use the Django framework. When I code in Python without using the Django framework and Visual Studio signals an error, then there is actually something wrong with my code, but when using Django it seems that it signals errors even tho the code is perfectly fine. I thought about switching off the feature completely, but it's a very convenient feature, when it works properly. How can I set Visual Studio in a way that when working with Django, it signals errors only when there is actually something wrong with the code? -
Django update fields on POST request when unique username field unchanged
I have a simple profile form that displays the users profile and allows them to make updates to Full Name, Initials, Username and Bio. In my Profile model, I have Username set to unique with field validation. It is more of a screen-name reference field, as email is used for login, however it still needs to be unique and the user can change this name if needed. The issue is that validation does not allow for POST form.save(), even when user does not change their username, but updates other fields, due to the fact that the username does already exist for the request user. How can I get around this issue. Sample of what i am trying to do: If request.user.username == form['username'].value() (meaning username is unchanged) allow form.save() else if form.is_valid(): (perform normal validation checks) form.save() Thanks for any suggestions. -
Error adding a convential sign up and github sign up together in a django project
I am doing a django book store project which has a successful sign up function. I followed WS Vincent's tutorial to connect Github signup (https://learndjango.com/tutorials/django-allauth-tutorial) and I have come across an error when integrating it. TemplateSyntaxError at / Invalid block tag on line 16: 'provider_login_url', expected 'endif'. Did you forget to register or load this tag? Below is the code for the major areas of my project. home.html {% extends '_base.html' %} {% load static %} {% block title %}Home{% endblock title %} {% block content %} <h1>Homepage</h1> <img class="bookcover" src="{% static 'images/djangoforprofessionals.jpg' %}"> {% if user.is_authenticated %} <p>Hi {{ user.email }}!</p> <p><a href="{% url 'account_logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <p><a href="{% url 'account_login' %}">Log In</a> | <a href="{% url 'account_signup' %}">Sign Up</a> <a href="{% provider_login_url 'github' %}">Sign Up</a></p> {% endif %} {% endblock content %} I am not familiar with HTML but I take the two sign up lines are not meant to be put one after the other. -
How can I test Django Channels using native Django's test framework instead of pytest?
Django Channels recommends using pytest in order to get an async enabled testing layer. I really don't want to throw another test framework into my project if I can help it. Is there a way to use Django's TestCase natively to test Django Channels? I've encountered multiple problems -- one is that async_to_sync() doesn't like to be called from the main thread. I am limited with Python 3.6 at the moment.