Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Test database not empty after running ./manage test --keepdb
Here is a minimal example of a test I'm trying to run from django.contrib.auth import get_user_model from django.test import TestCase User = get_user_model() class UserTests(TestCase): # def tearDown(self): # User.objects.all().delete() def test_user(self): User.objects.create(username='testuser') The first time it runs fine. But the second time it produces ...lib/python3.7/site-packages/MySQLdb/connections.py", line 224, in query _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1062, "Duplicate entry 'testuser' for key 'username'") The entry from the previous run is still in the database, hence the duplicate entry error. I thought using django.test.TestCase (as opposed to unittest.TestCase) clears the test database every time it is run? The problem disappears if I uncomment the tearDown function. In the end, it's not a big effort to include all the models in tearDown, but still, I wonder why this is necessary. Here are my database settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'materials', 'USER': config('DB_USER', default=''), 'PASSWORD': config('DB_PASSWORD', default=''), 'HOST': 'localhost', 'PORT': '', } } The storage engine is Aria. -
How to use django F expressions to only filter the date of datetime fields
I need to filter another datetime field through a datetime field, but I just need to compare date. How to implement it by F expression? F expression does not seem to format fields My model is: class Test(): date1 = models.DateTimeField() date2 = models.DateTimeField() I just need to compare date, not time. Test.objects.filter(Q(date2__gt=F('date1'))) It keeps comparing datetime. That's not what I want. I just want to compare date. As a Django rookie, I can't find a solution. -
django nginx : How to solve Server Error (500)?
Python3.7 Django2.1 centOS7 gunicorn nginx I am setting up a production environment. sudo gunicorn --bind 127.0.0.1:8000 myapp.wsgi:application After executing this, if you access the IP address, error (500) will occur. less /var/log/nginx/access.log There is no error in checking this. #gunicorn.conf server { listen 80; server_name IPaddress; location /static { alias /var/www/static; } location /media { alias /var/www/media; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; } } What should I check? -
Getting "AuthStateMissing ... Session value state missing." when going to callback URI when using AtlassianOAuth2 with Django
I was trying to setup oauth2 authentication in a Django app. Here's my settings: *other parts ommited* # AUTH STUFF AUTHENTICATION_BACKENDS = ( 'social_core.backends.atlassian.AtlassianOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_ATLASSIAN_KEY = ' *my atlassian key here* ' SOCIAL_AUTH_ATLASSIAN_KEY_SECRET = ' *my atlassian secret key here* ' LOGIN_URL = '/auth/login/atlassian-oauth2' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIAL_AUTH_URL_NAMESPACE = 'social' SESSION_COOKIE_SECURE = False # i had to do that^, based on what i have read from # https://stackoverflow.com/questions/37617308/session-value-missing-after-redirect-with-django-python-social-auth # but it still doesn't work, sadly... And then here's my view for the login page: def index(request): session_id = request.session.session_key session_id = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest() auth_url = 'https://auth.atlassian.com/authorize?audience=api.atlassian.com&client_id=*my_client_id_here*&scope=read%3Ajira-user%20read%3Ajira-work%20manage%3Ajira-project&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcomplete%2Fatlassian%2F&state=$'+ session_id +'&response_type=code&prompt=consent' print(auth_url) context = { 'message': 'You are now authenticated' if request.user.is_authenticated else 'You are not authenticated', 'auth_url': auth_url } return render(request, 'core/home.html', context) to explain the stuff below -- the url that I used for Authorization grant before was just: <a href="{% url "social:begin" "* name of backend here *" %}"> which is from the docs https://python-social-auth-docs.readthedocs.io/en/latest/configuration/django.html. It worked for facebook and google for me - but not with atlassian. So I checked the guide for the atlassian oauth2 (https://developer.atlassian.com/cloud/jira/platform/oauth-2-authorization-code-grants-3lo-for-apps/) and it said that I had to use the Jira Platform Rest API Authorization URL. So it worked … -
How to send an array from one view to another
How to send a list from one view to another? I tried to use request.session to send material_id_list but i got error this is my first view def get_autotransactions(request): material_id_list = [] slug = request.POST.get('slug') for index in range(int(request.POST.get('count'))): material_id_list.append(request.POST.get(f'material_id-{index}')) request.session['material_id_list'] = material_id_list return redirect(f'/management/inventorization/transactions/create/{slug}/') this is my second view def form(request, slug): material_id_list = request.session['material_id_list'] extra = 1 if material_id_list: extra = len(material_id_list) TransactionItemFormset = modelformset_factory(TransactionItem, formset=TransactionItemBaseFormSet, fields=('material', 'supplier', 'amount', 'price'), can_delete=True, extra=extra) organization = Organization.objects.get(slug=slug) queryset = TransactionItem.objects.none() transactionItems = TransactionItemFormset(request.POST or None, queryset=queryset, slug=slug, material_id_list=material_id_list) if transactionItems.is_valid(): tran_dict = {} for tran_form in transactionItems: if tran_form.is_valid(): instance = tran_form.save(commit=False) if instance.supplier.id: if instance.supplier.id not in tran_dict.keys(): form = TransactionForm() tran = form.save(commit=False) tran.organization = organization tran.supplier = instance.supplier tran.created_by = Profile.objects.get(user=request.user) tran.status = TRANSACTION_STATUS.NEW tran.save() instance.transaction = tran tran_dict[instance.supplier.id] = tran else: instance.transaction = tran_dict[instance.supplier.id] else: if instance.material.supplier.id not in tran_dict.keys(): form = TransactionForm() tran = form.save(commit=False) tran.organization = organization tran.supplier = instance.supplier tran.created_by = Profile.objects.get(user=request.user) tran.status = TRANSACTION_STATUS.NEW tran.save() instance.transaction = tran tran_dict[instance.material.supplier.id] = tran else: instance.transaction = tran_dict[instance.material.supplier.id] instance.units = instance.material.material.unit instance.remain = instance.amount instance.save() return redirect('management:inventorization:transactions:income') return render(request, f'{BASE_TEMPLATE}/form.html', { 'transactionItems': transactionItems }) this is my url url(r'^get_autotransactions', views.get_autotransactions, name='get_autotransactions'), url(r'^create/(?P<slug>\S+)/$', views.form, name='create',), Dont … -
Python 2.7: urllib2.urlopen(request) not working only in with Django
I can't make a request with urllib2 if I use Django, however, running the script alone works. if I run the script alone with the same virtual environment as Django, it works. the code I am using: data = urllib.urlencode({'somedata':somedata}) url = "https://www.example.com" request = urllib2.Request(url,data) response = urllib2.urlopen(request).read() print response The problem appears when Django tries to run it, I tried switching networks and OS: in Ubuntu, I get this error: <urlopen error [Errno 113] No route to host> in Windows: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond> any idea why this happens? -
How to fix 'Type error "(ModelName)" object is not iterable'?
I'm working on Django Admin, making an action to create several model instances from other model information. I have two models: - Item - ItemCopy I tried to do this through a for loop using: def copy_action(self, request, obj): items_to_copy = [] for item in Item.objects.all(): items_to_copy.append( ItemCopy(name=item.name, description=item.description) ) In others actions I have the same code with another model and it is works, but when I tried to do this throw me 'Type error 'ItemCopy' object is not iterable' -
How to correctly execute query in Django?
I need to execute the SELECT pg_database_size ('mydatabase') query, how do I do this in Django with the Postgres DBMS? I already tried doing the following from django.db import connection cursor = connection.cursor() size = cursor.execute('''SELECT pg_database_size("mydatabase")''') But the resulting size is None. How do I perform this query? The intent is to return the size of the database. -
How to view a non-described column in postgreSQL table so I can add non-null values to it
I am trying to apply changes I made to a Django model (listed below): class Meme(models.Model): # user author = models.ForeignKey(User, on_delete=models.CASCADE, default=0) # img file uploaded by user file = models.FileField(upload_to='memes/images/', null=True, verbose_name="") # keywords associated with the img (similar to hashtags on Twitter) tags = ArrayField(models.CharField(max_length=10, blank=True), size=20, default=list) meme_slug = models.CharField(max_length=200, default=1) published = models.DateTimeField("date published", default=datetime.now) favorited_by = models.ManyToManyField(User, related_name='favorites') disliked_by = models.ManyToManyField(User, related_name='dislikes') # a Meme can either be an original post (no parent) or a comment to another Meme (parent) parent = models.ForeignKey('self', on_delete=models.CASCADE, default=1) children = models.ManyToManyField('self', default=None) To do this, I run 'python .\manage.py makemigrations' and get this traceback: Migrations for 'justmemez': justmemez\migrations\0019_auto_20190514_1902.py - Remove field child_memes from meme <-- changed field name to "children" - Add field children to meme - Alter field parent on meme <-- proof "parent" column exists in db When I try running 'python .\manage.py migrate', I get this traceback: Traceback (most recent call last): File ".\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\John Ward\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\John Ward\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\John Ward\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\John Ward\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, … -
How to change `SECRET_KEY` settings option if django project already deployed?
My django project deployed to Ubuntu server was working fine. In my project i'm using currency switcher, which allows to change price currency depending on which currency customer has chosen in corresponding html form (in a nutshell form sends POST request with currency code to view, where price converted from one currency to another). But then i decided to change SECRET_KEY. Once in my django log files i noticed an error like django.security.SuspiciousSession WARNING Session data corrupted than it disappears.. But than i noticed that currency switcher works wrong. My questions are: 1. Could the changing of SECRET_KEY cause errors in the project(maybe related with csrf tokens of html forms with POST method somehow)? 2. If so, how to eliminate the negative consequences of changing SECRET_KEY(get working project back)? 3. What is the right way to change SECRET_KEY in the deployed django project? Hope you'll help guys.. -
How do I apply a code snippet to a Django input form?
How do I apply a code snippet to a Django input form? ex Python code js code html code and so on like a slack enter image description here -
Django Allauth Pipeline Not Creating Profile Table
Using django allauth for authentication. Would like to create a userprofile table on user authentication. App is name users and function is defined in pipelines.py Defined a function that created a separate user profile table. Added this function to SOCIAL_PIPELINE. During authentication, the function is triggered in the pipeline causing the population of the userprofile table. Have no idea why this is not working. All suggestions welcome def create_profile(backend, user, response, *args, **kwargs): user_profile = UserProfile.objects.filter(user_id=request.user) if user_profile is None: UserProfile.objects.create(user=request.user, referral_code=generate_code()) else: if user_profile.referral_code is None: user_profile.referral_code = generate_code() user_profile.save() SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'users.pipelines.create_profile', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
django.db.utils.IntegrityError: null value in column "address" violates not-null constraint
When I create a Location instance, i get this error. django.db.utils.IntegrityError: null value in column "address" violates not-null constraint this is my locaiton model. class Location(DirtyFieldsMixin, TimeStampedModel): id = SmallUUIDField( default=uuid_default(), primary_key=True, db_index=True, editable=False, verbose_name='ID' ) name = models.CharField(max_length=100) address = models.TextField(blank=True) timezone = models.CharField(null=True, max_length=100) phone = PhoneNumberField(blank=True) email = models.EmailField(blank=True) the payload looks like this when posting a locaiton. {'name': 'Beij the Sage', 'address': None, 'latlon': None, 'timezone': 'America/Los_Angeles', 'phone': '', 'email': ''} i have blank=True for the model so having None for the value of address shouldn't throw this error. -
Django: Return dictionary in ListView context
I have this ListView that handles the pagination but i need to return more data so i can use in a form that i have in home screen. class CarListView(ListView): model = Car template_name = 'home.html' context_object_name = 'cars' ordering = ['-created'] paginate_by = 6 limit = 12 Initialy was like this, and it worked well # def get_queryset(self): # return Car.objects.all()[:self.limit] But when i overrided context_data to return car_makes in the context, it broke the pagination, so it returns the context that i want but without pagination. def get_context_data(self, **kwargs): paginate_by = 6 cars = Car.objects.all()[:self.limit] car_makes = CarMakes.objects.all() context = {'cars': cars, 'car_makes': car_makes} return context Is there any way around this, so i can return a dictionary and still keep the pagination? -
Is there a solution to read a stream data from another source while django is running
I have a web app based Django and I need read a stream from another source (telnet or serial port) and save the data into a database while the application is running, there is a solution for that? -
I entered the code as textarea but the new line does not apply, so how do I change it?
I entered the code as textarea but the new line does not apply, so how do I change it? Do you know and what should I do in order to get the Python code color here? ex) from django.db import models from django.contrib.auth.models import User from django.urls import reverse from markdownx.models import MarkdownxField from markdownx.utils import markdown # Create your models here. class CssImage(models.Model): title = models.CharField(max_length=50) head_image = models.ImageField(upload_to='blog/%y%m%d', blank=True) author = models.ForeignKey(User, on_delete=True) created = models.DateTimeField(auto_now_add=True) -
Django : AWS Load Balancer : log: WARNING - Not Found: /gw.json
My server is giving log: WARNING - Not Found: /gw.json every half second. It seems to occur only once I turn my AWS load balancer health check on. This is new and was not doing this before. log: WARNING - Not Found: /gw.json [14/May/2019 17:00:20] "POST /gw.json?a=s.gw.dev.timer.count&gwId=04200310xxxxxxxxxxxxx&sign=646e9321d165xxxxxxxxa5c7 HTTP/1.0" 404 4078 Django 2.1 Postgres NGINX server I restarted the server and nothing changed. If I go directly to the server IP (vs. the load balancer) this does not occur. -
Model field null=True but then says null value violates not-null constraint
I have a field in my Model Entry called pause_time that has blank=True and null=True. Then when I create a new object in the model it says psycopg2.IntegrityError: null value in column "pause_time" violates not-null constraint. This was previously working and then I added a new app to the project, ran migrations and now im getting this error. Models.py class Entry(models.Model): TUID = models.IntegerField() start_time = models.DateTimeField() end_time = models.DateTimeField(blank=True, null=True, db_index=True) seconds_paused = models.PositiveIntegerField(default=0) pause_time = models.DateTimeField(blank=True, null=True) date_updated = models.DateTimeField(auto_now=True) hours = models.DecimalField(max_digits=11, decimal_places=2, default=0) pause_time_end = models.DateTimeField(blank=True, null=True) def _str_(self): return self.TUID views.py def home(request): if request.method =='POST': Entry.objects.create( TUID = request.user.id, start_time = timezone.now(), end_time = None, seconds_paused = 0, pause_time = , date_updated = None, hours = 0, pause_time_end = None, ) -
Non repeatable fields in models
Is there a directive in models.py that allows me to have a value not repeated in a field? I'm making a table of people and I need the email field not to be repeated. -
Read files in django without saving
I use request.FILES in test django project, but dictionary always empty I use django 1.11.17 views.py class UploadMenuView(CreateView): def post(self, request, *args, **kwargs): file = request.FILES.popitem() print(file.name) return HttpResponse(file.name) templates/admin/change_list.html ... {% csrf_token %} <input type="file" value="Select file" name="file"/> <input type="submit" value="Upload menu"/> </form> ... urls.py url(r'upload-menu/', UploadMenuView.as_view(), name='upload-menu') All my tryes end with Exception Value: 'popitem(): dictionary is empty'. But i see my file in F12 as POST request. key: file, value: file.txt -
How to show a blob image on HTML page in Django?
I have a image in the blob field in my mysql database. The images are displayed correctly using the base clients, but I can't display the image in html page. I try to use base64 converter for returned bytes. models.py: class BlobImg(models.Model): photo = models.TextField(null=True) views.py: def home(request): obj = BlobImg.objects.get(id=1) image_data = base64.b64encode(obj.photo) data = { 'news': News.objects.all(), 'title': 'Главная страница', 'imgs' : image_data } return render(request, 'app/home.html', data) html: <img src="data:image/jpeg;base64,{{ imgs }}" class="img-thumbnail"> I get bytes string in "imgs", but it doesn't work -
Django Channels 2: two authentication methods
how i can implement multiple authentication methods for my django channels app? I mean, i have a Token based auth and a AuthMiddlewareStack. How i can mantain these two authentication in order to manage the in session django auth for my internal application websocket data consumer/notify/etc... and adopt the websocket token authentication for the third-party apps? Here is my routing.py: application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( app.routing.websocket_test ) ), "websocket": TokenAuthMiddlewareStack( URLRouter([ app.routing.websocket_test ]), ) }) Thanks. -
ListView View object has no attribute 'object'
I used to have the view as a DetailView but when I wanted to add pagination I needed to change the view to a ListView. But since doing this it has started throwing this error: 'CategoryDetailView' object has no attribute 'object' I believe I need to assign category's to self but I am not 100% sure how to do this. I have tried: def category(self , request , *args , **kwargs): self.object = self.get_object() return self.object But it didn't work so this is what it is at the moment. View: class CategoryDetailView(ListView): model = Category paginate_by = 1 def get_context_data(self, **kwargs): context = super(CategoryDetailView, self).get_context_data(**kwargs) context['category_posts'] = Post.objects.filter(live=True, category=self.object) return context Thanks guys -
How can I create a form that has objects for fields
I am creating a leaderboard app that has Player and Game objects. I created a form using my own html code rather than Django forms (looks better in the template) where you can add a game that takes in a name for player 1 and player 2, and their respective goals. If I use ModelForm, it checks that the values are valid but since the form input is characters but the model object game has fields for objects, the query is invalid. I have tried querying the database before I try GameForm.is_valid and manually assign the players from the database using the input usernames but I get this error: That choice is not one of the available choices.</li></ul></li><li>player2<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> [14/May/2019 20:08:04] "POST /elousers/elosearch/ HTTP/1.1" 200 9271 How can I do this without making the form a modelchoicefield? is there an alternative or should I try a different route completely. views.py for the form (there is a second form above this form so I only provided the code for GameForm) elif 'addgame' in request.POST: data = request.POST.copy() try: player1 = Player.objects.get(name=data['player1']) data['player1'] = player1 except Player.DoesNotExist: render(request, 'elousers/elosearch.html', {'game_display': … -
How to call the django save method on an update
I would like to "disable" an update() method by essentially forcing it to call a save on every object in django. How would I do that? Currently I have: class HandleQuerySet(QuerySet): def update(self, *args, **kwargs): for x in self: x.save() But this doesn't seem to be passing the args to the save method -- as in, it doesn't save anything. How would I properly do this?