Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use widgets in Django Crisp Forms
I am using Django Crispy forms and using the FormHelper. Now i want that one of the fields should use widgets. Actually, i want to populate date picker in the field using the widgets. forms.py class DeviceFilterFormHelper(FormHelper): # form_class = "form form-inline" form_id = "Device-search-form" form_method = "GET" form_tag = True html5_required = True layout = Layout( Div( Div('name', css_class="col-md-6"), Div('location', css_class="col-md-6"), css_class='row' ), Div( Div('phone_number', css_class="col-md-6"), Div('updated_date', css_class="col-md-6"), css_class='row' ), FormActions( Submit("submit", ("Search"), css_class="col-md-5"), css_class="col-8 text-right align-self-center", ), ) Below is the widget along with its attributes which i want to use in the formHelper. updated_date = forms.DateInput(attrs={ 'required': True, 'class': 'date-time-picker', 'data-options': '{"format":"Y-m-d H:i", "timepicker":"true"}' }), I just can't figure out how will i be using the widget. -
Python Django - Associating a OneToOneField on users. IntegrityError NOT NULL constraint failed
I'm making a website (obviously) with Django and I have a problem with when I create users. I want to associate my users with a model, called a Class, and the Class contains multiple users. And I assume I need to use models.OneToOneField() to associate one class with multiple users. But when I, for example, create a superuser in the terminal, I instantly get an IntegrityError when I have typed the last bit of required information and pressed enter. I know you could just set null=True in the OneToOneField but then the user isn't associated with a class. Basically, I just want a model called a Class to have multiple users associated with it, and every Class have different Keys/authentication (as shown in models.py) to do different things on my website. Full traceback (after trying to create superuser): Traceback (most recent call last): File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: users_user.parent_class_id The above exception was the direct cause of the following exception: 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\lll20\Documents\PYJA\pyja\p_env\lib\site-packages\django\core\management\__init__.py", … -
How to differentiate account types in Django?
Thanks in advance if you're reading this... I'm a High School student working on a web application using Django, to help students find internships, and facilitate parents posting internship offers -- a sort of marketplace if you will. I'm trying to create a profile/account page for the users but I need a way to differentiate between whether the account logged in is a Student or Employer so that I can use views.py to generate a page appropriate to their account. In models.py, I have two different profile types which can be associated with a user account (handled by django.contrib.auth), see below for reference. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name = 'Student Profile' def __str__(self): return f"{self.user.username}'s Profile" class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=100, default='Unspecified') class Meta: verbose_name = 'Employer/Parent Profile' def __str__(self): return f"{self.user.username}'s Profile" In my views.py page, I'm trying to create a view for the account/profile that can detect whether the currently logged-in user's profile is linked to either the 'Student' or 'Parent' model and serve a page accordingly. I've tried a very rudimentary approach, as below, but unsurprisingly it's not working. def account(request): … -
View to Download FileField From Django
I have files which are saved to the MEDIA_ROOT - and I am displaying the file paths as URLs in a table in my UI. I would like for these files to download when the user clicks the link in the table. However, when that happens I get an error because I don't have a URL or View defined to handle this I suppose. Problem is, I'm not really sure where to start - any suggestions. Below is my model, and the .html which displays the table and the link. models.py class Orders(models.Model): ... models.FileField(upload_to='web_unit', null=True, blank=True) ... def __str__(self): return self.reference index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> .... </thead> <tbody> {% for orders in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' orders.pk %}"> <span class="fa fa-pencil"></span> </button> </td> .... <td><a href="{{ orders.order_file }}">Download</a></td> #this is the link </tr> {% endfor %} </tbody> </table> When the link in the table is clicked - I'd like for the file to be downloaded - I need help on how to define the URL and the View to make this … -
Django: How to limit TimeField to hours and minutes only (comparison issue)
I'm developping a web api using django, I have a TimeField that stores hours:minutes:seconds, since it will be compared to a hours:minutes (without seconds) coming from the mobile app, the comparison will always fail. here is a comparison without seconds which is returnning an empty QuerySet: >>> journey = Journey \ ... .objects \ ... .filter((Q(route__departStation=1) | Q(route__stop__station_id=1)), ... (Q(route__arrivalStation=1) | Q(route__stop__station_id=1)), ... route__departDate="2019-07-31", route__departTime="10:57") >>> journey <QuerySet []> and here is when I add seconds to the comparison: >>> journey = Journey \ ... .objects \ ... .filter((Q(route__departStation=1) | Q(route__stop__station_id=1)), ... (Q(route__arrivalStation=1) | Q(route__stop__station_id=1)), route__departDate="2019-07-31", route__departTime="10:57:05") >>> journey <QuerySet [<Journey: Journey object (1)>]> so please, how can I prevent the seconds from being saved to the database from this TimeField(), or at least how can I limit the comparison to hours and minutes only. -
Unable to load staticfiles after deploying django app on aws-ec2
I am a beginner in aws and I am trying to deploy a django app on aws-ec2. I have set-up gunicorn application server and nginx web server and app loads but without static files. I have followed many answers on stackoverflow but I am unable to fix my problem. I tried with both root and alias but they didn't work. The project structure is as follows:- /home/ubuntu/myskillhut/ django.conf(nginx configuration file) server { ... location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myskillhut/app.sock; } location /static/ { autoindex on; alias /home/ubuntu/myskillhut/static/; } } settings.py ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"), ) ... -
models.CASCADE not working correctly in DeleteView
models.CASCADE does not seem to function correctly when I try to delete a parent object in the delete view. I have two models. ExceptionReport and ExceptionReportHistroy. Users can create a report and if conditions are met, a history object is created. Users can delete a report and on deletion, all associated history objects should be deleted but when a user tries to delete, I get this error: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`lp`.`reports_exceptionreporthistory`, CONSTRAINT `reports_exceptionrep_report_id_99f21d10_fk_lp_except` FOREIGN KEY (`report_id`) REFERENCES `lp_exception_reports` (`id`))') I have no idea why since the on_delete=models.CASCADE Models: class ExceptionReports(models.Model): from_field = models.CharField(max_length=100, blank=True) emails = EmailListField(max_length=800) description = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) ... class ExceptionReportHistory(models.Model): created_date = models.DateTimeField(default=now) report = models.ForeignKey(ExceptionReports, on_delete=models.CASCADE) message = models.TextField(blank=True) ... View: class ExceptionReportDeleteView(LoginRequiredMixin, DeleteView): model = ExceptionReports template_name = "reports/delete.html" success_url = reverse_lazy('reports:exceptionreport_list') success_message = "Exception Report deleted successfully." URL: path('exceptionreports/', include([ path('', login_required(views.ExceptionReportListView.as_view()), name='exceptionreport_list'), path('add/', login_required(views.ExceptionReportCreateView.as_view()), name='exceptionreport_create'), path('<int:pk>/', include([ path('update/', login_required(views.ExceptionReportUpdateView.as_view()), name='exceptionreport-update'), path('delete/', login_required(views.ExceptionReportDeleteView.as_view()), name='exceptionreport-delete'), ])), ])), In the delete view, users should be prompted associated history objects that would also be deleted but that doesn't happen instead I get an IntegrityError -
Error when adding many-to-many-field on Post
I have an app within my project called posts, where inside their in the models.py, I have two models: Post and Like. I want to add a many-to-many-field on the post that references the Like model. I have executed makemigrations and migrate, however I am getting this error: NameError: name 'Like' is not defined models.py: class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(Like) def __str__(self): return self.user.username def summary_pretty(self): return self.summary[:50] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) -
Creage aggregate query with filtering in django
I have the following table/model. I am trying to figure out how to convert the SQL query into Django 1.11 syntax. In particular, I am having difficulty adding additional filter parameter into Django's When. http://sqlfiddle.com/#!9/8c6974/26 Here is the SQL create/populate: create table Activity ( Id INT AUTO_INCREMENT, username varchar(50), course_id varchar(50), activity_type varchar(50), activity_action varchar(50), times INT, date_event DATETIME, PRIMARY KEY(id) ); INSERT INTO Activity (username, course_id, activity_type, activity_action, times, date_event) VALUES ( 'john', '123', 'video', 'viewed', 2, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'attempted', 11, str_to_date('02-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'attempted', 22, str_to_date('03-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'attempted', 33, str_to_date('02-07-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'solved', 4, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'solved', 5, str_to_date('01-01-2019', '%d-%m-%Y')), ( 'john', '123', 'problem', 'solved', 6, str_to_date('01-02-2019', '%d-%m-%Y')), ( 'adam', '123', 'video', 'viewed', 2, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'attempted', 11, str_to_date('02-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'attempted', 22, str_to_date('03-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'attempted', 33, str_to_date('02-07-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'solved', 4, str_to_date('01-08-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'solved', 5, str_to_date('01-01-2019', '%d-%m-%Y')), ( 'adam', '123', 'problem', 'solved', 6, str_to_date('01-02-2019', '%d-%m-%Y')), ( 'meg', '123', 'discussion', 'asked', 6, str_to_date('03-02-2019', '%d-%m-%Y')), ( 'meg', '123', 'discussion', 'asked', 6, str_to_date('03-02-2019', '%d-%m-%Y')) … -
i have go an error in django 2.2 templatetags {% load post_tag%}
TemplateSyntaxError at / 'post_tag' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log static staticfiles tz i have this error in django 2.2 -
python - logging: How to access handler from config file
I am trying to use logging in Django Application. I want to predifine my formatters and handlers in config file and later use different handlers at different times as per the need. Currently i am using the following logger config in my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'format1': { 'format': '[%(duration).3f] %(statement)s', }, 'format2': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console1': { 'level': 'DEBUG', 'formatter': 'format1', 'class': 'logging.StreamHandler', }, 'console2': { 'class': 'logging.StreamHandler', 'formatter': 'format2', 'level': 'DEBUG', } } } Is there a way i can use the handlers specified in the settings.py file like: import logging def someview(request) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler("name of the handler from confi file i.e console1 or console2") #I tried # logger.addHandler('console1') it says # Attribute Error - 'str' object has no attribute 'level' # if record.levelno >= hdlr.level: # /usr/lib64/python3.7/logging/__init__.py in callHandlers, line 1590 # So how to use the handler mentioned in the config file -
Django's session-based model - id value in settings.py?
I am learning to build a product cart app for an online shop. But while I was reading other's app, I found something I couldn't understand. settings.py> CART_ID = 'cart_in_session' cart.py> from decimal import Decimal from django.conf import settings from shop.models import Product from coupon.models import Coupon class Kart(object): def __init__(self, request): self.session = request.session kart = self.session.get(settings.CART_ID) if not kart: kart = self.session[settings.CART_ID] = {} self.kart = kart I couldn't get this part of code snippet: if not kart: kart = self.session[settings.CART_ID] = {} It has two "=" symbol and I am wondering if it's for assignment and if it's really an assignment, then why it sets CART_ID's value ("cart_in_session" for its matched key CART_ID) to {} -
Error while saving date in MySQL using Django
I need to save date and time in database (MySQL). I am using Django. The jQuery datetimePicker gets populated but when i click the save button of form, it gives me an error that (1048, "Column 'updated_date' cannot be null") However, if you see below the updated dated do get posted I just can't find any reason why it is not saving the data. Forms.py updated_date = forms.DateTimeField(input_formats=["%Y-%m-%d"], widget=forms.TextInput(attrs= { 'required': True, 'class':'date-time-picker', 'data-options':'{"theme":"dark","format":"Y-m-d", "timepicker":"false"}' })) Model.py class Devices(models.Model): name = models.CharField (max_length=50, null=False, blank=False, unique= True) phone_number = models.CharField (max_length=20, blank=True, unique=True, verbose_name='PHONE NUMBER') location = models.ForeignKey(Location, on_delete=models.DO_NOTHING, null=False, blank=False) status = models.IntegerField(blank=False, default='1') ip_address = models.CharField(max_length=15, null=False, blank=False, unique=True, verbose_name='IP Address') power_status = models.IntegerField(blank=True, default='0') created_date = models.DateTimeField(default=timezone.now(), blank=False) created_by = models.IntegerField(blank=False) updated_date = models.DateField(blank=False) update_by = models.IntegerField(blank=True) def __str__(self): return self.name The data type in MySQL database is datetime. I have even changed it varchar as well but still it is not working. -
Django Heroku deployment URLconf error. Page not found (404)
I am a newbie to Django and trying to deploy my Django app on Heroku. I followed a tutorial and did everything, but when I was finally ready to deploy my app, I get the error "Page not found." I have tried removing the include() around my admin.site.urls because it worked for someone else, but it didn't work for me. this is my urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from profiles.views import delete urlpatterns = [ path(r'^profiles/', include('profiles.urls')), path(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) this is my settings.py file: import os import django_heroku import django os.environ['DJANGO_SETTINGS_MODULE'] = 'firstDjango.settings' from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY="bb33e5a618aa4f6e549b8207ad1d8fa7cd8d1015e13c8780" DEBUG = True ALLOWED_HOSTS = ['ewuradjango.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party #own # 'pages' 'profiles', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'firstDjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], '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', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'firstDjango.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = … -
How can I optimize loops within a Django template?
I have a database setup where I have the following schema: The main model is the Group. Under each group are an arbitrary number of Rules. Each Rule contains an arbitrary number of Regex's and Contacts. I'm displaying this whole set up under the main page so it looks something like this: Group A - Rule A - Regex 1, Contact 1, Contact 2 - Regex 2, Regex 3, Contact 3 - Rule B - Regex 5, Regex 6, Regex 6, Contact 4 - Regex 7, Contact 7, Contact 6 Group B - ... The db query itself is not terribly complex. It's basically: for group in groups: r = Rule.objects.filter(group=group) rules[group]= r But the template rendering is what is slowing things down. It's taking about 7 seconds to render the template because of the number of nested loops: {% for group, rules in rules.items %} {% for rule in rules %} {% for regex in rule.regexes.all %} {{regex.name}} {{regex.type}} {{...}} {% endfor %} {% for contacts in rule.contacts.all %} {{contacts.name}} {{contacts.email}} {{...}} {% endfor %} {% endfor %} {% endfor %} There's obviously more HTML in here but even without it, this rendering takes about 3-4 seconds (full template … -
How to create a dropdown menu in django with selections from created model objects?
I just want to create a dropdown menu with values from formerly created objects (instruments). In this case objects in the Instrument class. I read all the other posts about dropdowns in Django, but most of them address the creation of a new object or something with fixed choices. Though I want to select one from the available objects and then further process it. I don't want to create a new object and I need dynamic choices. forms.py # forms.py from django import forms from .models import Instrument class CreateForm(forms.Form): favorite_fruit = forms.ModelChoiceField(queryset = Instrument.objects.all()) models.py # models.py from django.db import models # Create your models here. class Instrument(models.Model): name = models.CharField(max_length=20, unique=True) description = models.TextField(default='') output_root = models.CharField(max_length=1000, default='') methods_root = models.CharField(max_length=1000, default='') def __str__(self): return self.name html template <!-- create.html --!> {% extends 'base.html' %} {% block content %} <h2>Create new worklist</h2> <form method="POST" class="create-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} -
Registration screen with 3 different user types
Well, I have the following registration screen and I have to basically have 3 types of users: Teacher, Licensing and Other. Here is a link for the image because i don't have 10 points of reputation: https://i.stack.imgur.com/PqXO1.png So far what I have in the models I made using AbstractBaseUser, I have only the normal user information and wanted to inherit from this User that I have these two other fields: The Teacher and licensing it with the specific fields I want. Here's my account model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Usuário deve ter um email") user = self.model( email=self.normalize_email(email) ) user.staff = is_staff user.admin = is_admin user.active = is_active user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, blank=True, null=True, verbose_name='Usuário') first_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Nome') last_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Sobrenome') active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS … -
How to show balance of each user in html page when it is login?
I have a very simple question. I am struggling to show the balance of each user in html page. Whenever a person login, his/her balance should be shown in browser. The result I am getting is just Your Balance is. After that nothing is showing. I want to show each user his/her own balance which I have stored in database. How to do it? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py @login_required def balance(request): total_amount = Balance.objects.all() for field in total_amount: field.amount context = { 'total_amount': total_amount } return render(request, 'users/balance.html', context) Html page <h2>Your Balance is: {{total_amount.amount}}</h2> -
convert csv file to xls & pdf in django
I have a CSV file stored in my server. I created this view which let the user download the CSV file. But I want to convert this CSV to xls and pdf and let users download it instead( either one of it, according to some conditions which I will add later). views.py class Download_csv_View(View): def get(self,request): file_path = #path of .csv file if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 -
How to check form field value before posting form - Django
I have a form that currently works great with the exception that a user can input any value they want into one of the form fields. I would like to first check the field value when the user presses the submit button, before the form is actually submitted. Where is the best place to do this, I am assuming in the views.py? My objective is to check the customerTag value that the user inputs, and ensure the value they enter exists in the CustomerTag model field. for my views.py I currently have: def usersignup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': '127.0.0.1:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') send_mail(email_subject, message, 'example@example.com', [to_email,], fail_silently=False) return render(request, 'confirm.html',) else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form': form}) forms.py I have: class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs):# for ensuring fields are not left empty super(CustomUserCreationForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['customerTag'].required = True class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'first_name', 'last_name', 'email', 'customerTag',) labels = { 'customerTag': ('Customer ID'), } help_texts = … -
How to enforce certain settings (of another app) for a Django Reusable App
I am writing a Django Reusable App. Parts of this app require certain other Django Reusable Apps, and critically require certain settings for those apps. For example, suppose that in order to use my_reusable_app you have to also use rest_framework and set: REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema", } (This is a silly example, but you get the idea.) How can I enforce this? My first thought is to use Django's built-in checks framwork. Any better ideas? -
Why am I getting this error in django: ModuleNotFoundError: No module named 'unicodedata'
I'm following a tutorial on how to populate django models using the Faker library, but when running the python file I get an error, can someone please help me understand why. I'm new to django, thanks Here's my code import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','PlzWorkApp.settings') import django django.setup() ## FAKE POP SCRIPT import random from PlzWorkApp.models import AccessRecord,Wepage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # create the fake data for thet entry fake_url = fakegen.ulr() fake_date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] # create a fake access AccessRecord for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("Populating complete!") Here's the message I get when I run the file: Traceback (most recent call last): File "populate_PlzWorkApp.py", line 5, in django.setup() File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django__init__.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\urls__init__.py", line 1, in from .base import ( File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\http__init__.py", line 2, in … -
Django: Hiding specific ForeignKey Objects
I've got these two models: class User(AbstractBaseUser, PermissionsMixin): club = models.ForeignKey('schedule.club', on_delete=models.CASCADE, null=True, blank=True) archived = models.DateTimeField('Archived at', blank=True, null=True) class Club(models.Model): archived = models.DateTimeField('Archived at', blank=True, null=True) some fields more fields Now when creating a new User for the field club I can always pick from a list of all my club objects. But for my Clubs I've got a archive function which is inside my models.py and does the following: def archive(self, user): self.name = 'Archived Club' self.archived = now() So they are not getting deleted. Only their data get anonymised and they basically still exist in the DB. And exactly those Clubs I don't want to see anymore when creating a new User and setting his/her club. Is there a way to do that without changing the club field in my form? Thanks for anyone who can help! :) -
No module named 'config' while uploading image on gcloud -django
I am trying to upload an image to gcloud server through admin area but it shows error No module named 'config' I am using gcloud proxy to use gcloud database here is the error trail- Traceback (most recent call last): File "F:\duit\duit_backend_env\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "F:\duit\duit_backend_env\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "F:\duit\duit_backend_env\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\duit\duit_backend_env\lib\site- packages\django\contrib\admin\options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "F:\duit\duit_backend_env\lib\site- packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) ... File "F:\duit\duit_backend_env\lib\importlib\__init__.py", line 126, i n import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _ find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _ call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' -
How to create custom filter using graphene-django and Relay that use multiple fields of different types?
Problem Hello, I'm using Graphene Django and Graphene Relay with Python 3.7. I'm trying to make a custom filter for the requests in GraphQL using Django filters. My table looks like this: | id(type: int) | flow(type: varchar) | datetime(type: datetime) | duration(type: int) | |---------------|---------------------|--------------------------|---------------------| | 1 | aaa | 2019-07-06 08:59:00 | 113095465 | | 2 | xxx | 2019-07-06 08:59:00 | 113095465 | | 3 | bbb | 2019-07-06 08:59:00 | 113095465 | I want to be able to execute this kind of SQL request using GraphQL: SELECT * FROM tablename WHERE datetime <= "2019-07-06 08:59:00" AND DATE_ADD(datetime, INTERVAL duration * 1000 SECOND) >= "2019-07-06 09:00:00"; Using a graphql query like : (of course the dates would be in Python DateTime Format) { allTable(startDate: "2019-07-06 08:59:00", endDate: "2019-07-06 09:00:00") { edges { node { id name } } } } Code models.py from django.db import models class TableName(models.Model): name = models.CharField() datetime = models.DateTimeField() duration = models.BigIntegerField() class Meta: managed = False db_table = 'tablename' schema.py from graphene import relay, ObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField import django_filters from .models import TableName from .fieldList import fields_table class TableFilter(django_filters.FilterSet): class Meta: model = TableName fields …