Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app deployment in AWS Beanstalk - Error after deployment - Internal Server Error
I have a django app deployed to AWS beanstalk. The first version was fine after following the official documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html Then, I added a new feature using django-filter to my site. Now, when I deploy, I get this error on the main front end page: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Below is the error log I have. [Thu Oct 01 04:47:09.118704 2020] [:error] [pid 21279] [remote 172.31.47.200:20528] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate [Thu Oct 01 04:47:09.118707 2020] [:error] [pid 21279] [remote 172.31.47.200:20528] raise RuntimeError("populate() isn't reentrant") [Thu Oct 01 04:47:09.118722 2020] [:error] [pid 21279] [remote 172.31.47.200:20528] RuntimeError: populate() isn't reentrant [Thu Oct 01 04:47:13.477606 2020] [:error] [pid 21279] [remote 172.31.3.100:48] mod_wsgi (pid=21279): Target WSGI script '/opt/python/current/app/djangoproject/wsgi.py' cannot be loaded as Python module. [Thu Oct 01 04:47:13.477658 2020] [:error] [pid 21279] [remote 172.31.3.100:48] mod_wsgi (pid=21279): Exception occurred processing WSGI script '/opt/python/current/app/djangoproject/wsgi.py'. [Thu Oct 01 04:47:13.477768 2020] [:error] [pid 21279] … -
Django rest framework creating Orders and order items
I want to create a Order and order items. For this i am simply creating new model object in views.py using CreateApiView but i am receiving error that "Serializer_class" should be included but i don't need serializer for this. //views.py class CreateOrder(CreateAPIView): def Post(self,request): header_token = request.META.get('HTTP_AUTHORIZATION', None) print(header_token) access_token = header_token.split(' ')[1] status,user = validate_token(access_token) cart=Cart.objects.get(user=user) print(cart) if cart: total=cart.total userprofile=UserProfile.objects.get(user=user) order,created=Order.objects.get_or_create(billing_profile=userprofile,total=total) cart_items=CartItem.objects.get(cart=cart) print(cart_items) for item in cart_items: itemid=item.item_id qty=item.quantity item_instance = Items.objects.get(item_id=item) order_item,created = OrderItems.objects.get_or_create(order=order, product=item_instance,quantity=qty) order.save() order_item.save() if created: item.delete() return Response (status=rt_status.HTTP_200_OK) I want to understand how to achieve this with or without serializer -
Django "This field is required." while trying to update CustomUser
In my models.py, I have this: class CustomUser(AbstractUser): USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) username = None email = models.EmailField(unique=True) .... class Student(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) address = models.TextField() profile_pic = models.ImageField(upload_to='media') session_start_year = models.DateField(null=True) session_end_year = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) In my forms.py, I have this: class CustomUserForm(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) widget = { 'password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = CustomUser fields = ['first_name', 'last_name', 'email', 'password', ] class StudentForm(CustomUserForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta(CustomUserForm.Meta): model = Student fields = CustomUserForm.Meta.fields + \ ['course', 'gender', 'address', 'profile_pic', 'session_start_year', 'session_end_year'] widgets = { 'session_start_year': DateInput(attrs={'type': 'date'}), 'session_end_year': DateInput(attrs={'type': 'date'}), } From which I was able to add new student by passing context = {'form': StudentForm()} to my template. But now, I am having issue in trying to update students. I was able to get the student object which I pass as instance to StudentForm() but only ['course', 'gender', 'address', 'profile_pic','session_start_year', 'session_end_year'] fields value were set. … -
Rendering CSS with HTML with Django
So I have the file main.html which is being returned unstyled even though I have style.css in /polls/static/polls/style.css Here is main.html (cut down for simplicity) {% load static %}<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'polls/style.css' %}"> </head> my settings.py has this for the static URL: STATIC_URL = '/static/' Yet it still returns it unstyled while the console gets returned 404 1671 The fix is probably easy I'm just a newbie at Django Thanks -
CSRF token missing or incorrect on POSTMAN
This is my views.py from django.shortcuts import render from django.views.generic import ListView from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' from django.views.generic import ListView, CreateView from django.urls import reverse_lazy from .forms import PostForm from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' class CreatePostView(CreateView): # new model = Post form_class = PostForm template_name = 'post.html' success_url = reverse_lazy('home') How do I pass a request to the templates render method. I am getting a csrf token error on Postman while using POST method -
How can I subclass Django TextChoices to add additional attributes?
I want to use Django 3.0 TextChoices for a models.CharField choices option and also as an Enum in other places in my code. This is a simplified version of my code from django.db import models class ValueTypeOriginal(models.TextChoices): # I know Django will add the label for me, I am just being explicit BOOLEAN = 'boolean', 'Boolean' class Template(models.Model): value_type = models.CharField(choices=ValueType.choices) I am wanting to add an additional attribute to the enum members, something so that this call >>> ValueType.BOOLEAN.native_type bool works. bool here isn't a string, but the built-in python function This blog post described doing something like that with Enum by overriding __new__. class Direction(Enum): left = 37, (-1, 0) up = 38, (0, -1) right = 39, (1, 0) down = 40, (0, 1) def __new__(cls, keycode, vector): obj = object.__new__(cls) obj._value_ = keycode obj.vector = vector return obj Based on that I tried: class ValueTypeModified(models.TextChoices): BOOLEAN = ('boolean', bool), 'Boolean' def __new__(cls, value): obj = str.__new__(cls, value) obj._value_, obj.native = value return obj That almost works. I get access to the unique TextChoices attributes like .choices, but string comparison doesn't work like it should. >>> ValueTypeOriginal.BOOLEAN == 'boolean' True >>> ValueTypeModified.BOOLEAN == 'boolean' False I think … -
Django ignoring localisation settings when displaying a DateTime on a form
I have the Django settings in "settings.py": LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True With a model in "models.py": class Foo(models.Model): date_time = models.DateTimeField(null=True, blank=True) And a form in "forms.py": class FooForm(forms.ModelForm): class Meta: model = Foo fields = ['date_time'] And in the template: <form method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Submit</button> <button type="button" onclick="javascript:window.location='/dashboard';">Cancel </button> </form> But the date is shown on the screen in the form as "2020-12-20 10:11:12" for example. Why doesn't Django use my localisation settings and display the date as "day, month, year"? I tried adding to the form: date_time = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M']) ...but it didn't have any effect. To quote the manual: "The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead." -
Submitting form after payment made via Paypal
helloo, I have recently integrated a PayPal payment option to my e-commerce project and everything is working fine except that after a payment is made the items remain in the cart and the payment is not notified to the backend. My question is how to set a submit the form for the address and all the details made in the check out the template along with the paid amount to reflect in the backend. Here is the checkout views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } ---------------------shipping and billing address ------------------- def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid(): ---------------------shipping and billing address ------------------- if is_valid_form([billing_address1, billing_province, billing_country, billing_postal_code, billing_phone_number]): billing_address = Address( user=self.request.user, street_address=billing_address1, apartment_address=billing_address2, province=billing_province, country=billing_country, postal_code=billing_postal_code, phone_number=billing_phone_number, address_type='B' ) billing_address.save() order.billing_address = billing_address order.save() set_default_billing = form.cleaned_data.get( 'set_default_billing') if set_default_billing: billing_address.default = True billing_address.save() else: messages.info( self.request, "Please fill in the required billing address fields") return redirect('core:checkout') payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option … -
using ajax with django login form
and i'm using ajax in my django login form in a bootstrap modal but i want to display if there are errors without the page being refreshed or the modal being closed , after checking some questions here is my try NB: i'm new to django and especially ajax in my views.py if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') in my forms.py class SigninForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'signin_email'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control','id':'signin_password'}), } def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] in the template <form action="" method="POST" id="form_signin"> {% csrf_token %} {{signin_form.email}} {{signin_form.password}} <button type="submit" name="signin_form">Sign in</button> <hr> {% for message in messages %} {{ message }} {% endfor %} </form> -
Logout in Django auth + service worker
I have an issue with my service worker. When I try to logout my user in offline mode I face 2 issues: If I don't try to cache /logout and just redirect to the login page, the sessionid cookie is not delete and so when I leave the offline mode the user is still connected If I try to cache /logout/ I have an error because /logout/ is not a page but only a view in django Can someone help me to find a solution so I can disconnect safely my user ? :) Big thx :D -
DRY way to rename ModelSerializer fields without duplicating model/field definitions?
Working with a legacy database with an awful schema and want to rename several ModelSerializer fields without having to redefine fields already defined on the model. Here's an example model: class LegacyItem(models.Model): # Note: ignore things that feel "wrong" here (just an example) legacyitem_id = models.IntegerField(primary_key=True) legacyitem_notes = models.CharField(max_length=4000, blank=True, null=True) directory_id = models.ForeignKey('Directory', models.DO_NOTHING) created_by_directory_id = models.ForeignKey('Directory', models.DO_NOTHING) created_date = models.DateField(auto_now_add=True) modified_by_directory_id = models.ForeignKey('Directory', models.DO_NOTHING) modified_date = models.DateField(auto_now=True) Here's a working serializer: class LegacyItemSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = LegacyItem read_only_fields = [ 'created_date', 'modified_date', ] The goal is to bulk rename model fields for the API so we can abstract away the awful schema. Here's a working serializer showing the sort of renaming we want to do: class LegacyItemSerializer(serializers.ModelSerializer): created_by = serializers.PrimaryKeyRelatedField( read_only=True, source='created_by_directory_id', ) customer = serializers.PrimaryKeyRelatedField( queryset=Directory.objects.all(), source='directory_id', ) id = serializers.PrimaryKeyRelatedField( read_only=True, source='legacyitem_id' ) modified_by = serializers.PrimaryKeyRelatedField( read_only=True, source='modified_by_directory_id', ) notes = serializers.DateField(source='legacyitem_notes') class Meta: fields = [ 'id', 'customer', 'notes', 'created_by', 'created_date', 'modified_by', 'modified_date', ] model = LegacyItem read_only_fields = [ 'created_date', 'modified_date', ] All we want to do is rename the fields. We don't want to change the validation and would rather keep most of that validation on the model and … -
Django: Automatically update database field to True with background task when condition is met
I have a Model Job which has a field filled. I want to automatically update filled to True if the current_date and time is equal to the Job's end_date and time. The end_date is set when creating the job. I am using a background task to check all Jobs in the DB and repeat the process always, but I can't get it to work. Here is my code Model.py class Job(models.Model): # title, description, requirements, job type etc. end_date = models.DateTimeField(null=True, blank=True) current_date = models.DateTimeField(null=True, blank=True) filled = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title task.py from django.utils import timezone queryset = Job.objects.all() @background(schedule=60) def auto_mark_as_filled(jobs): for job in [jobs]: job.date = timezone.now() if job.end_date == job.current_date: job.filled = True job.save() return jobs # repeat always/every seconds auto_mark_as_filled(queryset, repeat=1) I get TypeError: Object of type QuerySet is not JSON serializable I don't want to use celery as a background task is easier to implement. Any help will be appreciated thanks -
WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module
I use django 3.1.1 and Python 3.8.5. I want to create simple blog. I use some old code in which programmer used django 1.11 probably, so I change many things, but now I'm stuck I get error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module. When I try to remove WSGI_APPLICATION = 'mysite.wsgi.application' I get an error ImportError: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class This is my whole setting.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os 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/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*s@w*wx_w23k5vp%c%*aatqr42dsu3m$^(et@a(yrx$(4j-u*o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] SITE_ID = 1 # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'blog', 'taggit', 'haystack', ) MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF … -
¿Cómo instalar kerberos en windows?
Estoy investigando sobre el protocolo de autenticación Kerberos, hasta ahora he creado un proyecto en Django y ahí instale el modulo django-auth-kerberos, e hice las configuración del backend. Lo que no se es cómo instalar Kerberos en Windows, para crear los reinos dominios y demás configuraciones para kerberizar. ¿Kerberos se instala es solo en un servidor?, agradecería saber si existe una configuración para instalarlo en un maquina por ejemplo de windows 10 donde pueda crear reinos y todo lo de kerberos. -
Django do something when model instance created
I'm looking to update a user's coin count in their profile whenever I create a promo code redemption object from a model. Is there a method that runs when the object is created so I can update a field in the users profile from the promo code redemption model? I tried init() but the arguments were no longer being filled in and saved in the model and I'm just looking to run extra code rather than adding custom fields. I saw the signals file mentioned but wouldn't it be simpler to have it be done automatically through the model as a method? class Promo_Code_Redemption(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=9,decimal_places=2) date = models.DateTimeField(default=timezone.now) code = models.ForeignKey(Promo_Code, on_delete=models.CASCADE) code_text = models.TextField() revenue_type = "Promo code" def __str__(self): return self.code.code class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) withdrawal_email = models.EmailField(max_length=254) currency_total = models.DecimalField(max_digits=9,decimal_places=2,default=0.00) currency_earned_all_time = models.DecimalField(max_digits=11,decimal_places=2,default=0.00) def __str__(self): return self.user.username views.py @login_required def codes(request): if request.method == 'POST': form = Promo_code_redeem_form(request.user, request.POST) if form.is_valid(): promo_code = form.cleaned_data.get('code_text') #create promo code redemption instance Promo_Code_Redemption.objects.create(user=request.user, amount=Promo_Code.objects.get(code=promo_code.lower()).internal_currency_value, code=Promo_Code.objects.get(code=promo_code.lower()), code_text=promo_code) messages.success(request, f'Promo code redeemed succesfully!') return redirect('codes') else: form = Promo_code_redeem_form(request.user) codes = Promo_Code_Redemption.objects.filter(user=request.user).order_by('-date') total_codes_redeemed = Promo_Code_Redemption.objects.filter(user=request.user).count() total_codes_value = Promo_Code_Redemption.objects.filter(user=request.user).aggregate(Sum('amount')) total_codes_value = total_codes_value['amount__sum'] context = { … -
Post matching query Django
I get the Post matching query does not exists error when I run this code on my Django App. I tried to create the like section on every post on my blog app. I don't understand this error. I belive it has to be from the like function, but I have no clue why. dsd sadsa dsadsadsadsadsad dsasdsadasdasdsa views.py def like_post(request): user = request.user if request.method =='POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id = post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Likes.objects.get_or_create(user = user, post_id = post_id) if not created: if like.value =='Like': like.value='Unlike' else: like.value = 'Like' like.save() return redirect('blog-home') html file <form action="{% url 'like-post' %}" method="post"> {% csrf_token %} <input type="submit" name="post_id" value="{{post.id}}" class="btn btn-primary btn-sm"> {% if user not in post.liked.all %} <button class="ui button positive">Like</button> {% else %} <button class="ui button negative">Unlike</button> {% endif %} </form> models.py class Post(models.Model): content = models.TextField(blank=True, null=True) date_posted = models.DateTimeField(default = timezone.now ) #one user can have multiple posts, but one post can only have one author author = models.ForeignKey(User, on_delete = models.CASCADE) image = models.ImageField(blank = True, null=True, upload_to='post-images') video = models.FileField(blank=True, null=True, upload_to='post-images', validators=[validate_file_size,FileExtensionValidator(['ogg', 'm4v', 'wmw', 'wma','mov','avi','quicktime','flv','mp4','f4v','m4b', 'm4a', '3gp', 'aac', 'mp4', 'mp3', 'flac'])]) … -
Custom Django messages and adding extra context to Django change_view
I am using SESSION_COOKIE_AGE and added custom JS to refresh the page after the session expires to log a user out after a certain time of inactivity. I now was to add a message to the logout page to let the user know why they were logged out. According to Django Docs I have to add my custom message as context to the view and then call it on the template. The logout function is used for mainly for the change_form.html template, but of course SESSION_COOKIE_AGE works everywhere. Where is the view for change_form so I can add this context? I see from the docs it is called change_view, but not what file/folder it is in can I cannot find it for the life of me. Would there be an easier way to show this message no matter where the user was logged out from? -
create_user() missing 1 required positional argument: 'username'
I deleted username field because I wanted user to be able to login with their email address, so I have this in my models.py : class CustomUser(AbstractUser): USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) username = None email = models.EmailField(unique=True) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Student(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) address = models.TextField() profile_pic = models.ImageField(upload_to='media') session_start_year = models.DateField(null=True) session_end_year = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) In my views.py, I tried : user = CustomUser.objects.create_user(email=email, password=password, user_type=3, first_name=first_name, last_name=last_name) But I got create_user() missing 1 required positional argument: 'username' How can I fix this? -
How to create a responsive (the user being able to modify) graph to obtain inputs from it?
So I'm remodeling this website where at some point of a form the user has to enter its consumption profile in percentages (e.g. "I 50% of the energy on mondays 20% on Fridays, 30% on sundays"). My idea is to place some kind of graph (like the one I attached, imagine % in y axis and weekdays in x-axis) where the user could move up and down the bars to visually enter its consumption and finally, on form submit, grab the inputs from it using django, JS or Jquery. I don't know where to start or even if it is possible. I kindly ask you for help. :) -
Overriding ModelForm save method seems doing nothing
I was trying to change remove a manytomany field's certain value if it's fitting to certain condition. I have read from the documentation, I could achieve this by overriding save() method in ModelForm. Model and ModelForm classes: class Member(models.Model): class Meta: unique_together = [['project', 'person']] project = models.ForeignKey(Project, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) key_role = models.ForeignKey(Role, verbose_name=_('Key Role'), null=True, on_delete=models.SET_NULL) roles = models.ManyToManyField(Role, verbose_name=_('Additional Roles'), related_name='additional_role') desc = models.TextField(_('Job Description'), max_length=600) class MemberForm(ModelForm): class Meta: model = Member fields = ['key_role', 'roles'] def save(self, commit=True): member = super(MemberForm, self).save(commit=False) if member.key_role in member.roles: member.roles.remove(member.key_role) member.desc = "SHOULD BE CHANGED BUT NO, IT'S NOT" if commit: member.save() self.save_m2m() return member If it had run, at least desc field's value should be changed, but it is not. Is there anything I missed? Thank you -
Django Heroku app moved to new computer - error on git push heroku master
I recently moved my Django project deployed on Heroku to a new computer. By cloning my repository on my new computer. I have now made changes to the project on the new computer and have committed to my GitHub repository. Now I have added my project GitHub repository, as well as the Heroku remote repository to the remote and I, can see it when I run git remote -v: heroku https://git.heroku.com/myapp.git (fetch) heroku https://git.heroku.com/myapp.git (push) origin https://github.com/username/repo.git (fetch) origin https://github.com/username/repo.git (push) Now when I want to commit new changes I do: git add . and then git commit -m "commit message" - which commits to my GitHub repository? I do not know if this is correct Now when I want to push to heroku master using the command git push heroku master I get the following error: ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://git.heroku.com/myapp.git' I have also added keys, using heroku keys:add which since I didn't have any keys on my new computer I created a new one, which now I can see it when I run heroku keys. I want to just push the new changes I made on my repository … -
Adding django import_export to Abstract User Model
I am new to Django. This is my admin.py file. I want to implement the import_export feature on the Employee model which is Abstract User Model. from django.contrib import admin from inventory.models import Employee from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Group from import_export.admin import ImportExportModelAdmin admin.site.unregister(Group) # admin.site.register(Employee) class EmployeeAdmin(UserAdmin): list_display = ('emp_num', 'emp_name', 'email', 'emp_designation', 'is_admin', 'is_staff') search_fields = ('emp_num', 'emp_name') readonly_fields = ('last_login',) ordering = ('emp_num',) filter_horizontal = () list_filter = ('is_admin',) fieldsets = () admin.site.register(Employee, EmployeeAdmin) Please Help !! Thanks in Advance ! -
django filefield returning localhost-prefixed URL
I'm trying not to specify the full path of the web app in the settings to make it as portable as possible. However, with MEDIA_URL="/media/", an URL returned from a Django FileField model is http://localhost/media/.... with MEDIA_URL="//example.com/media/", the URL returned is http://example.com/media/.... But the schema (http/s) and domain (example.com) should match those of the requesting page. How can I do this? The Django app is served through Nginx in combination with Gunicorn. -
Showing fields of django form already filled after submission, is not working
I am new to Django and the following is my snippet of code in which after receiving feedback from the user I redirected my user back to the feedback form page but it is not showing filled fields. Is there any problem in my code? @login_required def Feedback(request): if request.method == 'POST': Feedback_Form = FeedbackForm(request.POST) Feedback_Form.instance.user = request.user if Feedback_Form.is_valid(): Feedback_Form.save() username = request.user messages.success(request, f'Thanks for your Feedback. Thanks for using our site, {username}.') return redirect('Feed-back') else: Feedback_Form = FeedbackForm() return render(request,'users/feedback.html',{'feedback_form': Feedback_Form}) -
How to handle a legacy database in the Django framework
I'm working on an django app that needs to access a very large (mysql) database, the db has no foreign keys whatsoever. I need to do querys on multiple tables.The way i'm doing it is VERY ineficient and involves doing multiple loops: ''' {% for flower in especies_id %} <td>{{flower.especies}}</td> {% for family in family_id %} {% if family.family_id == flower.family_id %} <td><a class="nav-item active" href="/home"> {{family.family_name}}</td></a> {% endif %} {% endfor %} {% endfor %} ''' Is there a way to handle this db with the django shell maybe?Javascript? Or refactor the db entirely