Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AssertionError during update view test in django
I have an application in django 2.2 and I'm trying to test update with factory-boy. I get an error: AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) I will be greatfull for every hint view code: class SpotUpdateView(UpdateView): model = Spot fields = ['title', 'description'] template_name = 'spot/spot_update.html' context_object_name = 'spot_detal' def get_success_url(self): return reverse('spot_detail_url', kwargs={'slug': self.object.slug, 'id': self.object.id}) url: path('post/update/<str:slug>/<int:id>/', login_required(SpotUpdateView.as_view()), name='spot_update_url'), unit test code def test_spot_update(self): self.client.login(username='user', password='123!') spot_object = SpotFactory.create() response = self.client.post(reverse('spot_update_url', kwargs={'id': spot_object.id, 'slug': spot_object.slug}), {'title': 'My new title', 'description': 'After update'}) self.assertEqual(response.status_code, 302) spot_object.refresh_from_db() self.assertContains(response, 'After update') -
django form queryset getting user data and filtering by team
I have a User-Team model setup. When a user creates a "project" they can assign the project to people on their team. However, when I use a queryset in my multiple select form field, it of course shows all users in the entire database. How can I filter just on the user's team? The code in my forms.py for the init method doesn't work at all...so hoping for some guidance. models.py class CustomUser(AbstractUser): username = None first_name = models.CharField(max_length=255, unique=False, verbose_name='first name') last_name = models.CharField(max_length=255, unique=False, verbose_name='last name') email = models.EmailField(max_length=255, unique=True) user_team = models.ForeignKey('Team', on_delete=models.SET_NULL, null=True, blank=True, related_name='userteam') team_leader = models.BooleanField(default=False) team_member = models.BooleanField(default=False) # user types membership_type = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) # Abstract User fields active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' #MAIL_FIELD = 'email' REQUIRED_FIELDS = [] # email/password will be required by default def __str__(self): return self.email class Team(models.Model): team_id = models.BigAutoField(auto_created=True, primary_key=True) team_name = models.CharField(max_length=35, null=False, default='YourTeam') team_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) num_users = models.IntegerField(default=1) team_leader = models.ForeignKey(CustomUser, on_delete=models.CASCADE) def __str__(self): return str(self.team_id) forms.py class CreateTaskForm(forms.ModelForm): name = forms.CharField(label='Task Name') description = forms.CharField(label='Description', widget=forms.Textarea) users = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple(), queryset=CustomUser.objects.all()) class Meta: model = Task fields = ['name', 'description', 'team_task', 'date_due', 'users',] … -
cannot import name 'Preference' from 'djangobin.utils'
In models.py the following error occurs when I use from .utils import Preference as Pref: from django.db import models from .utils import Preference as Pref Error: cannot import name 'Preference' from 'djangobin.utils' Python Version - 3.8.2 Django Version - 3.0.6 Windows 10(64-bit) PIP Version - 19.0 Tool - Pycharm Reference Website - Overiq Reference Website Link- https://overiq.com/django-1-11/basics-of-models-in-django/ -
Django fetching file from an URL and save it to a model FileField with S3
I need to fetch a file from an API and then save it in an Survey object. It seems to be working fine, i.e. I can fetch the file and save it where I need to, but a ConnectionAbortedError is raised and the file is uploaded twice. The one saved in the model being the last one. Here is the views.py: def send_survey(request): ## Using convertApi to merge PDFs convertapi.api_secret = settings.CONVERTAPI_SECRET result = convertapi.convert('merge', {'Files': [files_url_list]}) ## Getting the file from the url r = requests.get(result.file.url) ## Saving the file to the Survey object if r.status_code == 200: contentFile = ContentFile(r.content) s = Survey() s.file.save('Last survey', contentFile, save=True) messages.success(request, "The literature survey saved successfully!") else: messages.error(request, r.status_code) return redirect('homepage') And the models.py: class Survey(models.Model): date = models.DateField('Date', default=date.today) file = models.FileField('Survey', upload_to='literature_survey/previous_surveys', default=None) sent = models.BooleanField('Sent?', default=False) def __str__(self): return f"Survey #{self.pk}" And I get the following error: ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 62615) Traceback (most recent call last): File "C:\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 182, in … -
Media Directory in Django
What are MEDIA_URL and MEDIA_ROOT in django and why do we need to use them? Can't we directly add images directly into the database by logging in to admin account. -
Got "function missing required argument 'month' (pos 2)" error while adding a DateField to models.py
I am a Django beginner and I am trying to make a Biography app, I am following the official django documentation for learning the framework. So when I create a DateField in models.py as it was shown in docs, I got an error while I ran the server it says "function missing required argument 'month' (pos 2)" what should I do? Please help #models.py from django.db import models from django.utils import timezone import datetime # Create your models here. TYPE = ( ('politician','POLITICIAN'), ('poet','POET'), ('author','AUTHOR'), ('actor','ACTOR'), ) class About(models.Model): title = models.CharField(max_length = 200, default='') context = models.CharField(max_length = 200, default='') born_on = models.DateField('Born on') died_on = models.DateField( 'Died on') main = models.TextField(default='') category = models.CharField(choices = TYPE , default = 'poet', max_length = 10) image = models.ImageField(blank=True, default='', upload_to='static') updated_on = models.DateTimeField(auto_now = True) created_on = models.DateTimeField(auto_now_add = True) def __str__(self): return self.title def was_published_recently(self): return self.created_on >= timezone.now() - datetime.timedelta(days=1) -
How to link a VueJs frontend to a Django backend? [closed]
Recently I have created a signup page using VueJs as frontend and Django as backend. Now I want to link them so that I can save my user data to the database and reuse it from there and have no clue how to do it. -
Django: Button feeds from database entries
I'm trying to solve a problem that i don't find on google ( apparently ). I got a Django Project which allows People to get registered. I got my form which is something like this: forms.py class RegistrationForm(UserCreationForm): """docstring for RegistrationForm""" email = forms.EmailField(required=True) studio_associato = forms.CharField(required=True) nome = forms.CharField(required=True) cognome = forms.CharField(required=True) class Meta: # define a metadata related to this class model = User fields = ( 'username', 'nome', 'cognome', 'studio_associato', 'password1', 'password2' ) I managed to correctly store and visualize the User in the DB and the admin page. What i'm trying to get is to let this field 'studio_associato' be a field that when a User register himself through the registration form, he have to specify from which (in Italian Studio = Office ) Office he's working for. Each User can only work with an Office unlike Office could have obviously more Users linked to it. My final product i'm trying to achieve is a field: "Studio associato" (showed during the registration form of the User) which displays all the Offices registered till that moment and let you Click or Search a specific Office to link that user for. Note that my html page is just … -
DjangoTemplate + Javascript - How to compare javascript variable with django multiple values
How to compare javascript variable "var1" with django multiple values. If a answer is ok, program should say ¡very good! Django + Javascript: <script> var var1 = document.getElementById("userAnswer").value; if ( {% for textEUS in question.textEUS.all %} var1 == {{ textEUS }} {% endfor %} ){ alert(¡Very good!); } </script> only Django: {% for textEUS in question.textEUS.all %} {{ textEUS }} {% endfor %} only Javascript: <script> function tocorrect(){ var var1 = document.getElementById("userAnswer").value; if (var1 == "answer"){ alert(¡Very good!); } } </script> -
Django 2 forms on 1 page,1 is ajax and 1 is not
Using class based views, I can successfully process my normal form, my ajax form returns valid and all is well but I'm really struggling to figure out where I should be handling the ajax request, should I be doing it in get_context_data or in the form_valid method, in either case it doesn't process it correctly def get_context_data(self, **kwargs): context = super(POEdit, self).get_context_data(**kwargs) context['document_header'] = self.object if self.request.POST: #Posted Form if self.request.is_ajax: self.get_ajax_response() context['form_comments'] = DocumentCommentsUpdateForm(self.request.POST, instance=self.object) context['form_lines'] = DocumentFormSetUpdate(self.request.POST, instance=self.object) else: #No Post context['form_lines'] = DocumentFormSetUpdate(instance=self.object) context['form_comments'] = DocumentCommentsUpdateForm() context['comments'] = self.get_comments() return context get ajax response below, its entre def get_ajax_response(self): data = { 'pk': 'pk', } return JsonResponse(data) there is appropriate code to send and receive a response in the view $('#comments-form').submit(function(e){ e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ url : "{% url 'po:edit' document_header.id %}", type : "POST", data : serializedData, success : function(json) { $('#id_comment').val(''); console.log(json); console.log("success"); }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); console.log(xhr.status + ": " + xhr.responseText); } }); } ); -
<module 'accounts.urls' from 'C:\\Users\\rajus\\website\\simplesocial\\accounts\\urls.py'>' does not appear to have any patterns in it
django.core.exceptions.ImproperlyConfigured: The included URLconf ' accounts.urls my project urls signup -
What would be the best option to host a personal website? [closed]
I would like to find the best solution to rent a server to host a personal website running Django. It'd be better if it runs on Linux and other than that, the only thing as I said is that it will be a Django website. Traffic should be low as it will only host showcase projects, as in other CV-looking websites you may have encountered. I know nothing about server/hosting services, but I know how to host on a home server though. I looked in AWS but man... Too many offers, pricing is really shady. I can be down with it but for now I don't really understand. Some of you must have dealt with this situation, I'd like to have your opinion. What would be my best option ? -
What should i do either extend django base user model or create custom user model?
I am starting a social network kind of website as a hobby project and have knowledge of working with Django but due to less experience I am confused about my user model my user will have multiple fields and I want to give different permissions. P.S I am really sorry for being so vague -
Prepopulating a Django model with large amounts of data
I'm trying to load a list of Rolling Stone's top 500 songs - as well as other characteristics such as their rank, description, cover image, ect. - into a Django database so that I can display a random song each day on m. I managed to scrape the list from the site well enough, but I'm having trouble loading the list into the database as a single instance of the model I created, as opposed to 500. I tried writing a migration to do it for me, but I don't think it worked properly. I've attached the code below, let me know if you see anything: # Create function to actally load data into table def loadSongs(apps, schema_editor): # Initialize counter to iterate through site pages, initialize album rankings, create model, then scrape pages one by one #top500songs = Songs() links = np.arange(1,11,1) rank = 500 songList = [] for link in links: # Get and store link to page, initialize lists to store data values page = requests.get('https://www.rollingstone.com/music/music-lists/500-greatest-songs-of-all-time-151127/?list_page=' + str(link)) soup = BeautifulSoup(page.text, "html.parser") # Look for song entries on the page, stored as articles with "item" class. Sleep for a bit to prevent overloading server songs = soup.find_all('article', … -
How to add a new view to django-oscar
I don't think I fully grasp the django-oscar documentation. I am trying to add a new view, a home view at / of the site. But whatever I seem to do it keeps going to /catalogue/ when I want to access / instead. it says I should do the following: from oscar.apps.offer.apps import OfferConfig as CoreOfferConfig from .views import IndexView from django.conf.urls import url class OfferConfig(CoreOfferConfig): def ready(self): super().ready() self.index_view = IndexView def get_urls(self): urls = super().get_urls() urls += [ url(r'^$', self.index_view.as_view(), name='index'), ] return self.post_process_urls(urls) and this is in myproject/myapp/offer/apps.py. myapp was created following the django-oscar tutorial which involved running the command ./manage.py oscar_fork_app order myapp. general breakdown of the folder: myproject: - myproject - settings.py ... - static - myapp - order - offer - apps.py - __init.py - templates manage.py my urls.py in myproject looks as follows: from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.conf.urls.static import static from django.conf import settings from django.apps import apps urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), url(r'^', include(apps.get_app_config('oscar').urls[0])), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the view I am trying to add is very very basic at the moment: from django.views.generic import TemplateView class IndexView(TemplateView): template_name = "pages/index.html" … -
"No attribute" error in the Django Shell through ForeignKey
I have a models.py file from django.db import models class PersonalInformation(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) def __str__(self): return self.first_name class OrderInformation(models.Model): personalInformation = models.ForeignKey(ContactInformation, on_delete=models.CASCADE) item_name = models.TextField(blank = False) price = models.DecimalField(max_digits = 8, decimal_places = 2) def __str__(self): return self.item_name in the shell am running following command: from web.models import PersonalInformation, OrderInformation k = ContactInformation.objects.get(pk = 1) it outputs <PersonalInformation: john@test.com> which is correct. However, which I do this k.orderInformation_set.all() it get the error AttributeError: 'PersonalInformation' object has no attribute 'orderInformation_set' Isn't Django supposed to generate this orderInformation_set field automatically? -
Image not Showing in Template
I am trying to add an image in a page but I keep getting AttributeError: 'Setting' object has no attribute 'image' I have used Images several times in other models the same project but I don't know what I might be missing here Here is the Models.py class Setting(models.Model): title = models.CharField(max_length=60) about_text = RichTextUploadingField(verbose_name="About Us Text") about_image = models.ImageField( blank=True, upload_to='Marketing', verbose_name="About Us Image") def __str__(self): return self.title def get_image_url(self): return "%s/%s" % (settings.MEDIA_URL, self.image) Here is the views def who_we_are(request): setting = Setting.objects.get() template = 'who_we_are.html' context = {'setting': setting} return render(request, template, context) Here is the template {% extends "base.html"%} {% block content %} <div class="view" style="background-image: url('{{ setting.get_image_url }}');></div> <div class="container pt-4"> {{setting.about_text|safe}} </div> {% endblock content %} -
Secure data PUT from IoT devices to DRF backend
I have not been able to find any helpful material on this subject. I am looking for a primer on how to restrict certain endpoints in DRF to accept data from only certain 'whitelisted' IP address. I am aware of adding the IPs to 'REMOTE_ADDR' settings but that doesn't fully solve my problem. Users will have IoT devices with static IPs. Data streaming from these devices need to be added to the db in a secure manner with the User/tenant specific information along with it. I am thinking IP restriction might be the best way of going about it. Please let me know if there are other better ways. Frameworks used: DRF django_tenants Postgresql -
How would you design Forums boards models?
i have a question for you guys, I'm inexperienced, still learning, slowly building my portfolio to try and get my first job as a Junior Currently I'm building Discussion forum app, I'm trying to admin be able assign restrictions to who can view and/or add new posts to each BoardGroup/Board/SubBoard with the lowest child having the highest priority on self, My code is shown below, even though its working it doesn't feel right, I think there is better way to design in, and my question is, how would you design it? Models: class BaseBoardClass(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=248, blank=True, null=True) class Meta: abstract = True """Permissions Groups, if null all users have permission""" can_view_group = models.ManyToManyField(Group, blank=True, null=True, help_text="What groups will ba bale to view given this Board/Group " " Aviable after creation", related_name="%(class)s_can_view_group") can_add_new_posts = models.ManyToManyField(Group, blank=True, null=True, help_text="What groups will ba able to add new topics to this Board/Group," " Aviable after creation", related_name="%(class)s_can_add_new_posts") def __str__(self): return self.name class BoardGroup(BaseBoardClass): def get_absolute_url(self): return reverse("boards_app:board_group", kwargs={"board_id": self.id}) class Board(BaseBoardClass): """Board group the boards belongs to""" parent = models.ForeignKey(BoardGroup, on_delete=models.SET_NULL, null=True, related_name="boards") def get_absolute_url(self): return reverse("boards_app:board", kwargs={"board_id": self.id}) class SubBoard(BaseBoardClass): #todo better way to behave on_delete parent = … -
Is it a good practice to store SQL query in the database?
My Usecase: We allow the users of the system to create a list(i.e segment) of contact details based on the variety of the filters from the UI. So they create the segment using a form to select say all people living in a particular state. So the issue here is that, when the new contacts are added, I want these segments to be updated as well. The solution that I can think of is saving SQL query for each segment and update each segment when new contacts are added using these SQL queries. I thought of saving only parameters in a json string format but complication in that case is filters available are over multiple tables and there is no way to generate the dynamic SQL query as it invovles joins and different filters (i.e. 'in', 'endswith', etc). I don't think either of them is the best solution. Any better ideas? Any help would be appreciated, thanks in advance! -
Environment Variable not being read Heroku windows
This is my settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 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 = 't9iu8f#m48b)#vrjcm1(ek7#hlv9qc1&pu+h)ofz^^d_r10t(d' SECRET_KEY= os.environ['secretKey'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['ashesidocconnect.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'Connect.apps.ConnectConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', ] 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', ] ROOT_URLCONF = 'DocConnect.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DocConnect.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'Connect-docInfo' … -
Django-bootstrap-datepicker-plus is not rendering datepicker properly
I am facing with the problem that my datetimepicker is not loading at all. Just in my template, the datetime field loads the current date and time when i press the calendar icon as the image shows. Despite following the installation steps from here : https://pypi.org/project/django-bootstrap-datepicker-plus/ and checking other answers in stackoverflow i did not manage to find the solution. I think the problem has to do with the imports and their priority. my template {% extends 'base.html' %} {% load render_table from django_tables2 %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% block page-title %}Creation of Process Note{% endblock %} {% block content %} <div class="row"> <div class="col-md-6 col-xl-6 offset-md-3"> <form class="well" method="post" action=""> {% csrf_token %} {% bootstrap_form form %} <br> {% buttons %} <button type="submit" class="btn btn-primary"> Submit </button> {% endbuttons %} </form> {{ form.media }} </div> </div> {% endblock %} In my base.html the appearence of the imports is: Inside head <link href="/static/theme/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css"> <script src="/static/theme/assets/js/jquery.min.js"></script> ... Inside footer <script src="/static/theme/assets/js/bootstrap.bundle.min.js"></script> ... my model class Case_Notes(models.Model): date_created = models.DateTimeField("Creation Date", null=True,blank=True, default=datetime.datetime.now) date = models.DateTimeField("Appointment Date", null=True,blank=True) notes = models.CharField("Notes",max_length=500, blank=True, null=True) def __str__(self): return self.notes my form class ProcessNotesForm(ModelForm): notes= … -
Can not send email from host account to user email while resetting password
I have made a smtp configuration in my django app settings, which will sent a email in users account to reset password.but whenever i enter the form it causes an error like TimeoutError at /password_reset/ [WinError 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. -
How can I query in sql to get a queryset reformated
I have a user table whose PK is user_id and a item table whos PK is item_id. Then I have another record table that records when a user pick an item(many to many). That is to say its attributes include user_id, item_id and pick_time. And I want to get a table like this: wanted query result in which 1 refers the user has at least once picked the item while blank refers not Please help me with this problem in any case: How can I write my sql code to get this queryset? If can't solve in sql query, how to restruct my database? Sorry for my bad sql skill and poor expression. Thansk a lot! -
Password, Email Verification and Password Reset in Django
I am building a simple webapp with Django. Users can login and post articles and prayer requests. The things left for me to deplot this webapp is to improve my registration view. I mean I want users password to consist at least an Uppercase a number and must be 8 letters long. In addition to this, I want a verification email to be sent to the user for confirmation of their accounts. Finally, I need a custom reset password views. I have created all the necessary templates needed for this. I have come across a number of blogs, they have been rather confusing. Can anyone help with this please? A step-by-step guide please.