Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create model for existing database table in django
I have an old table in the database. And I want to create a model in Django application. After creating a model and I used migrate command then it created a new table with its own name. -
Create a django api that wil read and store the contents of a file
I need to create a django api that wil read the contents of a file and store it in the database. -
Check value in database and remove value from dropdown
I have loop, inside that there is a dropdown and I want to check in database and remove value from dropdown accordingly. {% for item in items %} <select name="somename" class="someclass"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> {% endfor %} So initially it looks like this. So when value "1" is selected then it should not display throughout the loop and it should not display if it is already selected and saved in database. -
form validation returns False
I'm dealing with form validation. For some mysterious reason my form.is_valid() returns false. I looked over other related topics here on SO but none of them helped. I'm getting no errors from form.errors. view: def index(request): form = TestCaseForm() if request.method == 'POST': if form.is_valid(): TestCase.objects.create( name=request.POST['name'], documentation=request.POST['documentation'], steps=request.POST['steps'], tags=request.POST['tags'], setup=request.POST['setup'], teardown=request.POST['teardown'], template=request.POST['template'], timeout=request.POST.get(int('timeout')), ) return redirect('/list') else: for i in form.errors: print(i) return render(request, 'index.html', {'form': form}) forms.py: class TestCaseForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Name'}), label='') documentation = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Documentation'}), label='') steps = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Steps'}), label='') tags = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Tags'}), label='') setup = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Setup'}), label='') teardown = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Teardown'}), label='') template = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Template'}), label='') timeout = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Timeout (optional)'}), required=False, label='') models.py: class TestCase(models.Model): """ The test case """ name = models.CharField(max_length=200) documentation = models.CharField(max_length=2048, blank=True) steps = models.CharField(max_length=2048, blank=True) tags = models.CharField(max_length=200, blank=True) setup = models.CharField(max_length=2048, blank=True) teardown = models.CharField(max_length=2048, blank=True) template = models.CharField(max_length=200, blank=True) timeout = models.IntegerField(default=10) def __str__(self): return self.name html: <form method="POST" action="/"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn … -
Django create/save and atomic requests
I am running Django (1.11.20 with ATOMIC_REQUESTS: True) and Postgres, and have a Django view that basically does: job = Job(name='hello') job.save() files = JobFile.objects.create(job_id=job.id, file='myfile.txt') Most of the time, this works fine. But every so often, another process (that is executed by cron) checks the JobFile table and finds it not containing a record for a given existing Job, when doing: jobs = Job.objects.filter(timestamp=my_timestamp) JobFile.objects.filter(job__in=jobs) It reports this in a log and errors and when I check somewhat later the DB contains a JobFile just fine. I am scratching my head as to why it doesnt find JobFile records, and now I investigated and found that in the lastest occurrences of this problem, the cron process initiated about 0.1s before record creation and finished closely after, which made me suspicious that there is some sort of timing problem. But my (limited) understanding would be that when this is all in a single view, ATOMIC_REQUESTS would ensure that both objects exist. My other suspect is the create method but that seems to return nicely after calling save according to its source. What am I missing? -
login/check the username and password from database in Django website using post request
i have create a blog website where i want to do login of user whose username and password are saved in a database table name "myuser" i ll already fetch the username and password from post request in my function , NOW HOW I CAN COMPARE THIS VALUE FROM MY ALREADY CREATED TABLE VALUES TO CHECK USERNAME AND PASSWORD IS CORRECT OR NOT -
specify multiple variations for field in database using factory boy
I am new to using the tool django factory boy. I would like to know how can we specify multiple test data patterns for a field in database model using the factory class of django factory boy. -
How to prevent 404 error when retrieving an image from my static folder
My Django project includes a company logo which is stored inside the static folder and displayed in the navbar on each page. The logo displays on some pages, but for some reason it returns a 404 error on others. I can't spot any correlation between the pages that return a 404. Does anybody have any idea why I've encountered this problem? # base.html <a class="navbar-brand" href="{% url 'index' %}"> <img src="../static/img/acceler8_logo.png" id="acc-logo"> </a> # settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) -
How to send email from just the user who are logged in to an official account?
I am trying to send email from the user who is logged in to an account which I have given bilalkhangood4@gmail.com. But I have typed it manually. I want whenever I log in, it should send an email only from that user account instead of writing it manually. How to do it? I used User also but it is giving me TypeError at /ViewSendEmail/ object of type 'ModelBase' has no len() settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', User, #FROM ['bilalkhangood4@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
Procsssing csv files from upload in formtools (django)
Using formtools for django, I am trying to process the files being uploaded by the user in each step. So doing something likes this: def do_something_with_the_form_data(form_list): """ Do something, such as sending mail """ form_data = [form.cleaned_data for form in form_list] file = form_data[1]['bankA'] print(form_data[1]['file1']) f = open(file, 'rb') reader = csv.reader(f) ... is returning an error What is best practice for this? How can I properly read the files being uploaded by the user? P.S. Let me know if you want to see the forms or entire view -
Django: How can I include a variable within a nested for loop?
I need to include a Django template language variable within a nested 'for' loop to obtain page specific information in the dictionary. The structure of 'request.session.record_input' is: request.session.record_input = {'1':{'Data1':Data1, 'Data2':Data2} ,'2':{ etc... I've including it as just the variable name although I'm aware that this wouldn't work, this is purely to show where the variable would be. {% for page in request.session.record_input.keys %} <div class="container" style="text-align:center; vertical-align:middle;"> {% for key, value in request.session.record_input.page.items %} <div class="row"> <div class="col-2 centreObject"> <p1> {{ key|extract_comname }} </p1> </div> <div class="col-3 centreObject"> <p1>{{ value }}</p1> </div> </div> {% endfor %} </div> <hr> {% endfor %} I would normally access this in Python via: for page in request.session.record_input.keys(): for key, value in request.session.record_input[page].items() But you can use '[]' within the Django template language Any help will be greatly appreciated! -
How can I set query params in a url of django rest framework?
I have an API that i need to remove something from cache of Redis So I build a view and sync it to a url but I keep getting HTTP_404 (not found). class ExpireRoom(APIView): permission_classes = (IsAuthenticated, ) def delete(self, request, format=None): room_manager = RoomManager() room_identifier = self.kwargs['room_identifier'] is_success = room_manager.delete(room_identifier) if is_success: return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) Here's my url in urls.py: urlpatterns = [ url(r'^expire-room/(?P<room_identifier>\w+)/$', ExpireRoom.as_view(), name='core_ExpireRoom_deletingRoom') ] -
'Manager' object has no attribute 'filter_by_instance'
class Post(models.Model, HitCountMixin): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") content = RichTextField() draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) read_time = models.IntegerField(default=0) # models.TimeField(null=True, blank=True) #assume minutes updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) tags = TaggableManager(blank=True, related_name="posts_tags") hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') objects = PostManager() def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-timestamp", "-updated"] def get_markdown(self): content = self.content markdown_text = markdown(content) return mark_safe(markdown_text) @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type -
django: allocate user.is_staff= True from permission group
I have tried to allocate is_staff to my new user, but it doesn't work. I have also tried if request.POST.get('group_name') == 'Staff': user.is_staff = True, without any success. views # Register a new user @login_required @group_required('Staff') def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() if form.cleaned_data['group_name'] == 'Staff': user.is_staff = True group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) messages.success(request, "User has been added!") return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) forms: class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) is_active = forms.BooleanField(initial=True, required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', ) -
Make checks in backend before loading completely new page
Imagine u're on web page and clicking the button. Then from JS through ajax, for example: # .js file $.get(url, data) .done((data) => { window.location.href = data['url'] # loading new page }) .fail((data) => { alert(data['error']); # error message in alert window }) u reffer to some def: # views.py def course(request, id): ... # collecting some data from DB and also making checks course = Course.objects.get(id=id) # What if Course.DoesntExist return JsonResponse({'url': 'path tothis def again but not as ajax_request'}) # OR return render(request, 'page.html', { ... }) BUT! There's some thinkings about it: So before I wanted to return render I'd like to make some checks (when getting necessary objects from DB) and in case of errors (Exception) catch it and show as alert message without getting to the new page. But if all is OK I am as usual loading new page. But that means def has to be able to return render and JsonResponse responses, work not only with ajax_request but with usual request. How can I make it? -
Django form doesn't send POST request and site freezes
I'm trying to set up a basic forum site for my coworkers to use. The problem is that when I attempt to log in to the site, no POST request is sent (shown by the terminal) and the entire website becomes unresponsive. In fact, it's sitting in another browser tab buffering infinitely as I type this. I followed Corey Schafer's Django tutorials to lay the groundwork of the site, as I've never done anything with Django. I finished the tutorial series, and the site was fully functioning (minus the password-reset emails). After finishing the tutorials, I added a tagging feature to the post-form through django-taggit. I had to wait until the head of IT could input some files into the company site to access emails (through SendGrid), but I finally was able to send a single password-reset email to myself. I successfully reset my password, and this is where things started to go wrong. I wanted to change my password back, so I went through the process again, but this time when I pressed the "Send Email" button on the password-reset page, the buffering icon (on Chrome), started going backwards and wouldn't stop. I didn't check my console when this … -
Squashing legacy django appilcation that has a lot of data migrations
We have a legacy application with a lot of different business flows and data migrations. Out migrations have got to a point where migrations run very slow. We haven't quite squashed the migration in a decade We are looking at an approach where we have data migrations in a different app. And then squash the existing migrations -
about reverse url for category get_absolute_url
this is my Category get_absolute_ur def get_absolute_url(self): return reverse('products:categories_display', args=[self.id, self.slug]) This is my product view class category_slug_view(ObjectViewedMixin, DetailView): queryset = Category.objects.all() template_name = "products/product_page.html" This is my product url url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', category_slug_view.as_view()), -
using analytics in django by installing it's package
I am new to django and I'm trying to find a method to count the views of my website, so I encountered a package which name is analytic and i installed it with pip. first I need some help to introduce me what is the meaning and functionality of analytics and then help me to work with that package which i had installed it from pip. thanks in advance -
Factory boy's post_generation hook is not setting attribute on the model object after upgrading Django to 2.2
Consider the case of following two factories. Some part of the code might not make sense as I've tried to anonymise classes and fields. class FactoryA(factory.django.DjangoModelFactory): class Meta: model = ModelA name = 'John' @factory.post_generation def post_hook(self, create, extracted, **kwargs): post_generated_objs = [] for i in range(3): post_generated_objs.append(SomeOtherFactory(id=i+100)) self.post_generated_objs = post_generated_objs return post_generated_objs class FactoryB(factory.django.DjangoModelFactory): class Meta: model = ModelB some_data = factory.LazyAttribute(lambda obj: obj.model_a.post_generated_objects[0]) It used to work as expected before upgrading Django to latest version, i.e. 2.2. I am using latest version of factoryboy as well. The issue here is that factoryboy is not setting the attribute post_generated_objs to the returned object of ModelA created by FactoryA. The error I get is AttributeError: 'ModelA' object has no attribute 'post_generated_objs' Python 3.7 django==2.2.4 factory-boy==2.12.0 pytest==4.4.0 pytest-django>=3.5 pytest-xdist==1.28.0 -
Creat User by Api in django with rest framework !!1
some problems with creating user in Django!!!! Hello guys H want to create user by Api in Django and i confused how to do that. the first thing is should i logged in with superuser account and then create new user(or can i create anonymously? is that secure? ) The other questions is how to Authenticate anonymous user if anonymous person can create user. -
How to test postgres statement_timeout in django
I have added both connect and statement timeouts for a postgres database in my django service. So the relevant django setting looks like; _CONN_TIMEOUT = 5 _STATEMENT_TIMEOUT = 3000 # millisecond DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "mobile_loans", # ..., "OPTIONS": { "connect_timeout": _CONN_TIMEOUT, "options": "-c statement_timeout={0}ms".format(_STATEMENT_TIMEOUT), }, } } And then, I'm writing tests like this; class DbTimeoutTest(TestCase): def test_db_statement_timeout(self): """ test carrying out an SQL query that takes longer than the configured postgres `statement_timeout` value """ # set statement_timeout to 1 millisecond mock_s_timeout = 1 with self.settings(_CONN_TIMEOUT=5, _STATEMENT_TIMEOUT=mock_s_timeout): self.assertEqual( settings.DATABASES["default"]["OPTIONS"]["options"], "-c statement_timeout={0}ms".format(mock_s_timeout), ) Book.objects.create(name="Hello") However, that test is not working. - The assert self.assertEqual does not pass, meaning that the setting override did not work. - I would expect the Book.objects.create statement to fail with timeout but it does not. So questions; 1. How do I test for postgres statement_timeout?(been able to also test for connect timeout would also be a plus) 2. How do I catch, the statement timeout error in my code? -
Heroku CI: run django tests with postgis
I have a django project with postgis and I want to run tests with Heroku CI. I want to use heroku-postgresql:in-dyno addon's plan as it recommended. But seems like in-dyno plan doesn't support postgis extension. Is it possible to setup the postgis extension manually? -
How to have a writable file ready on google cloud bucket for using with library save functions
So I am using moviepy library to get a gif out of a video file that is located on my google cloud bucket. now I am using google-cloud-storage package for the save & read operations so far. But I was using the package methods. Now moviepy requires a filepath as a parameter to run it's write_gif method to produce the gif. After a while I figured I can use gsutil sort of solution with it. I came across gcsfs. But problem is I can't figure out how to have the file writable for write_gif to work since even here I am able to open the blank bucket gif file using open method on gcsfs object vfile = 'https://storage.googleapis.com/test.appspot.com/dir/sample.mp4' tfile = 'https://storage.googleapis.com/test.appspot.com/dir/sample.gif' #non-existant-file clip = VideoFileClip(vfile) gifClip = clip.subclip(8, 10) target_gc_thumb = bucket.blob('dir/sample.gif') target_gc_thumb.upload_from_string('',content_type='image/gif') #blank-gif-file-saved fs = gcsfs.GCSFileSystem(project='test') with fs.open('test.appspot.com/dir/sample.gif', 'w', metadata={"Content-Type":"image/gif"}) as f: gifClip.write_gif(f,fps=5) #raises-error-since-it-expects-a-local-file-path clip.close() I get this error since I not passig a string that represents the local file path : Could not find a format to write the specified file in mode '?' -
Django Model QuerySet: RuntimeError generator raised StopIteration
I've recently updated my Django to version 2.2.4 and python to 3.7, and I encounter this error randomly: Traceback (most recent call last): File "/foo/venv/lib/python3.7/site-packages/django/db/models/query.py", line 73, in __iter__ obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/foo/venv/lib/python3.7/site-packages/django/db/models/base.py", line 511, in from_db for f in cls._meta.concrete_fields File "/foo/venv/lib/python3.7/site-packages/django/db/models/base.py", line 511, in <listcomp> for f in cls._meta.concrete_fields StopIteration I tried to debug the code to find out what's happening, and it seems the from_db function in django.db.models.base.py is causing this error: # /foo/venv/lib/python3.7/site-packages/django/db/models/base.py ... @classmethod def from_db(cls, db, field_names, values): if len(values) != len(cls._meta.concrete_fields): values_iter = iter(values) values = [ next(values_iter) if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields ] new = cls(*values) new._state.adding = False new._state.db = db return new ... next(values_iter) is raising this error and it seems that Django devs should surround that with try except block to make this work in python 3.7, but my question is, is there a way to overcome this issue as a temp fix or not? thanks.