Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Oscar version updated automatically
I am learning about Django Oscar. I was following a tutorial yesterday that is using Django Oscar version 1.6. I followed all the instructions in the tutorial. It was working fine yesterday. Now, when I ran my project today using python manage.py runserver, I got the error about using get_core_apps which has been removed in Django Oscar 2. I ran pip freeze to see the version of Django Oscar installed on my device and it said 2.0.2. Was it updated automatically? I did not make any changes to the project since working on it yesterday. -
Django - Replace None by an empty string on the CharField model - best practices
I've decided to review my Django App and I found some issues in my models. My issue is related to the CharField blank and null options. I was reading about best practices in Django and I've just found out that I was doing everything wrong. Many posts here explain that we should not use blank and null options on CharField at the same time. To follow the rule I deleted the null=True and kept just blank=True Here comes my doubt: I'm populating my DB from a web scrape code. Sometimes the CharField options are returned as None from the website and when my code tried to send it to the DB (I am not doing it in Forms) I get the Invalid Format error telling me that I shouldn't use None - because I took of the null=True. I've read some stuff about it and figure out one solution, which I'm presenting here to hear from you, guys/girls. Is this the best approach? I feel like Django might have something out of the box for this very common situation. class Empresa(models.Model): #I've chosen just some fields to keep it simple userstelegram = models.ManyToManyField(UserTelegram, blank=True) nome = models.CharField(max_length=150, blank=True) denominacao_social = … -
my django web app is working fine on local host but showing at runtime on pythonanywhere it's error log is showing this error
df_path = request.POST.get('path') dataframe = pd.read_csv(df_path) This is the code which is showing this error when hosted on pythnanywhere. Is there anything I am missing while hosting ? I have tried several things but I am stuck at this point... Internal Server Error: / Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/gauravraj/Outlier_Detection (copy)/Outlier_Detection/views.py", line 75, in home dataframe = pd.read_csv(df_path) File "/usr/lib/python3.8/site-packages/pandas/io/parsers.py", line 685, in parser_f return _read(filepath_or_buffer, kwds) File "/usr/lib/python3.8/site-packages/pandas/io/parsers.py", line 439, in _read fp_or_buf, _, compression, should_close = get_filepath_or_buffer( File "/usr/lib/python3.8/site-packages/pandas/io/common.py", line 224, in get_filepath_or_buffer raise ValueError(msg.format(_type=type(filepath_or_buffer))) ValueError: Invalid file path or buffer object type: <class 'NoneType'> -
How to run a series of manage.py django commands with gunicorn + nginx?
I have a django project. To run, I execute python3 manage.py runserver , then I run python3 manage.py listener. I would like to run this with gunicorn + nginx. I am only able to run the first portion python3 manage.py runserver with my gunicorn + nginx setup and not sure how to include the second command python3 manage.py listener. When running with gunicorn only, I run the command gunicorn --bind 0.0.0.0:8000 slack.wsgi:application and that loads the app locally fine for the runserver part but not sure how to include the second command 'listener'. nginx is also setup but same like above, only runs the first part for runserver. This is the tutorial I have been following for my django project https://github.com/subodh-malgonde/slack-django-tutorial Any help is greatly appreciated. I tried using subprocess in the views.py to execute python3 manage.py listener but could not get that to work and just got "django.request ERROR Internal Server Error:". I know this is not the right way to do it but could not finding anything online. Thanks -
I cant get this template due to this views.py loop in django
I am a new developer in Django type programming. I have a problem with sending this value to the database. What I want to do is the value is dynamically sent from the website then the process of the data will be sent to the database with the models.py in (processing folder) from the views.py(app folder) through forms.py in (processing folder). this is my code in models.py (processing folder) class Accountdetail(models.Model): firstname = models.CharField(max_length = 20) lastname = models.CharField(max_length = 20) address = models.CharField(max_length = 100) city = models.CharField(max_length = 50) country = models.CharField(max_length = 50) postalcode = models.CharField(max_length = 20) position = models.CharField(max_length = 50) university = models.CharField(max_length = 50) course = models.CharField(max_length = 50) secondschool = models.CharField(max_length = 50) primaryschool = models.CharField(max_length = 50) aboutme = models.CharField(max_length = 300) this is my form.py(processing folder code) from django.forms import ModelForm from django import forms from .models import Accountdetail class AccountForm(ModelForm): class Meta: model = Accountdetail fields = '__all__' def __init__(self, *args, **kwargs): super(AccountForm, self).__init__(*args, **kwargs) self.fields['firstname'].widget=forms.TextInput( attrs={ "placeholder" : "First Name" } ) self.fields['lastname'].widget=forms.TextInput( attrs={ "placeholder" : "Last Name" } ) self.fields['address'].widget=forms.TextInput( attrs={ "placeholder" : "Address" } ) self.fields['city'].widget=forms.TextInput( attrs={ "placeholder" : "City" } ) self.fields['country'].widget=forms.TextInput( attrs={ "placeholder" : … -
Git push heroku doesn't run properly
So I am pushing files from a git repository to a heroku git repository. However, when I run this, things go normal, then errors start happening. -----> Installing python-3.8.6 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.1.2 Downloading Django-3.1.2-py3-none-any.whl (7.8 MB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting psycopg2-binary==2.7.7 Downloading psycopg2-binary-2.7.7.tar.gz (428 kB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Collecting asgiref~=3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting pytz Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Building wheels for collected packages: psycopg2-binary Building wheel for psycopg2-binary (setup.py): started Building wheel for psycopg2-binary (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-uvz1913i/psycopg2-binary/setup.py'"'"'; __file__='"'"'/tmp/pip-install-uvz1913i/psycopg2-binary/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-0ilqbc20 cwd: /tmp/pip-install-uvz1913i/psycopg2-binary/ Complete output (72 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/psycopg1.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> … -
Heroku Local works fine and it is connected to Postgresql DB hosted by Heroku. Once attempt to deploy, got error code=H14 status=503
I hope I can get some help in what should be my approach to deploy through Heroku. I have a Python app with Django framework and Postgresql db. When I changed the environment from development to production, I used gunicorn to set up a wsgi path and then allowed the host in settings.py. I created a Procfile where manage.py lives, migrated my db to postgres and installed whitenoise middleware to collect static files. When I run Heroku local to verify that my app is running, everything works correctly. Static files are located, can access the database and the localhost is ‘0.0.0.0’. When I push to Heroku, I get the link where the app is released, and verifying deployment is done. Once I click on the link I see the error page displayed. ‘Heroku logs --tail’ gets me an error code=H14 status=503. I know It has to be an issue with Procfile because it is not in my root directory. When I attempt to move Procfile to the root directory, gunicorn stops working because it doesn’t find a wsgi file nor manage.py. How can I fix this conflict and what should be my approach? I don’t understand why everything works perfectly … -
Unable to authenticate user from oracle database (python 3.8.3 and django 3.0)
how do I a login in from the database? I need to use two elements (user and password) of a table from Bd to perform a login. Someone know the format of what i need to put in models.py, views.py or more specific, the things that i need to do a correct login, thanks. -
Django: How to create a Customized Reference code for each Order?
I have an E-commerce project and I am trying facilitate reading order reference codes for me, so currently I am generating random figures as following: My current code generated is: def create_ref_code(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=6)) model.py class Order(models.Model): ref_code = models.CharField(max_length=20, blank=True, null=True) ordered_date = models.DateTimeField() def __str__(self): return self.user.username Reference code is generated every time a payment is executed: def payment_complete(request): ---------payment codes------------- payment.save() # assign the payment to order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() My question is how do I generate a code in the following format that includes that day, month, year, hour, minute and a digit that increases with a new transaction DDMMYYHHMMXXX Day, Month, Year, Hour, Minute,3 digits starting with 001 and increasing with each new order. How can I adjust my function to reach this? -
'ObtainAuthToken' object has no attribute 'request'
Currently i wanna use viewset and auth, and generating token using obtainauthtoken via apiview, but it is returning error 'ObtainAuthToken' object has no attribute 'request' How to solved it? This is the version that i use Django==3.1.2 djangorestframework==3.12.1 The Code class LoginViewSet(viewsets.ViewSet): """Checks email and password and returns an auth token.""" serializer_class = AuthTokenSerializer def create(self, request): """Use the ObtainAuthToken APIView to validate and create a token.""" return ObtainAuthToken().post(request) -
I am getting an additional message after I ran server of windows shell
Though I am successfully able to run my server from shell but I also got one more message with that . I am attaching the message below. Help me figure it out what it really wants to say and will it create any problems in the future for me? [10/Oct/2020 05:11:37] "GET / HTTP/1.1" 200 16348 [10/Oct/2020 05:11:37] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [10/Oct/2020 05:11:37] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304 [10/Oct/2020 05:11:37] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348 [10/Oct/2020 05:11:37] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564 Not Found: /favicon.ico [10/Oct/2020 05:11:37] "GET /favicon.ico HTTP/1.1" 404 1978 -
Exclude records on manytomany relationship in Django
I have two models with a many to many relationship as shown: class Season(models.Model): name = models.CharField(max_length=255) total_weeks = models.IntegerField() active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class League(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=10, null=True) admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='admin_id') users = models.ManyToManyField(settings.AUTH_USER_MODEL) season_set = models.ManyToManyField(Season, through='LeagueSeason') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.code = uuid.uuid4().hex[:6].upper() super(League, self).save(*args, **kwargs) class LeagueSeason(models.Model): GANADOR = 1 RESULTADO_EXACTO = 2 Type = ( (GANADOR, 'Escoger ganador'), (RESULTADO_EXACTO, 'Escoger resultado exacto'), ) league = models.ForeignKey(League, on_delete=models.PROTECT, related_name='leagues_set') season = models.ForeignKey(Season, on_delete=models.PROTECT, related_name='season_set') season_type = models.IntegerField(choices=Type, default=GANADOR) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "leagues_seasons" def __str__(self): return 'League {} - {}'.format(self.league.name, self.season.name) My season serializers are like this: class LeagueSeasonSerializer(serializers.ModelSerializer): class Meta: model = LeagueSeason fields = [ 'league_id', 'season_type' ] class SeasonsSerializer(serializers.ModelSerializer): season_set = LeagueSeasonSerializer(many = True) class Meta: model = Season fields = '__all__' All is good and fine, but when I make a request /league/7/seasons I get this result: [ { "id": 1, "season_set": [ { "league_id": 7, "season_type": 1 }, { "league_id": 8, "season_type": 2 } ], "name": "2020 Season", "total_weeks": 21, … -
smtplib.SMTPAuthenticationError in Django with pythonanywhere
I have made a little Django app which I plan to use on a real website here. Register an account. A dummy account if you want, log out and click on the link to reset your password. If you enter in your email, You will get an error like this First of all, I don't want to see this error from pythonanywhere. I want my own custom 500 InternalServerError which is this one: I don't know why I get an error because everything works fine on the localhost. So what I really wanted to do is notify the staff users on that are registered about an InternalServerError like so def error_500_view(request): staff_members = [i.email for i in Person.objects.all() if i.is_staff] send_mail( '500 Error', 'There was an InternalServerError in our website. Let\'s fix it!', 'testkenny00@gmail.com', staff_members, fail_silently=False, ) context = { 'title': 'InternalServerError' } return render(request, '500.html', context) But that gave me an smtplib.SMTPAuthenticationError. Again, this also works on the localhost. The registered staff users get an email from the localhost that there is an 500 error. When I hosted this on PythonAnywhere I got this smtplib.SMTPAuthenticationError. -
Django createview creates extra instance without foreign keys
I am using Django createview to create Bid items in an auction site. The createview will create the new object but it creates an extra object instance without the corresponding foreign keys. I am using @staticmethod to to ascertain whether the bid being submitted is indeed the highest bid then create in related Listing. Thank you in advance if you could point what im doing incorrectly. models.py class Bid(TimeStampMixin): """model representing bid obj""" auction = models.ForeignKey( Listing, on_delete=models.SET_NULL, related_name='offer', null=True) bidder = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='bid_user') amount = models.PositiveIntegerField() objects = BidQuerySet.as_manager() def __str__(self): return f"{self.amount} in Listing No: {self.auction.id}" class Meta: ordering = ['amount'] @staticmethod def high_bid(auction, bidder, bid_amount): """util method to ascertain highest bid in auction then create in related auction obj :param auction---listing being bid on, bid__auction :param bidder---user bidding :param amount--- current highest bid """ ###error checks, is auction running? is current bid less than start bid? etc if bid_amount < auction.start_bid: return if (auction.highest_offer and bid_amount < auction.highest_offer.amount): return if bidder.id is auction.user.id: raise PermissionDenied ##after checks create highest bid object in listing model new_high_bid = Bid.objects.create( auction= auction, bidder = bidder, amount = bid_amount ) auction.highest_offer = new_high_bid auction.save() class Listing(TimeStampMixin): user = … -
ModelMultipleChoiceField django and debug mode
i'm trying to implement a ModelMultipleChoiceField in my application, like that: Link model.py class Services(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=300) class Professionals_Services(models.Model): professional = models.ForeignKey(User, on_delete=models.CASCADE) service = models.ForeignKey(Services, on_delete=models.CASCADE) form.py class ProfileServicesUpdateForm(forms.ModelForm): service = forms.ModelMultipleChoiceField(required=False, queryset=Services.objects.all()) class Meta: model = Professionals_Services fields = ['service'] def clean(self): # this condition only if the POST data is cleaned, right? cleaned_data = super(ProfileServicesUpdateForm, self).clean() print(cleaned_data.get('service')) view.py class EditProfileServicesView(CreateView): model = Professionals_Services form_class = ProfileServicesUpdateForm context_object_name = 'services' template_name = 'accounts/edit-profile.html' @method_decorator(login_required(login_url=reverse_lazy('professionals:login'))) def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): form = self.form_class(data=request.POST) if form.is_valid(): services = form.save(commit=False) services.save() html <select class="ui search fluid dropdown" multiple="" name="service" id="id_service"> {% for service in services_list %} <option value="{{ service.id }}">{{ service.type }}</option> {% endfor %} </select> For development i'm using Pycham Professionals(latest version) with docker, when i run the application and i try to make a POST the answer is: Cannot assign "<QuerySet [<Services: Services object (2)>, <Services: Services object (5)>, <Services: Services object (6)>, <Services: Services object (7)>]>": "Professionals_Services.service" must be a "Services" instance. But if i run the application in debug mode and with a breakpoints on the if form.is_valid(): the application works fine That's because … -
Django self referencing many-to-many model
I have a simple Django Jobs model with two fields; applicants and applicants_selected. "applicants" is a many to many relationship to the users model. I want "applicants_selected" to be a many to many relationship to the applicants field of the same model For Example: class Job(models.Model): applicants = models.ManyToManyField('User', blank=True) selected_applicants = models.ManyToManyField('Self.applicants', blank=True) What's the best way to do this? Thanks -
Getting data in Django sent via ajax
I have an array of objects in JS: var users = [ {name: "Amir", age: 22}, {name: "James", age: 12}, ] and suppose I have a view in Django that just create to iterate over users array: def print_users(request): for user in users: print(user.name, user.age) But I send data using Ajax in Jquery in the way down below: var parameters = { "users": users, "csrfmiddlewaretoken": CSRFToken }; $.post("http://localhost:8000/users/print", parameters).done(function(data, statusText){ console.log(data, statusText); }); The PROBLEM comes in the view, I can't fetch data in the shape that it is. I get a queryset like this when I print(request.POST): <QueryDict: {'users[0][name]': ['Amir'], 'users[0][age]': ['22'], 'users[1][name]': ['James'], 'users[1][age]': ['12'],'csrfmiddlewaretoken': ['ZpcfFKppuiBZNtHAjcnKSuyvrtC7YNiUGcd6yFvfMLQMD0LemCjfFv5tPptNgu9t']}> It just like iterates over it, I want users in shape of Array. How can I do it? What is the problem? -
social-auth-app-django and AUTH_USER_MODEL
When I built the Django /api about three years ago, it was built on a legacy database that used a users table. For this, I did not extend the default Django auth_user model, but replaced it altogether with AUTH_USER_MODEl = 'authentication.User. Now I'm trying to implement Azure AD authentication into the web app using social-auth-app-django. I'm finding when I run the migrations I get a: $ ./manage.py migrate social_django Operations to perform: Apply all migrations: social_django Running migrations: Applying social_django.0001_initial...Traceback (most recent call last): File "/Users/eox-dev/Projects/current/company/company-app/api/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "Users" does not exist Which I believe is associated with not using, nor extending, the auth_user model. Is there a way to get the library to use AUTH_USER_MODEL? -
Issues with modifying users in a multi-tenant app
I am creating a multi tenant app with isolated schema using 'django-tenant' and I am having issues with modifying the user model that comes by default with django. I tried using "django-tenant-users" but I think it's not compatible with Django 3 and Python 3.7 as I get errors and I couldn't really find a solution to them. Besides that there's nothing else special. I was trying to create a user class like that: class User(AbstractUser): pass But even with that my app couldn't migrate (I am using migrate_schemas command) Maybe there's something else that django has that will help me with modifying User class for it to be compatible with different schemas and all that. Will be really thankful for any hints. -
Django translation using non-English language as default
I've used two language in my web app; English and Russian. I've added settings as LANGUAGE_CODE = 'ru' LANGUAGES = [ ('ru', gettext('русский')), ('en', gettext('English')), ] And added 'django.middleware.locale.LocaleMiddleware', Everything is working fine. No problem with translations. But the problem is, google is indexing my website without language code, for example "mysite.com". Which is simple. When a user clicks on that link it's rendering English template instead of Russian. Then user needs to change it into Russian by using a language chooser of my website. It's happening even from incognito window. I want that user will see russian first. (btw, i'm testing it from outside of russia). I've read language preferences and I think django preferring Accept-Language HTTP header. Because there is no language code in url by google index. and there is no django_language cookie for the first time visit in this website. Is there any way so an user will redirect to russian translation first, then he can choose the language he prefer. -
Large file upload with django and nginx
File sizes of 100MB are getting uploaded but over that, I get an error saying nginx 504 gateway error. Here are the current configuration, These are present in nginx client_max_body_size 200M; proxy_connect_timeout 1200s; proxy_send_timeout 1200s; proxy_read_timeout 1200s; fastcgi_send_timeout 1200s; fastcgi_read_timeout 1200s; gunicorn.conf.py import multiprocessing import greenlet print(greenlet.__version__) bind = "0.0.0.0:8000" print("Binding on : ", bind) workers = multiprocessing.cpu_count() * 2 + 1 print("Spawned :", workers, " workers") worker_class = "gevent" print("Using ", worker_class, " worker class") timeout = 1200 I'm running my django app and nginx as separate docker containers. Here are the solutions that I've tried. Changed gunicorn timeout to 2400 Changed the following in nginx config client_max_body_size 200M; proxy_connect_timeout 1600s; proxy_send_timeout 1600s; proxy_read_timeout 1600s; fastcgi_send_timeout 1600s; fastcgi_read_timeout 1600s; I checked the networks tab and request send was at 44seconds and waiting ws at 4.02minutes and then I got the Gateway timeout 504 error. -
How to make `<p>` display: inline after linebreak filter?
I have this in my template: {{ doc.description|linebreaks }} <a href="#">Edit</a> because the string has linebreaks inside that I want to display. Problem is, I want the Edit button to be displayed inline with the string, and the linebreak filter automatically applies <p></p> to the string. How do I make this <p> display: inline? (I need to add class="d-inline" as I am using bootstrap) -
Serializer removing one to many relationship in Django
When I try to attach photos to a pet the serializer is removing the attachment, I'm getting attachment :['This field is required']. My code: models.py class Pet(models.Model): pet_id = models.UUIDField('pet uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) name = models.CharField('Pet name', max_length=255, null=False, blank=False) class Attachment(models.Model): attachment_id = models.UUIDField('attachment uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) pet_id = models.ForeignKey(Pet, on_delete=models.CASCADE) name = models.FileField(upload_to='photos/', null=False, blank=False) upload_at = models.DateTimeField('Time it was uploaded', max_length=50, null=False, blank=False ) serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ('name','upload_at') class PetSerializer(serializers.ModelSerializer): attachment = AttachmentSerializer(source='attachment_set', many=True) class Meta: model = Pet fields = ('pet_id','name', 'attachment') # because this: # https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers def create(self, validated_data): attachments = validated_data.pop('attachment') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet=pet, **att) return pet views.py def create_pet(self, request): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return Response({'error':serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED) if on PetSerializer I do attachment = AttachmentSerializer(many=True, source='attachment_set', required=False) there is no problem with the attachment but I need the attachments. Also I have done in the models.py on the Attachment pet_id = models.ForeignKey(Pet, related_name='attachments', on_delete=models.CASCADE) and the serializers PetSerializer: class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = ('pet_id','name', 'attachments') # because this: # https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers def create(self, validated_data): attachments = validated_data.pop('attachment') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet=pet, … -
FeinCMS: type object 'ReportForm' has no attribute '_feincms_content_types'
FeinCms was working fine with my old django-1.8 But when I did upgrade it to django-2.0, I got this error. I'm just stuck here. models: class MyForm(create_base_model()): name = models.CharField(max_length=255, default='New Report', unique=True) title = models.CharField(max_length=255) # Attach content types to Report report = ReportForm() report.register_regions( ('main', 'Main content'), ) map(report.create_content_type, CONTENT_TYPES) # CONTENT_TYPES are my custom content types admin: from feincms.admin.item_editor import ItemEditor admin.site.register(MyForm, ItemEditor) -
how to run static files in pythonanywhere hosting?
I'm trying to upload my project via pythonanywhere but I always get failed to load static files I tried to download it by the static files section of web tab that exists into pythonanywhere and also I got failed you can see what I did here, I will show you all details that I did to help you to understand what could give me the help through it: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATIC_ROOT = "/home/abdelhamedabdin96/website/website/static/index" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # MAIN_DIR = os.path.dirname(os.path.dirname(__file__)) # STATICFILES_DIRS = ( # os.path.join(MAIN_DIR, 'static'), # ) and in urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)